es6.js 4.7 MB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969229702297122972229732297422975229762297722978229792298022981229822298322984229852298622987229882298922990229912299222993229942299522996229972299822999230002300123002230032300423005230062300723008230092301023011230122301323014230152301623017230182301923020230212302223023230242302523026230272302823029230302303123032230332303423035230362303723038230392304023041230422304323044230452304623047230482304923050230512305223053230542305523056230572305823059230602306123062230632306423065230662306723068230692307023071230722307323074230752307623077230782307923080230812308223083230842308523086230872308823089230902309123092230932309423095230962309723098230992310023101231022310323104231052310623107231082310923110231112311223113231142311523116231172311823119231202312123122231232312423125231262312723128231292313023131231322313323134231352313623137231382313923140231412314223143231442314523146231472314823149231502315123152231532315423155231562315723158231592316023161231622316323164231652316623167231682316923170231712317223173231742317523176231772317823179231802318123182231832318423185231862318723188231892319023191231922319323194231952319623197231982319923200232012320223203232042320523206232072320823209232102321123212232132321423215232162321723218232192322023221232222322323224232252322623227232282322923230232312323223233232342323523236232372323823239232402324123242232432324423245232462324723248232492325023251232522325323254232552325623257232582325923260232612326223263232642326523266232672326823269232702327123272232732327423275232762327723278232792328023281232822328323284232852328623287232882328923290232912329223293232942329523296232972329823299233002330123302233032330423305233062330723308233092331023311233122331323314233152331623317233182331923320233212332223323233242332523326233272332823329233302333123332233332333423335233362333723338233392334023341233422334323344233452334623347233482334923350233512335223353233542335523356233572335823359233602336123362233632336423365233662336723368233692337023371233722337323374233752337623377233782337923380233812338223383233842338523386233872338823389233902339123392233932339423395233962339723398233992340023401234022340323404234052340623407234082340923410234112341223413234142341523416234172341823419234202342123422234232342423425234262342723428234292343023431234322343323434234352343623437234382343923440234412344223443234442344523446234472344823449234502345123452234532345423455234562345723458234592346023461234622346323464234652346623467234682346923470234712347223473234742347523476234772347823479234802348123482234832348423485234862348723488234892349023491234922349323494234952349623497234982349923500235012350223503235042350523506235072350823509235102351123512235132351423515235162351723518235192352023521235222352323524235252352623527235282352923530235312353223533235342353523536235372353823539235402354123542235432354423545235462354723548235492355023551235522355323554235552355623557235582355923560235612356223563235642356523566235672356823569235702357123572235732357423575235762357723578235792358023581235822358323584235852358623587235882358923590235912359223593235942359523596235972359823599236002360123602236032360423605236062360723608236092361023611236122361323614236152361623617236182361923620236212362223623236242362523626236272362823629236302363123632236332363423635236362363723638236392364023641236422364323644236452364623647236482364923650236512365223653236542365523656236572365823659236602366123662236632366423665236662366723668236692367023671236722367323674236752367623677236782367923680236812368223683236842368523686236872368823689236902369123692236932369423695236962369723698236992370023701237022370323704237052370623707237082370923710237112371223713237142371523716237172371823719237202372123722237232372423725237262372723728237292373023731237322373323734237352373623737237382373923740237412374223743237442374523746237472374823749237502375123752237532375423755237562375723758237592376023761237622376323764237652376623767237682376923770237712377223773237742377523776237772377823779237802378123782237832378423785237862378723788237892379023791237922379323794237952379623797237982379923800238012380223803238042380523806238072380823809238102381123812238132381423815238162381723818238192382023821238222382323824238252382623827238282382923830238312383223833238342383523836238372383823839238402384123842238432384423845238462384723848238492385023851238522385323854238552385623857238582385923860238612386223863238642386523866238672386823869238702387123872238732387423875238762387723878238792388023881238822388323884238852388623887238882388923890238912389223893238942389523896238972389823899239002390123902239032390423905239062390723908239092391023911239122391323914239152391623917239182391923920239212392223923239242392523926239272392823929239302393123932239332393423935239362393723938239392394023941239422394323944239452394623947239482394923950239512395223953239542395523956239572395823959239602396123962239632396423965239662396723968239692397023971239722397323974239752397623977239782397923980239812398223983239842398523986239872398823989239902399123992239932399423995239962399723998239992400024001240022400324004240052400624007240082400924010240112401224013240142401524016240172401824019240202402124022240232402424025240262402724028240292403024031240322403324034240352403624037240382403924040240412404224043240442404524046240472404824049240502405124052240532405424055240562405724058240592406024061240622406324064240652406624067240682406924070240712407224073240742407524076240772407824079240802408124082240832408424085240862408724088240892409024091240922409324094240952409624097240982409924100241012410224103241042410524106241072410824109241102411124112241132411424115241162411724118241192412024121241222412324124241252412624127241282412924130241312413224133241342413524136241372413824139241402414124142241432414424145241462414724148241492415024151241522415324154241552415624157241582415924160241612416224163241642416524166241672416824169241702417124172241732417424175241762417724178241792418024181241822418324184241852418624187241882418924190241912419224193241942419524196241972419824199242002420124202242032420424205242062420724208242092421024211242122421324214242152421624217242182421924220242212422224223242242422524226242272422824229242302423124232242332423424235242362423724238242392424024241242422424324244242452424624247242482424924250242512425224253242542425524256242572425824259242602426124262242632426424265242662426724268242692427024271242722427324274242752427624277242782427924280242812428224283242842428524286242872428824289242902429124292242932429424295242962429724298242992430024301243022430324304243052430624307243082430924310243112431224313243142431524316243172431824319243202432124322243232432424325243262432724328243292433024331243322433324334243352433624337243382433924340243412434224343243442434524346243472434824349243502435124352243532435424355243562435724358243592436024361243622436324364243652436624367243682436924370243712437224373243742437524376243772437824379243802438124382243832438424385243862438724388243892439024391243922439324394243952439624397243982439924400244012440224403244042440524406244072440824409244102441124412244132441424415244162441724418244192442024421244222442324424244252442624427244282442924430244312443224433244342443524436244372443824439244402444124442244432444424445244462444724448244492445024451244522445324454244552445624457244582445924460244612446224463244642446524466244672446824469244702447124472244732447424475244762447724478244792448024481244822448324484244852448624487244882448924490244912449224493244942449524496244972449824499245002450124502245032450424505245062450724508245092451024511245122451324514245152451624517245182451924520245212452224523245242452524526245272452824529245302453124532245332453424535245362453724538245392454024541245422454324544245452454624547245482454924550245512455224553245542455524556245572455824559245602456124562245632456424565245662456724568245692457024571245722457324574245752457624577245782457924580245812458224583245842458524586245872458824589245902459124592245932459424595245962459724598245992460024601246022460324604246052460624607246082460924610246112461224613246142461524616246172461824619246202462124622246232462424625246262462724628246292463024631246322463324634246352463624637246382463924640246412464224643246442464524646246472464824649246502465124652246532465424655246562465724658246592466024661246622466324664246652466624667246682466924670246712467224673246742467524676246772467824679246802468124682246832468424685246862468724688246892469024691246922469324694246952469624697246982469924700247012470224703247042470524706247072470824709247102471124712247132471424715247162471724718247192472024721247222472324724247252472624727247282472924730247312473224733247342473524736247372473824739247402474124742247432474424745247462474724748247492475024751247522475324754247552475624757247582475924760247612476224763247642476524766247672476824769247702477124772247732477424775247762477724778247792478024781247822478324784247852478624787247882478924790247912479224793247942479524796247972479824799248002480124802248032480424805248062480724808248092481024811248122481324814248152481624817248182481924820248212482224823248242482524826248272482824829248302483124832248332483424835248362483724838248392484024841248422484324844248452484624847248482484924850248512485224853248542485524856248572485824859248602486124862248632486424865248662486724868248692487024871248722487324874248752487624877248782487924880248812488224883248842488524886248872488824889248902489124892248932489424895248962489724898248992490024901249022490324904249052490624907249082490924910249112491224913249142491524916249172491824919249202492124922249232492424925249262492724928249292493024931249322493324934249352493624937249382493924940249412494224943249442494524946249472494824949249502495124952249532495424955249562495724958249592496024961249622496324964249652496624967249682496924970249712497224973249742497524976249772497824979249802498124982249832498424985249862498724988249892499024991249922499324994249952499624997249982499925000250012500225003250042500525006250072500825009250102501125012250132501425015250162501725018250192502025021250222502325024250252502625027250282502925030250312503225033250342503525036250372503825039250402504125042250432504425045250462504725048250492505025051250522505325054250552505625057250582505925060250612506225063250642506525066250672506825069250702507125072250732507425075250762507725078250792508025081250822508325084250852508625087250882508925090250912509225093250942509525096250972509825099251002510125102251032510425105251062510725108251092511025111251122511325114251152511625117251182511925120251212512225123251242512525126251272512825129251302513125132251332513425135251362513725138251392514025141251422514325144251452514625147251482514925150251512515225153251542515525156251572515825159251602516125162251632516425165251662516725168251692517025171251722517325174251752517625177251782517925180251812518225183251842518525186251872518825189251902519125192251932519425195251962519725198251992520025201252022520325204252052520625207252082520925210252112521225213252142521525216252172521825219252202522125222252232522425225252262522725228252292523025231252322523325234252352523625237252382523925240252412524225243252442524525246252472524825249252502525125252252532525425255252562525725258252592526025261252622526325264252652526625267252682526925270252712527225273252742527525276252772527825279252802528125282252832528425285252862528725288252892529025291252922529325294252952529625297252982529925300253012530225303253042530525306253072530825309253102531125312253132531425315253162531725318253192532025321253222532325324253252532625327253282532925330253312533225333253342533525336253372533825339253402534125342253432534425345253462534725348253492535025351253522535325354253552535625357253582535925360253612536225363253642536525366253672536825369253702537125372253732537425375253762537725378253792538025381253822538325384253852538625387253882538925390253912539225393253942539525396253972539825399254002540125402254032540425405254062540725408254092541025411254122541325414254152541625417254182541925420254212542225423254242542525426254272542825429254302543125432254332543425435254362543725438254392544025441254422544325444254452544625447254482544925450254512545225453254542545525456254572545825459254602546125462254632546425465254662546725468254692547025471254722547325474254752547625477254782547925480254812548225483254842548525486254872548825489254902549125492254932549425495254962549725498254992550025501255022550325504255052550625507255082550925510255112551225513255142551525516255172551825519255202552125522255232552425525255262552725528255292553025531255322553325534255352553625537255382553925540255412554225543255442554525546255472554825549255502555125552255532555425555255562555725558255592556025561255622556325564255652556625567255682556925570255712557225573255742557525576255772557825579255802558125582255832558425585255862558725588255892559025591255922559325594255952559625597255982559925600256012560225603256042560525606256072560825609256102561125612256132561425615256162561725618256192562025621256222562325624256252562625627256282562925630256312563225633256342563525636256372563825639256402564125642256432564425645256462564725648256492565025651256522565325654256552565625657256582565925660256612566225663256642566525666256672566825669256702567125672256732567425675256762567725678256792568025681256822568325684256852568625687256882568925690256912569225693256942569525696256972569825699257002570125702257032570425705257062570725708257092571025711257122571325714257152571625717257182571925720257212572225723257242572525726257272572825729257302573125732257332573425735257362573725738257392574025741257422574325744257452574625747257482574925750257512575225753257542575525756257572575825759257602576125762257632576425765257662576725768257692577025771257722577325774257752577625777257782577925780257812578225783257842578525786257872578825789257902579125792257932579425795257962579725798257992580025801258022580325804258052580625807258082580925810258112581225813258142581525816258172581825819258202582125822258232582425825258262582725828258292583025831258322583325834258352583625837258382583925840258412584225843258442584525846258472584825849258502585125852258532585425855258562585725858258592586025861258622586325864258652586625867258682586925870258712587225873258742587525876258772587825879258802588125882258832588425885258862588725888258892589025891258922589325894258952589625897258982589925900259012590225903259042590525906259072590825909259102591125912259132591425915259162591725918259192592025921259222592325924259252592625927259282592925930259312593225933259342593525936259372593825939259402594125942259432594425945259462594725948259492595025951259522595325954259552595625957259582595925960259612596225963259642596525966259672596825969259702597125972259732597425975259762597725978259792598025981259822598325984259852598625987259882598925990259912599225993259942599525996259972599825999260002600126002260032600426005260062600726008260092601026011260122601326014260152601626017260182601926020260212602226023260242602526026260272602826029260302603126032260332603426035260362603726038260392604026041260422604326044260452604626047260482604926050260512605226053260542605526056260572605826059260602606126062260632606426065260662606726068260692607026071260722607326074260752607626077260782607926080260812608226083260842608526086260872608826089260902609126092260932609426095260962609726098260992610026101261022610326104261052610626107261082610926110261112611226113261142611526116261172611826119261202612126122261232612426125261262612726128261292613026131261322613326134261352613626137261382613926140261412614226143261442614526146261472614826149261502615126152261532615426155261562615726158261592616026161261622616326164261652616626167261682616926170261712617226173261742617526176261772617826179261802618126182261832618426185261862618726188261892619026191261922619326194261952619626197261982619926200262012620226203262042620526206262072620826209262102621126212262132621426215262162621726218262192622026221262222622326224262252622626227262282622926230262312623226233262342623526236262372623826239262402624126242262432624426245262462624726248262492625026251262522625326254262552625626257262582625926260262612626226263262642626526266262672626826269262702627126272262732627426275262762627726278262792628026281262822628326284262852628626287262882628926290262912629226293262942629526296262972629826299263002630126302263032630426305263062630726308263092631026311263122631326314263152631626317263182631926320263212632226323263242632526326263272632826329263302633126332263332633426335263362633726338263392634026341263422634326344263452634626347263482634926350263512635226353263542635526356263572635826359263602636126362263632636426365263662636726368263692637026371263722637326374263752637626377263782637926380263812638226383263842638526386263872638826389263902639126392263932639426395263962639726398263992640026401264022640326404264052640626407264082640926410264112641226413264142641526416264172641826419264202642126422264232642426425264262642726428264292643026431264322643326434264352643626437264382643926440264412644226443264442644526446264472644826449264502645126452264532645426455264562645726458264592646026461264622646326464264652646626467264682646926470264712647226473264742647526476264772647826479264802648126482264832648426485264862648726488264892649026491264922649326494264952649626497264982649926500265012650226503265042650526506265072650826509265102651126512265132651426515265162651726518265192652026521265222652326524265252652626527265282652926530265312653226533265342653526536265372653826539265402654126542265432654426545265462654726548265492655026551265522655326554265552655626557265582655926560265612656226563265642656526566265672656826569265702657126572265732657426575265762657726578265792658026581265822658326584265852658626587265882658926590265912659226593265942659526596265972659826599266002660126602266032660426605266062660726608266092661026611266122661326614266152661626617266182661926620266212662226623266242662526626266272662826629266302663126632266332663426635266362663726638266392664026641266422664326644266452664626647266482664926650266512665226653266542665526656266572665826659266602666126662266632666426665266662666726668266692667026671266722667326674266752667626677266782667926680266812668226683266842668526686266872668826689266902669126692266932669426695266962669726698266992670026701267022670326704267052670626707267082670926710267112671226713267142671526716267172671826719267202672126722267232672426725267262672726728267292673026731267322673326734267352673626737267382673926740267412674226743267442674526746267472674826749267502675126752267532675426755267562675726758267592676026761267622676326764267652676626767267682676926770267712677226773267742677526776267772677826779267802678126782267832678426785267862678726788267892679026791267922679326794267952679626797267982679926800268012680226803268042680526806268072680826809268102681126812268132681426815268162681726818268192682026821268222682326824268252682626827268282682926830268312683226833268342683526836268372683826839268402684126842268432684426845268462684726848268492685026851268522685326854268552685626857268582685926860268612686226863268642686526866268672686826869268702687126872268732687426875268762687726878268792688026881268822688326884268852688626887268882688926890268912689226893268942689526896268972689826899269002690126902269032690426905269062690726908269092691026911269122691326914269152691626917269182691926920269212692226923269242692526926269272692826929269302693126932269332693426935269362693726938269392694026941269422694326944269452694626947269482694926950269512695226953269542695526956269572695826959269602696126962269632696426965269662696726968269692697026971269722697326974269752697626977269782697926980269812698226983269842698526986269872698826989269902699126992269932699426995269962699726998269992700027001270022700327004270052700627007270082700927010270112701227013270142701527016270172701827019270202702127022270232702427025270262702727028270292703027031270322703327034270352703627037270382703927040270412704227043270442704527046270472704827049270502705127052270532705427055270562705727058270592706027061270622706327064270652706627067270682706927070270712707227073270742707527076270772707827079270802708127082270832708427085270862708727088270892709027091270922709327094270952709627097270982709927100271012710227103271042710527106271072710827109271102711127112271132711427115271162711727118271192712027121271222712327124271252712627127271282712927130271312713227133271342713527136271372713827139271402714127142271432714427145271462714727148271492715027151271522715327154271552715627157271582715927160271612716227163271642716527166271672716827169271702717127172271732717427175271762717727178271792718027181271822718327184271852718627187271882718927190271912719227193271942719527196271972719827199272002720127202272032720427205272062720727208272092721027211272122721327214272152721627217272182721927220272212722227223272242722527226272272722827229272302723127232272332723427235272362723727238272392724027241272422724327244272452724627247272482724927250272512725227253272542725527256272572725827259272602726127262272632726427265272662726727268272692727027271272722727327274272752727627277272782727927280272812728227283272842728527286272872728827289272902729127292272932729427295272962729727298272992730027301273022730327304273052730627307273082730927310273112731227313273142731527316273172731827319273202732127322273232732427325273262732727328273292733027331273322733327334273352733627337273382733927340273412734227343273442734527346273472734827349273502735127352273532735427355273562735727358273592736027361273622736327364273652736627367273682736927370273712737227373273742737527376273772737827379273802738127382273832738427385273862738727388273892739027391273922739327394273952739627397273982739927400274012740227403274042740527406274072740827409274102741127412274132741427415274162741727418274192742027421274222742327424274252742627427274282742927430274312743227433274342743527436274372743827439274402744127442274432744427445274462744727448274492745027451274522745327454274552745627457274582745927460274612746227463274642746527466274672746827469274702747127472274732747427475274762747727478274792748027481274822748327484274852748627487274882748927490274912749227493274942749527496274972749827499275002750127502275032750427505275062750727508275092751027511275122751327514275152751627517275182751927520275212752227523275242752527526275272752827529275302753127532275332753427535275362753727538275392754027541275422754327544275452754627547275482754927550275512755227553275542755527556275572755827559275602756127562275632756427565275662756727568275692757027571275722757327574275752757627577275782757927580275812758227583275842758527586275872758827589275902759127592275932759427595275962759727598275992760027601276022760327604276052760627607276082760927610276112761227613276142761527616276172761827619276202762127622276232762427625276262762727628276292763027631276322763327634276352763627637276382763927640276412764227643276442764527646276472764827649276502765127652276532765427655276562765727658276592766027661276622766327664276652766627667276682766927670276712767227673276742767527676276772767827679276802768127682276832768427685276862768727688276892769027691276922769327694276952769627697276982769927700277012770227703277042770527706277072770827709277102771127712277132771427715277162771727718277192772027721277222772327724277252772627727277282772927730277312773227733277342773527736277372773827739277402774127742277432774427745277462774727748277492775027751277522775327754277552775627757277582775927760277612776227763277642776527766277672776827769277702777127772277732777427775277762777727778277792778027781277822778327784277852778627787277882778927790277912779227793277942779527796277972779827799278002780127802278032780427805278062780727808278092781027811278122781327814278152781627817278182781927820278212782227823278242782527826278272782827829278302783127832278332783427835278362783727838278392784027841278422784327844278452784627847278482784927850278512785227853278542785527856278572785827859278602786127862278632786427865278662786727868278692787027871278722787327874278752787627877278782787927880278812788227883278842788527886278872788827889278902789127892278932789427895278962789727898278992790027901279022790327904279052790627907279082790927910279112791227913279142791527916279172791827919279202792127922279232792427925279262792727928279292793027931279322793327934279352793627937279382793927940279412794227943279442794527946279472794827949279502795127952279532795427955279562795727958279592796027961279622796327964279652796627967279682796927970279712797227973279742797527976279772797827979279802798127982279832798427985279862798727988279892799027991279922799327994279952799627997279982799928000280012800228003280042800528006280072800828009280102801128012280132801428015280162801728018280192802028021280222802328024280252802628027280282802928030280312803228033280342803528036280372803828039280402804128042280432804428045280462804728048280492805028051280522805328054280552805628057280582805928060280612806228063280642806528066280672806828069280702807128072280732807428075280762807728078280792808028081280822808328084280852808628087280882808928090280912809228093280942809528096280972809828099281002810128102281032810428105281062810728108281092811028111281122811328114281152811628117281182811928120281212812228123281242812528126281272812828129281302813128132281332813428135281362813728138281392814028141281422814328144281452814628147281482814928150281512815228153281542815528156281572815828159281602816128162281632816428165281662816728168281692817028171281722817328174281752817628177281782817928180281812818228183281842818528186281872818828189281902819128192281932819428195281962819728198281992820028201282022820328204282052820628207282082820928210282112821228213282142821528216282172821828219282202822128222282232822428225282262822728228282292823028231282322823328234282352823628237282382823928240282412824228243282442824528246282472824828249282502825128252282532825428255282562825728258282592826028261282622826328264282652826628267282682826928270282712827228273282742827528276282772827828279282802828128282282832828428285282862828728288282892829028291282922829328294282952829628297282982829928300283012830228303283042830528306283072830828309283102831128312283132831428315283162831728318283192832028321283222832328324283252832628327283282832928330283312833228333283342833528336283372833828339283402834128342283432834428345283462834728348283492835028351283522835328354283552835628357283582835928360283612836228363283642836528366283672836828369283702837128372283732837428375283762837728378283792838028381283822838328384283852838628387283882838928390283912839228393283942839528396283972839828399284002840128402284032840428405284062840728408284092841028411284122841328414284152841628417284182841928420284212842228423284242842528426284272842828429284302843128432284332843428435284362843728438284392844028441284422844328444284452844628447284482844928450284512845228453284542845528456284572845828459284602846128462284632846428465284662846728468284692847028471284722847328474284752847628477284782847928480284812848228483284842848528486284872848828489284902849128492284932849428495284962849728498284992850028501285022850328504285052850628507285082850928510285112851228513285142851528516285172851828519285202852128522285232852428525285262852728528285292853028531285322853328534285352853628537285382853928540285412854228543285442854528546285472854828549285502855128552285532855428555285562855728558285592856028561285622856328564285652856628567285682856928570285712857228573285742857528576285772857828579285802858128582285832858428585285862858728588285892859028591285922859328594285952859628597285982859928600286012860228603286042860528606286072860828609286102861128612286132861428615286162861728618286192862028621286222862328624286252862628627286282862928630286312863228633286342863528636286372863828639286402864128642286432864428645286462864728648286492865028651286522865328654286552865628657286582865928660286612866228663286642866528666286672866828669286702867128672286732867428675286762867728678286792868028681286822868328684286852868628687286882868928690286912869228693286942869528696286972869828699287002870128702287032870428705287062870728708287092871028711287122871328714287152871628717287182871928720287212872228723287242872528726287272872828729287302873128732287332873428735287362873728738287392874028741287422874328744287452874628747287482874928750287512875228753287542875528756287572875828759287602876128762287632876428765287662876728768287692877028771287722877328774287752877628777287782877928780287812878228783287842878528786287872878828789287902879128792287932879428795287962879728798287992880028801288022880328804288052880628807288082880928810288112881228813288142881528816288172881828819288202882128822288232882428825288262882728828288292883028831288322883328834288352883628837288382883928840288412884228843288442884528846288472884828849288502885128852288532885428855288562885728858288592886028861288622886328864288652886628867288682886928870288712887228873288742887528876288772887828879288802888128882288832888428885288862888728888288892889028891288922889328894288952889628897288982889928900289012890228903289042890528906289072890828909289102891128912289132891428915289162891728918289192892028921289222892328924289252892628927289282892928930289312893228933289342893528936289372893828939289402894128942289432894428945289462894728948289492895028951289522895328954289552895628957289582895928960289612896228963289642896528966289672896828969289702897128972289732897428975289762897728978289792898028981289822898328984289852898628987289882898928990289912899228993289942899528996289972899828999290002900129002290032900429005290062900729008290092901029011290122901329014290152901629017290182901929020290212902229023290242902529026290272902829029290302903129032290332903429035290362903729038290392904029041290422904329044290452904629047290482904929050290512905229053290542905529056290572905829059290602906129062290632906429065290662906729068290692907029071290722907329074290752907629077290782907929080290812908229083290842908529086290872908829089290902909129092290932909429095290962909729098290992910029101291022910329104291052910629107291082910929110291112911229113291142911529116291172911829119291202912129122291232912429125291262912729128291292913029131291322913329134291352913629137291382913929140291412914229143291442914529146291472914829149291502915129152291532915429155291562915729158291592916029161291622916329164291652916629167291682916929170291712917229173291742917529176291772917829179291802918129182291832918429185291862918729188291892919029191291922919329194291952919629197291982919929200292012920229203292042920529206292072920829209292102921129212292132921429215292162921729218292192922029221292222922329224292252922629227292282922929230292312923229233292342923529236292372923829239292402924129242292432924429245292462924729248292492925029251292522925329254292552925629257292582925929260292612926229263292642926529266292672926829269292702927129272292732927429275292762927729278292792928029281292822928329284292852928629287292882928929290292912929229293292942929529296292972929829299293002930129302293032930429305293062930729308293092931029311293122931329314293152931629317293182931929320293212932229323293242932529326293272932829329293302933129332293332933429335293362933729338293392934029341293422934329344293452934629347293482934929350293512935229353293542935529356293572935829359293602936129362293632936429365293662936729368293692937029371293722937329374293752937629377293782937929380293812938229383293842938529386293872938829389293902939129392293932939429395293962939729398293992940029401294022940329404294052940629407294082940929410294112941229413294142941529416294172941829419294202942129422294232942429425294262942729428294292943029431294322943329434294352943629437294382943929440294412944229443294442944529446294472944829449294502945129452294532945429455294562945729458294592946029461294622946329464294652946629467294682946929470294712947229473294742947529476294772947829479294802948129482294832948429485294862948729488294892949029491294922949329494294952949629497294982949929500295012950229503295042950529506295072950829509295102951129512295132951429515295162951729518295192952029521295222952329524295252952629527295282952929530295312953229533295342953529536295372953829539295402954129542295432954429545295462954729548295492955029551295522955329554295552955629557295582955929560295612956229563295642956529566295672956829569295702957129572295732957429575295762957729578295792958029581295822958329584295852958629587295882958929590295912959229593295942959529596295972959829599296002960129602296032960429605296062960729608296092961029611296122961329614296152961629617296182961929620296212962229623296242962529626296272962829629296302963129632296332963429635296362963729638296392964029641296422964329644296452964629647296482964929650296512965229653296542965529656296572965829659296602966129662296632966429665296662966729668296692967029671296722967329674296752967629677296782967929680296812968229683296842968529686296872968829689296902969129692296932969429695296962969729698296992970029701297022970329704297052970629707297082970929710297112971229713297142971529716297172971829719297202972129722297232972429725297262972729728297292973029731297322973329734297352973629737297382973929740297412974229743297442974529746297472974829749297502975129752297532975429755297562975729758297592976029761297622976329764297652976629767297682976929770297712977229773297742977529776297772977829779297802978129782297832978429785297862978729788297892979029791297922979329794297952979629797297982979929800298012980229803298042980529806298072980829809298102981129812298132981429815298162981729818298192982029821298222982329824298252982629827298282982929830298312983229833298342983529836298372983829839298402984129842298432984429845298462984729848298492985029851298522985329854298552985629857298582985929860298612986229863298642986529866298672986829869298702987129872298732987429875298762987729878298792988029881298822988329884298852988629887298882988929890298912989229893298942989529896298972989829899299002990129902299032990429905299062990729908299092991029911299122991329914299152991629917299182991929920299212992229923299242992529926299272992829929299302993129932299332993429935299362993729938299392994029941299422994329944299452994629947299482994929950299512995229953299542995529956299572995829959299602996129962299632996429965299662996729968299692997029971299722997329974299752997629977299782997929980299812998229983299842998529986299872998829989299902999129992299932999429995299962999729998299993000030001300023000330004300053000630007300083000930010300113001230013300143001530016300173001830019300203002130022300233002430025300263002730028300293003030031300323003330034300353003630037300383003930040300413004230043300443004530046300473004830049300503005130052300533005430055300563005730058300593006030061300623006330064300653006630067300683006930070300713007230073300743007530076300773007830079300803008130082300833008430085300863008730088300893009030091300923009330094300953009630097300983009930100301013010230103301043010530106301073010830109301103011130112301133011430115301163011730118301193012030121301223012330124301253012630127301283012930130301313013230133301343013530136301373013830139301403014130142301433014430145301463014730148301493015030151301523015330154301553015630157301583015930160301613016230163301643016530166301673016830169301703017130172301733017430175301763017730178301793018030181301823018330184301853018630187301883018930190301913019230193301943019530196301973019830199302003020130202302033020430205302063020730208302093021030211302123021330214302153021630217302183021930220302213022230223302243022530226302273022830229302303023130232302333023430235302363023730238302393024030241302423024330244302453024630247302483024930250302513025230253302543025530256302573025830259302603026130262302633026430265302663026730268302693027030271302723027330274302753027630277302783027930280302813028230283302843028530286302873028830289302903029130292302933029430295302963029730298302993030030301303023030330304303053030630307303083030930310303113031230313303143031530316303173031830319303203032130322303233032430325303263032730328303293033030331303323033330334303353033630337303383033930340303413034230343303443034530346303473034830349303503035130352303533035430355303563035730358303593036030361303623036330364303653036630367303683036930370303713037230373303743037530376303773037830379303803038130382303833038430385303863038730388303893039030391303923039330394303953039630397303983039930400304013040230403304043040530406304073040830409304103041130412304133041430415304163041730418304193042030421304223042330424304253042630427304283042930430304313043230433304343043530436304373043830439304403044130442304433044430445304463044730448304493045030451304523045330454304553045630457304583045930460304613046230463304643046530466304673046830469304703047130472304733047430475304763047730478304793048030481304823048330484304853048630487304883048930490304913049230493304943049530496304973049830499305003050130502305033050430505305063050730508305093051030511305123051330514305153051630517305183051930520305213052230523305243052530526305273052830529305303053130532305333053430535305363053730538305393054030541305423054330544305453054630547305483054930550305513055230553305543055530556305573055830559305603056130562305633056430565305663056730568305693057030571305723057330574305753057630577305783057930580305813058230583305843058530586305873058830589305903059130592305933059430595305963059730598305993060030601306023060330604306053060630607306083060930610306113061230613306143061530616306173061830619306203062130622306233062430625306263062730628306293063030631306323063330634306353063630637306383063930640306413064230643306443064530646306473064830649306503065130652306533065430655306563065730658306593066030661306623066330664306653066630667306683066930670306713067230673306743067530676306773067830679306803068130682306833068430685306863068730688306893069030691306923069330694306953069630697306983069930700307013070230703307043070530706307073070830709307103071130712307133071430715307163071730718307193072030721307223072330724307253072630727307283072930730307313073230733307343073530736307373073830739307403074130742307433074430745307463074730748307493075030751307523075330754307553075630757307583075930760307613076230763307643076530766307673076830769307703077130772307733077430775307763077730778307793078030781307823078330784307853078630787307883078930790307913079230793307943079530796307973079830799308003080130802308033080430805308063080730808308093081030811308123081330814308153081630817308183081930820308213082230823308243082530826308273082830829308303083130832308333083430835308363083730838308393084030841308423084330844308453084630847308483084930850308513085230853308543085530856308573085830859308603086130862308633086430865308663086730868308693087030871308723087330874308753087630877308783087930880308813088230883308843088530886308873088830889308903089130892308933089430895308963089730898308993090030901309023090330904309053090630907309083090930910309113091230913309143091530916309173091830919309203092130922309233092430925309263092730928309293093030931309323093330934309353093630937309383093930940309413094230943309443094530946309473094830949309503095130952309533095430955309563095730958309593096030961309623096330964309653096630967309683096930970309713097230973309743097530976309773097830979309803098130982309833098430985309863098730988309893099030991309923099330994309953099630997309983099931000310013100231003310043100531006310073100831009310103101131012310133101431015310163101731018310193102031021310223102331024310253102631027310283102931030310313103231033310343103531036310373103831039310403104131042310433104431045310463104731048310493105031051310523105331054310553105631057310583105931060310613106231063310643106531066310673106831069310703107131072310733107431075310763107731078310793108031081310823108331084310853108631087310883108931090310913109231093310943109531096310973109831099311003110131102311033110431105311063110731108311093111031111311123111331114311153111631117311183111931120311213112231123311243112531126311273112831129311303113131132311333113431135311363113731138311393114031141311423114331144311453114631147311483114931150311513115231153311543115531156311573115831159311603116131162311633116431165311663116731168311693117031171311723117331174311753117631177311783117931180311813118231183311843118531186311873118831189311903119131192311933119431195311963119731198311993120031201312023120331204312053120631207312083120931210312113121231213312143121531216312173121831219312203122131222312233122431225312263122731228312293123031231312323123331234312353123631237312383123931240312413124231243312443124531246312473124831249312503125131252312533125431255312563125731258312593126031261312623126331264312653126631267312683126931270312713127231273312743127531276312773127831279312803128131282312833128431285312863128731288312893129031291312923129331294312953129631297312983129931300313013130231303313043130531306313073130831309313103131131312313133131431315313163131731318313193132031321313223132331324313253132631327313283132931330313313133231333313343133531336313373133831339313403134131342313433134431345313463134731348313493135031351313523135331354313553135631357313583135931360313613136231363313643136531366313673136831369313703137131372313733137431375313763137731378313793138031381313823138331384313853138631387313883138931390313913139231393313943139531396313973139831399314003140131402314033140431405314063140731408314093141031411314123141331414314153141631417314183141931420314213142231423314243142531426314273142831429314303143131432314333143431435314363143731438314393144031441314423144331444314453144631447314483144931450314513145231453314543145531456314573145831459314603146131462314633146431465314663146731468314693147031471314723147331474314753147631477314783147931480314813148231483314843148531486314873148831489314903149131492314933149431495314963149731498314993150031501315023150331504315053150631507315083150931510315113151231513315143151531516315173151831519315203152131522315233152431525315263152731528315293153031531315323153331534315353153631537315383153931540315413154231543315443154531546315473154831549315503155131552315533155431555315563155731558315593156031561315623156331564315653156631567315683156931570315713157231573315743157531576315773157831579315803158131582315833158431585315863158731588315893159031591315923159331594315953159631597315983159931600316013160231603316043160531606316073160831609316103161131612316133161431615316163161731618316193162031621316223162331624316253162631627316283162931630316313163231633316343163531636316373163831639316403164131642316433164431645316463164731648316493165031651316523165331654316553165631657316583165931660316613166231663316643166531666316673166831669316703167131672316733167431675316763167731678316793168031681316823168331684316853168631687316883168931690316913169231693316943169531696316973169831699317003170131702317033170431705317063170731708317093171031711317123171331714317153171631717317183171931720317213172231723317243172531726317273172831729317303173131732317333173431735317363173731738317393174031741317423174331744317453174631747317483174931750317513175231753317543175531756317573175831759317603176131762317633176431765317663176731768317693177031771317723177331774317753177631777317783177931780317813178231783317843178531786317873178831789317903179131792317933179431795317963179731798317993180031801318023180331804318053180631807318083180931810318113181231813318143181531816318173181831819318203182131822318233182431825318263182731828318293183031831318323183331834318353183631837318383183931840318413184231843318443184531846318473184831849318503185131852318533185431855318563185731858318593186031861318623186331864318653186631867318683186931870318713187231873318743187531876318773187831879318803188131882318833188431885318863188731888318893189031891318923189331894318953189631897318983189931900319013190231903319043190531906319073190831909319103191131912319133191431915319163191731918319193192031921319223192331924319253192631927319283192931930319313193231933319343193531936319373193831939319403194131942319433194431945319463194731948319493195031951319523195331954319553195631957319583195931960319613196231963319643196531966319673196831969319703197131972319733197431975319763197731978319793198031981319823198331984319853198631987319883198931990319913199231993319943199531996319973199831999320003200132002320033200432005320063200732008320093201032011320123201332014320153201632017320183201932020320213202232023320243202532026320273202832029320303203132032320333203432035320363203732038320393204032041320423204332044320453204632047320483204932050320513205232053320543205532056320573205832059320603206132062320633206432065320663206732068320693207032071320723207332074320753207632077320783207932080320813208232083320843208532086320873208832089320903209132092320933209432095320963209732098320993210032101321023210332104321053210632107321083210932110321113211232113321143211532116321173211832119321203212132122321233212432125321263212732128321293213032131321323213332134321353213632137321383213932140321413214232143321443214532146321473214832149321503215132152321533215432155321563215732158321593216032161321623216332164321653216632167321683216932170321713217232173321743217532176321773217832179321803218132182321833218432185321863218732188321893219032191321923219332194321953219632197321983219932200322013220232203322043220532206322073220832209322103221132212322133221432215322163221732218322193222032221322223222332224322253222632227322283222932230322313223232233322343223532236322373223832239322403224132242322433224432245322463224732248322493225032251322523225332254322553225632257322583225932260322613226232263322643226532266322673226832269322703227132272322733227432275322763227732278322793228032281322823228332284322853228632287322883228932290322913229232293322943229532296322973229832299323003230132302323033230432305323063230732308323093231032311323123231332314323153231632317323183231932320323213232232323323243232532326323273232832329323303233132332323333233432335323363233732338323393234032341323423234332344323453234632347323483234932350323513235232353323543235532356323573235832359323603236132362323633236432365323663236732368323693237032371323723237332374323753237632377323783237932380323813238232383323843238532386323873238832389323903239132392323933239432395323963239732398323993240032401324023240332404324053240632407324083240932410324113241232413324143241532416324173241832419324203242132422324233242432425324263242732428324293243032431324323243332434324353243632437324383243932440324413244232443324443244532446324473244832449324503245132452324533245432455324563245732458324593246032461324623246332464324653246632467324683246932470324713247232473324743247532476324773247832479324803248132482324833248432485324863248732488324893249032491324923249332494324953249632497324983249932500325013250232503325043250532506325073250832509325103251132512325133251432515325163251732518325193252032521325223252332524325253252632527325283252932530325313253232533325343253532536325373253832539325403254132542325433254432545325463254732548325493255032551325523255332554325553255632557325583255932560325613256232563325643256532566325673256832569325703257132572325733257432575325763257732578325793258032581325823258332584325853258632587325883258932590325913259232593325943259532596325973259832599326003260132602326033260432605326063260732608326093261032611326123261332614326153261632617326183261932620326213262232623326243262532626326273262832629326303263132632326333263432635326363263732638326393264032641326423264332644326453264632647326483264932650326513265232653326543265532656326573265832659326603266132662326633266432665326663266732668326693267032671326723267332674326753267632677326783267932680326813268232683326843268532686326873268832689326903269132692326933269432695326963269732698326993270032701327023270332704327053270632707327083270932710327113271232713327143271532716327173271832719327203272132722327233272432725327263272732728327293273032731327323273332734327353273632737327383273932740327413274232743327443274532746327473274832749327503275132752327533275432755327563275732758327593276032761327623276332764327653276632767327683276932770327713277232773327743277532776327773277832779327803278132782327833278432785327863278732788327893279032791327923279332794327953279632797327983279932800328013280232803328043280532806328073280832809328103281132812328133281432815328163281732818328193282032821328223282332824328253282632827328283282932830328313283232833328343283532836328373283832839328403284132842328433284432845328463284732848328493285032851328523285332854328553285632857328583285932860328613286232863328643286532866328673286832869328703287132872328733287432875328763287732878328793288032881328823288332884328853288632887328883288932890328913289232893328943289532896328973289832899329003290132902329033290432905329063290732908329093291032911329123291332914329153291632917329183291932920329213292232923329243292532926329273292832929329303293132932329333293432935329363293732938329393294032941329423294332944329453294632947329483294932950329513295232953329543295532956329573295832959329603296132962329633296432965329663296732968329693297032971329723297332974329753297632977329783297932980329813298232983329843298532986329873298832989329903299132992329933299432995329963299732998329993300033001330023300333004330053300633007330083300933010330113301233013330143301533016330173301833019330203302133022330233302433025330263302733028330293303033031330323303333034330353303633037330383303933040330413304233043330443304533046330473304833049330503305133052330533305433055330563305733058330593306033061330623306333064330653306633067330683306933070330713307233073330743307533076330773307833079330803308133082330833308433085330863308733088330893309033091330923309333094330953309633097330983309933100331013310233103331043310533106331073310833109331103311133112331133311433115331163311733118331193312033121331223312333124331253312633127331283312933130331313313233133331343313533136331373313833139331403314133142331433314433145331463314733148331493315033151331523315333154331553315633157331583315933160331613316233163331643316533166331673316833169331703317133172331733317433175331763317733178331793318033181331823318333184331853318633187331883318933190331913319233193331943319533196331973319833199332003320133202332033320433205332063320733208332093321033211332123321333214332153321633217332183321933220332213322233223332243322533226332273322833229332303323133232332333323433235332363323733238332393324033241332423324333244332453324633247332483324933250332513325233253332543325533256332573325833259332603326133262332633326433265332663326733268332693327033271332723327333274332753327633277332783327933280332813328233283332843328533286332873328833289332903329133292332933329433295332963329733298332993330033301333023330333304333053330633307333083330933310333113331233313333143331533316333173331833319333203332133322333233332433325333263332733328333293333033331333323333333334333353333633337333383333933340333413334233343333443334533346333473334833349333503335133352333533335433355333563335733358333593336033361333623336333364333653336633367333683336933370333713337233373333743337533376333773337833379333803338133382333833338433385333863338733388333893339033391333923339333394333953339633397333983339933400334013340233403334043340533406334073340833409334103341133412334133341433415334163341733418334193342033421334223342333424334253342633427334283342933430334313343233433334343343533436334373343833439334403344133442334433344433445334463344733448334493345033451334523345333454334553345633457334583345933460334613346233463334643346533466334673346833469334703347133472334733347433475334763347733478334793348033481334823348333484334853348633487334883348933490334913349233493334943349533496334973349833499335003350133502335033350433505335063350733508335093351033511335123351333514335153351633517335183351933520335213352233523335243352533526335273352833529335303353133532335333353433535335363353733538335393354033541335423354333544335453354633547335483354933550335513355233553335543355533556335573355833559335603356133562335633356433565335663356733568335693357033571335723357333574335753357633577335783357933580335813358233583335843358533586335873358833589335903359133592335933359433595335963359733598335993360033601336023360333604336053360633607336083360933610336113361233613336143361533616336173361833619336203362133622336233362433625336263362733628336293363033631336323363333634336353363633637336383363933640336413364233643336443364533646336473364833649336503365133652336533365433655336563365733658336593366033661336623366333664336653366633667336683366933670336713367233673336743367533676336773367833679336803368133682336833368433685336863368733688336893369033691336923369333694336953369633697336983369933700337013370233703337043370533706337073370833709337103371133712337133371433715337163371733718337193372033721337223372333724337253372633727337283372933730337313373233733337343373533736337373373833739337403374133742337433374433745337463374733748337493375033751337523375333754337553375633757337583375933760337613376233763337643376533766337673376833769337703377133772337733377433775337763377733778337793378033781337823378333784337853378633787337883378933790337913379233793337943379533796337973379833799338003380133802338033380433805338063380733808338093381033811338123381333814338153381633817338183381933820338213382233823338243382533826338273382833829338303383133832338333383433835338363383733838338393384033841338423384333844338453384633847338483384933850338513385233853338543385533856338573385833859338603386133862338633386433865338663386733868338693387033871338723387333874338753387633877338783387933880338813388233883338843388533886338873388833889338903389133892338933389433895338963389733898338993390033901339023390333904339053390633907339083390933910339113391233913339143391533916339173391833919339203392133922339233392433925339263392733928339293393033931339323393333934339353393633937339383393933940339413394233943339443394533946339473394833949339503395133952339533395433955339563395733958339593396033961339623396333964339653396633967339683396933970339713397233973339743397533976339773397833979339803398133982339833398433985339863398733988339893399033991339923399333994339953399633997339983399934000340013400234003340043400534006340073400834009340103401134012340133401434015340163401734018340193402034021340223402334024340253402634027340283402934030340313403234033340343403534036340373403834039340403404134042340433404434045340463404734048340493405034051340523405334054340553405634057340583405934060340613406234063340643406534066340673406834069340703407134072340733407434075340763407734078340793408034081340823408334084340853408634087340883408934090340913409234093340943409534096340973409834099341003410134102341033410434105341063410734108341093411034111341123411334114341153411634117341183411934120341213412234123341243412534126341273412834129341303413134132341333413434135341363413734138341393414034141341423414334144341453414634147341483414934150341513415234153341543415534156341573415834159341603416134162341633416434165341663416734168341693417034171341723417334174341753417634177341783417934180341813418234183341843418534186341873418834189341903419134192341933419434195341963419734198341993420034201342023420334204342053420634207342083420934210342113421234213342143421534216342173421834219342203422134222342233422434225342263422734228342293423034231342323423334234342353423634237342383423934240342413424234243342443424534246342473424834249342503425134252342533425434255342563425734258342593426034261342623426334264342653426634267342683426934270342713427234273342743427534276342773427834279342803428134282342833428434285342863428734288342893429034291342923429334294342953429634297342983429934300343013430234303343043430534306343073430834309343103431134312343133431434315343163431734318343193432034321343223432334324343253432634327343283432934330343313433234333343343433534336343373433834339343403434134342343433434434345343463434734348343493435034351343523435334354343553435634357343583435934360343613436234363343643436534366343673436834369343703437134372343733437434375343763437734378343793438034381343823438334384343853438634387343883438934390343913439234393343943439534396343973439834399344003440134402344033440434405344063440734408344093441034411344123441334414344153441634417344183441934420344213442234423344243442534426344273442834429344303443134432344333443434435344363443734438344393444034441344423444334444344453444634447344483444934450344513445234453344543445534456344573445834459344603446134462344633446434465344663446734468344693447034471344723447334474344753447634477344783447934480344813448234483344843448534486344873448834489344903449134492344933449434495344963449734498344993450034501345023450334504345053450634507345083450934510345113451234513345143451534516345173451834519345203452134522345233452434525345263452734528345293453034531345323453334534345353453634537345383453934540345413454234543345443454534546345473454834549345503455134552345533455434555345563455734558345593456034561345623456334564345653456634567345683456934570345713457234573345743457534576345773457834579345803458134582345833458434585345863458734588345893459034591345923459334594345953459634597345983459934600346013460234603346043460534606346073460834609346103461134612346133461434615346163461734618346193462034621346223462334624346253462634627346283462934630346313463234633346343463534636346373463834639346403464134642346433464434645346463464734648346493465034651346523465334654346553465634657346583465934660346613466234663346643466534666346673466834669346703467134672346733467434675346763467734678346793468034681346823468334684346853468634687346883468934690346913469234693346943469534696346973469834699347003470134702347033470434705347063470734708347093471034711347123471334714347153471634717347183471934720347213472234723347243472534726347273472834729347303473134732347333473434735347363473734738347393474034741347423474334744347453474634747347483474934750347513475234753347543475534756347573475834759347603476134762347633476434765347663476734768347693477034771347723477334774347753477634777347783477934780347813478234783347843478534786347873478834789347903479134792347933479434795347963479734798347993480034801348023480334804348053480634807348083480934810348113481234813348143481534816348173481834819348203482134822348233482434825348263482734828348293483034831348323483334834348353483634837348383483934840348413484234843348443484534846348473484834849348503485134852348533485434855348563485734858348593486034861348623486334864348653486634867348683486934870348713487234873348743487534876348773487834879348803488134882348833488434885348863488734888348893489034891348923489334894348953489634897348983489934900349013490234903349043490534906349073490834909349103491134912349133491434915349163491734918349193492034921349223492334924349253492634927349283492934930349313493234933349343493534936349373493834939349403494134942349433494434945349463494734948349493495034951349523495334954349553495634957349583495934960349613496234963349643496534966349673496834969349703497134972349733497434975349763497734978349793498034981349823498334984349853498634987349883498934990349913499234993349943499534996349973499834999350003500135002350033500435005350063500735008350093501035011350123501335014350153501635017350183501935020350213502235023350243502535026350273502835029350303503135032350333503435035350363503735038350393504035041350423504335044350453504635047350483504935050350513505235053350543505535056350573505835059350603506135062350633506435065350663506735068350693507035071350723507335074350753507635077350783507935080350813508235083350843508535086350873508835089350903509135092350933509435095350963509735098350993510035101351023510335104351053510635107351083510935110351113511235113351143511535116351173511835119351203512135122351233512435125351263512735128351293513035131351323513335134351353513635137351383513935140351413514235143351443514535146351473514835149351503515135152351533515435155351563515735158351593516035161351623516335164351653516635167351683516935170351713517235173351743517535176351773517835179351803518135182351833518435185351863518735188351893519035191351923519335194351953519635197351983519935200352013520235203352043520535206352073520835209352103521135212352133521435215352163521735218352193522035221352223522335224352253522635227352283522935230352313523235233352343523535236352373523835239352403524135242352433524435245352463524735248352493525035251352523525335254352553525635257352583525935260352613526235263352643526535266352673526835269352703527135272352733527435275352763527735278352793528035281352823528335284352853528635287352883528935290352913529235293352943529535296352973529835299353003530135302353033530435305353063530735308353093531035311353123531335314353153531635317353183531935320353213532235323353243532535326353273532835329353303533135332353333533435335353363533735338353393534035341353423534335344353453534635347353483534935350353513535235353353543535535356353573535835359353603536135362353633536435365353663536735368353693537035371353723537335374353753537635377353783537935380353813538235383353843538535386353873538835389353903539135392353933539435395353963539735398353993540035401354023540335404354053540635407354083540935410354113541235413354143541535416354173541835419354203542135422354233542435425354263542735428354293543035431354323543335434354353543635437354383543935440354413544235443354443544535446354473544835449354503545135452354533545435455354563545735458354593546035461354623546335464354653546635467354683546935470354713547235473354743547535476354773547835479354803548135482354833548435485354863548735488354893549035491354923549335494354953549635497354983549935500355013550235503355043550535506355073550835509355103551135512355133551435515355163551735518355193552035521355223552335524355253552635527355283552935530355313553235533355343553535536355373553835539355403554135542355433554435545355463554735548355493555035551355523555335554355553555635557355583555935560355613556235563355643556535566355673556835569355703557135572355733557435575355763557735578355793558035581355823558335584355853558635587355883558935590355913559235593355943559535596355973559835599356003560135602356033560435605356063560735608356093561035611356123561335614356153561635617356183561935620356213562235623356243562535626356273562835629356303563135632356333563435635356363563735638356393564035641356423564335644356453564635647356483564935650356513565235653356543565535656356573565835659356603566135662356633566435665356663566735668356693567035671356723567335674356753567635677356783567935680356813568235683356843568535686356873568835689356903569135692356933569435695356963569735698356993570035701357023570335704357053570635707357083570935710357113571235713357143571535716357173571835719357203572135722357233572435725357263572735728357293573035731357323573335734357353573635737357383573935740357413574235743357443574535746357473574835749357503575135752357533575435755357563575735758357593576035761357623576335764357653576635767357683576935770357713577235773357743577535776357773577835779357803578135782357833578435785357863578735788357893579035791357923579335794357953579635797357983579935800358013580235803358043580535806358073580835809358103581135812358133581435815358163581735818358193582035821358223582335824358253582635827358283582935830358313583235833358343583535836358373583835839358403584135842358433584435845358463584735848358493585035851358523585335854358553585635857358583585935860358613586235863358643586535866358673586835869358703587135872358733587435875358763587735878358793588035881358823588335884358853588635887358883588935890358913589235893358943589535896358973589835899359003590135902359033590435905359063590735908359093591035911359123591335914359153591635917359183591935920359213592235923359243592535926359273592835929359303593135932359333593435935359363593735938359393594035941359423594335944359453594635947359483594935950359513595235953359543595535956359573595835959359603596135962359633596435965359663596735968359693597035971359723597335974359753597635977359783597935980359813598235983359843598535986359873598835989359903599135992359933599435995359963599735998359993600036001360023600336004360053600636007360083600936010360113601236013360143601536016360173601836019360203602136022360233602436025360263602736028360293603036031360323603336034360353603636037360383603936040360413604236043360443604536046360473604836049360503605136052360533605436055360563605736058360593606036061360623606336064360653606636067360683606936070360713607236073360743607536076360773607836079360803608136082360833608436085360863608736088360893609036091360923609336094360953609636097360983609936100361013610236103361043610536106361073610836109361103611136112361133611436115361163611736118361193612036121361223612336124361253612636127361283612936130361313613236133361343613536136361373613836139361403614136142361433614436145361463614736148361493615036151361523615336154361553615636157361583615936160361613616236163361643616536166361673616836169361703617136172361733617436175361763617736178361793618036181361823618336184361853618636187361883618936190361913619236193361943619536196361973619836199362003620136202362033620436205362063620736208362093621036211362123621336214362153621636217362183621936220362213622236223362243622536226362273622836229362303623136232362333623436235362363623736238362393624036241362423624336244362453624636247362483624936250362513625236253362543625536256362573625836259362603626136262362633626436265362663626736268362693627036271362723627336274362753627636277362783627936280362813628236283362843628536286362873628836289362903629136292362933629436295362963629736298362993630036301363023630336304363053630636307363083630936310363113631236313363143631536316363173631836319363203632136322363233632436325363263632736328363293633036331363323633336334363353633636337363383633936340363413634236343363443634536346363473634836349363503635136352363533635436355363563635736358363593636036361363623636336364363653636636367363683636936370363713637236373363743637536376363773637836379363803638136382363833638436385363863638736388363893639036391363923639336394363953639636397363983639936400364013640236403364043640536406364073640836409364103641136412364133641436415364163641736418364193642036421364223642336424364253642636427364283642936430364313643236433364343643536436364373643836439364403644136442364433644436445364463644736448364493645036451364523645336454364553645636457364583645936460364613646236463364643646536466364673646836469364703647136472364733647436475364763647736478364793648036481364823648336484364853648636487364883648936490364913649236493364943649536496364973649836499365003650136502365033650436505365063650736508365093651036511365123651336514365153651636517365183651936520365213652236523365243652536526365273652836529365303653136532365333653436535365363653736538365393654036541365423654336544365453654636547365483654936550365513655236553365543655536556365573655836559365603656136562365633656436565365663656736568365693657036571365723657336574365753657636577365783657936580365813658236583365843658536586365873658836589365903659136592365933659436595365963659736598365993660036601366023660336604366053660636607366083660936610366113661236613366143661536616366173661836619366203662136622366233662436625366263662736628366293663036631366323663336634366353663636637366383663936640366413664236643366443664536646366473664836649366503665136652366533665436655366563665736658366593666036661366623666336664366653666636667366683666936670366713667236673366743667536676366773667836679366803668136682366833668436685366863668736688366893669036691366923669336694366953669636697366983669936700367013670236703367043670536706367073670836709367103671136712367133671436715367163671736718367193672036721367223672336724367253672636727367283672936730367313673236733367343673536736367373673836739367403674136742367433674436745367463674736748367493675036751367523675336754367553675636757367583675936760367613676236763367643676536766367673676836769367703677136772367733677436775367763677736778367793678036781367823678336784367853678636787367883678936790367913679236793367943679536796367973679836799368003680136802368033680436805368063680736808368093681036811368123681336814368153681636817368183681936820368213682236823368243682536826368273682836829368303683136832368333683436835368363683736838368393684036841368423684336844368453684636847368483684936850368513685236853368543685536856368573685836859368603686136862368633686436865368663686736868368693687036871368723687336874368753687636877368783687936880368813688236883368843688536886368873688836889368903689136892368933689436895368963689736898368993690036901369023690336904369053690636907369083690936910369113691236913369143691536916369173691836919369203692136922369233692436925369263692736928369293693036931369323693336934369353693636937369383693936940369413694236943369443694536946369473694836949369503695136952369533695436955369563695736958369593696036961369623696336964369653696636967369683696936970369713697236973369743697536976369773697836979369803698136982369833698436985369863698736988369893699036991369923699336994369953699636997369983699937000370013700237003370043700537006370073700837009370103701137012370133701437015370163701737018370193702037021370223702337024370253702637027370283702937030370313703237033370343703537036370373703837039370403704137042370433704437045370463704737048370493705037051370523705337054370553705637057370583705937060370613706237063370643706537066370673706837069370703707137072370733707437075370763707737078370793708037081370823708337084370853708637087370883708937090370913709237093370943709537096370973709837099371003710137102371033710437105371063710737108371093711037111371123711337114371153711637117371183711937120371213712237123371243712537126371273712837129371303713137132371333713437135371363713737138371393714037141371423714337144371453714637147371483714937150371513715237153371543715537156371573715837159371603716137162371633716437165371663716737168371693717037171371723717337174371753717637177371783717937180371813718237183371843718537186371873718837189371903719137192371933719437195371963719737198371993720037201372023720337204372053720637207372083720937210372113721237213372143721537216372173721837219372203722137222372233722437225372263722737228372293723037231372323723337234372353723637237372383723937240372413724237243372443724537246372473724837249372503725137252372533725437255372563725737258372593726037261372623726337264372653726637267372683726937270372713727237273372743727537276372773727837279372803728137282372833728437285372863728737288372893729037291372923729337294372953729637297372983729937300373013730237303373043730537306373073730837309373103731137312373133731437315373163731737318373193732037321373223732337324373253732637327373283732937330373313733237333373343733537336373373733837339373403734137342373433734437345373463734737348373493735037351373523735337354373553735637357373583735937360373613736237363373643736537366373673736837369373703737137372373733737437375373763737737378373793738037381373823738337384373853738637387373883738937390373913739237393373943739537396373973739837399374003740137402374033740437405374063740737408374093741037411374123741337414374153741637417374183741937420374213742237423374243742537426374273742837429374303743137432374333743437435374363743737438374393744037441374423744337444374453744637447374483744937450374513745237453374543745537456374573745837459374603746137462374633746437465374663746737468374693747037471374723747337474374753747637477374783747937480374813748237483374843748537486374873748837489374903749137492374933749437495374963749737498374993750037501375023750337504375053750637507375083750937510375113751237513375143751537516375173751837519375203752137522375233752437525375263752737528375293753037531375323753337534375353753637537375383753937540375413754237543375443754537546375473754837549375503755137552375533755437555375563755737558375593756037561375623756337564375653756637567375683756937570375713757237573375743757537576375773757837579375803758137582375833758437585375863758737588375893759037591375923759337594375953759637597375983759937600376013760237603376043760537606376073760837609376103761137612376133761437615376163761737618376193762037621376223762337624376253762637627376283762937630376313763237633376343763537636376373763837639376403764137642376433764437645376463764737648376493765037651376523765337654376553765637657376583765937660376613766237663376643766537666376673766837669376703767137672376733767437675376763767737678376793768037681376823768337684376853768637687376883768937690376913769237693376943769537696376973769837699377003770137702377033770437705377063770737708377093771037711377123771337714377153771637717377183771937720377213772237723377243772537726377273772837729377303773137732377333773437735377363773737738377393774037741377423774337744377453774637747377483774937750377513775237753377543775537756377573775837759377603776137762377633776437765377663776737768377693777037771377723777337774377753777637777377783777937780377813778237783377843778537786377873778837789377903779137792377933779437795377963779737798377993780037801378023780337804378053780637807378083780937810378113781237813378143781537816378173781837819378203782137822378233782437825378263782737828378293783037831378323783337834378353783637837378383783937840378413784237843378443784537846378473784837849378503785137852378533785437855378563785737858378593786037861378623786337864378653786637867378683786937870378713787237873378743787537876378773787837879378803788137882378833788437885378863788737888378893789037891378923789337894378953789637897378983789937900379013790237903379043790537906379073790837909379103791137912379133791437915379163791737918379193792037921379223792337924379253792637927379283792937930379313793237933379343793537936379373793837939379403794137942379433794437945379463794737948379493795037951379523795337954379553795637957379583795937960379613796237963379643796537966379673796837969379703797137972379733797437975379763797737978379793798037981379823798337984379853798637987379883798937990379913799237993379943799537996379973799837999380003800138002380033800438005380063800738008380093801038011380123801338014380153801638017380183801938020380213802238023380243802538026380273802838029380303803138032380333803438035380363803738038380393804038041380423804338044380453804638047380483804938050380513805238053380543805538056380573805838059380603806138062380633806438065380663806738068380693807038071380723807338074380753807638077380783807938080380813808238083380843808538086380873808838089380903809138092380933809438095380963809738098380993810038101381023810338104381053810638107381083810938110381113811238113381143811538116381173811838119381203812138122381233812438125381263812738128381293813038131381323813338134381353813638137381383813938140381413814238143381443814538146381473814838149381503815138152381533815438155381563815738158381593816038161381623816338164381653816638167381683816938170381713817238173381743817538176381773817838179381803818138182381833818438185381863818738188381893819038191381923819338194381953819638197381983819938200382013820238203382043820538206382073820838209382103821138212382133821438215382163821738218382193822038221382223822338224382253822638227382283822938230382313823238233382343823538236382373823838239382403824138242382433824438245382463824738248382493825038251382523825338254382553825638257382583825938260382613826238263382643826538266382673826838269382703827138272382733827438275382763827738278382793828038281382823828338284382853828638287382883828938290382913829238293382943829538296382973829838299383003830138302383033830438305383063830738308383093831038311383123831338314383153831638317383183831938320383213832238323383243832538326383273832838329383303833138332383333833438335383363833738338383393834038341383423834338344383453834638347383483834938350383513835238353383543835538356383573835838359383603836138362383633836438365383663836738368383693837038371383723837338374383753837638377383783837938380383813838238383383843838538386383873838838389383903839138392383933839438395383963839738398383993840038401384023840338404384053840638407384083840938410384113841238413384143841538416384173841838419384203842138422384233842438425384263842738428384293843038431384323843338434384353843638437384383843938440384413844238443384443844538446384473844838449384503845138452384533845438455384563845738458384593846038461384623846338464384653846638467384683846938470384713847238473384743847538476384773847838479384803848138482384833848438485384863848738488384893849038491384923849338494384953849638497384983849938500385013850238503385043850538506385073850838509385103851138512385133851438515385163851738518385193852038521385223852338524385253852638527385283852938530385313853238533385343853538536385373853838539385403854138542385433854438545385463854738548385493855038551385523855338554385553855638557385583855938560385613856238563385643856538566385673856838569385703857138572385733857438575385763857738578385793858038581385823858338584385853858638587385883858938590385913859238593385943859538596385973859838599386003860138602386033860438605386063860738608386093861038611386123861338614386153861638617386183861938620386213862238623386243862538626386273862838629386303863138632386333863438635386363863738638386393864038641386423864338644386453864638647386483864938650386513865238653386543865538656386573865838659386603866138662386633866438665386663866738668386693867038671386723867338674386753867638677386783867938680386813868238683386843868538686386873868838689386903869138692386933869438695386963869738698386993870038701387023870338704387053870638707387083870938710387113871238713387143871538716387173871838719387203872138722387233872438725387263872738728387293873038731387323873338734387353873638737387383873938740387413874238743387443874538746387473874838749387503875138752387533875438755387563875738758387593876038761387623876338764387653876638767387683876938770387713877238773387743877538776387773877838779387803878138782387833878438785387863878738788387893879038791387923879338794387953879638797387983879938800388013880238803388043880538806388073880838809388103881138812388133881438815388163881738818388193882038821388223882338824388253882638827388283882938830388313883238833388343883538836388373883838839388403884138842388433884438845388463884738848388493885038851388523885338854388553885638857388583885938860388613886238863388643886538866388673886838869388703887138872388733887438875388763887738878388793888038881388823888338884388853888638887388883888938890388913889238893388943889538896388973889838899389003890138902389033890438905389063890738908389093891038911389123891338914389153891638917389183891938920389213892238923389243892538926389273892838929389303893138932389333893438935389363893738938389393894038941389423894338944389453894638947389483894938950389513895238953389543895538956389573895838959389603896138962389633896438965389663896738968389693897038971389723897338974389753897638977389783897938980389813898238983389843898538986389873898838989389903899138992389933899438995389963899738998389993900039001390023900339004390053900639007390083900939010390113901239013390143901539016390173901839019390203902139022390233902439025390263902739028390293903039031390323903339034390353903639037390383903939040390413904239043390443904539046390473904839049390503905139052390533905439055390563905739058390593906039061390623906339064390653906639067390683906939070390713907239073390743907539076390773907839079390803908139082390833908439085390863908739088390893909039091390923909339094390953909639097390983909939100391013910239103391043910539106391073910839109391103911139112391133911439115391163911739118391193912039121391223912339124391253912639127391283912939130391313913239133391343913539136391373913839139391403914139142391433914439145391463914739148391493915039151391523915339154391553915639157391583915939160391613916239163391643916539166391673916839169391703917139172391733917439175391763917739178391793918039181391823918339184391853918639187391883918939190391913919239193391943919539196391973919839199392003920139202392033920439205392063920739208392093921039211392123921339214392153921639217392183921939220392213922239223392243922539226392273922839229392303923139232392333923439235392363923739238392393924039241392423924339244392453924639247392483924939250392513925239253392543925539256392573925839259392603926139262392633926439265392663926739268392693927039271392723927339274392753927639277392783927939280392813928239283392843928539286392873928839289392903929139292392933929439295392963929739298392993930039301393023930339304393053930639307393083930939310393113931239313393143931539316393173931839319393203932139322393233932439325393263932739328393293933039331393323933339334393353933639337393383933939340393413934239343393443934539346393473934839349393503935139352393533935439355393563935739358393593936039361393623936339364393653936639367393683936939370393713937239373393743937539376393773937839379393803938139382393833938439385393863938739388393893939039391393923939339394393953939639397393983939939400394013940239403394043940539406394073940839409394103941139412394133941439415394163941739418394193942039421394223942339424394253942639427394283942939430394313943239433394343943539436394373943839439394403944139442394433944439445394463944739448394493945039451394523945339454394553945639457394583945939460394613946239463394643946539466394673946839469394703947139472394733947439475394763947739478394793948039481394823948339484394853948639487394883948939490394913949239493394943949539496394973949839499395003950139502395033950439505395063950739508395093951039511395123951339514395153951639517395183951939520395213952239523395243952539526395273952839529395303953139532395333953439535395363953739538395393954039541395423954339544395453954639547395483954939550395513955239553395543955539556395573955839559395603956139562395633956439565395663956739568395693957039571395723957339574395753957639577395783957939580395813958239583395843958539586395873958839589395903959139592395933959439595395963959739598395993960039601396023960339604396053960639607396083960939610396113961239613396143961539616396173961839619396203962139622396233962439625396263962739628396293963039631396323963339634396353963639637396383963939640396413964239643396443964539646396473964839649396503965139652396533965439655396563965739658396593966039661396623966339664396653966639667396683966939670396713967239673396743967539676396773967839679396803968139682396833968439685396863968739688396893969039691396923969339694396953969639697396983969939700397013970239703397043970539706397073970839709397103971139712397133971439715397163971739718397193972039721397223972339724397253972639727397283972939730397313973239733397343973539736397373973839739397403974139742397433974439745397463974739748397493975039751397523975339754397553975639757397583975939760397613976239763397643976539766397673976839769397703977139772397733977439775397763977739778397793978039781397823978339784397853978639787397883978939790397913979239793397943979539796397973979839799398003980139802398033980439805398063980739808398093981039811398123981339814398153981639817398183981939820398213982239823398243982539826398273982839829398303983139832398333983439835398363983739838398393984039841398423984339844398453984639847398483984939850398513985239853398543985539856398573985839859398603986139862398633986439865398663986739868398693987039871398723987339874398753987639877398783987939880398813988239883398843988539886398873988839889398903989139892398933989439895398963989739898398993990039901399023990339904399053990639907399083990939910399113991239913399143991539916399173991839919399203992139922399233992439925399263992739928399293993039931399323993339934399353993639937399383993939940399413994239943399443994539946399473994839949399503995139952399533995439955399563995739958399593996039961399623996339964399653996639967399683996939970399713997239973399743997539976399773997839979399803998139982399833998439985399863998739988399893999039991399923999339994399953999639997399983999940000400014000240003400044000540006400074000840009400104001140012400134001440015400164001740018400194002040021400224002340024400254002640027400284002940030400314003240033400344003540036400374003840039400404004140042400434004440045400464004740048400494005040051400524005340054400554005640057400584005940060400614006240063400644006540066400674006840069400704007140072400734007440075400764007740078400794008040081400824008340084400854008640087400884008940090400914009240093400944009540096400974009840099401004010140102401034010440105401064010740108401094011040111401124011340114401154011640117401184011940120401214012240123401244012540126401274012840129401304013140132401334013440135401364013740138401394014040141401424014340144401454014640147401484014940150401514015240153401544015540156401574015840159401604016140162401634016440165401664016740168401694017040171401724017340174401754017640177401784017940180401814018240183401844018540186401874018840189401904019140192401934019440195401964019740198401994020040201402024020340204402054020640207402084020940210402114021240213402144021540216402174021840219402204022140222402234022440225402264022740228402294023040231402324023340234402354023640237402384023940240402414024240243402444024540246402474024840249402504025140252402534025440255402564025740258402594026040261402624026340264402654026640267402684026940270402714027240273402744027540276402774027840279402804028140282402834028440285402864028740288402894029040291402924029340294402954029640297402984029940300403014030240303403044030540306403074030840309403104031140312403134031440315403164031740318403194032040321403224032340324403254032640327403284032940330403314033240333403344033540336403374033840339403404034140342403434034440345403464034740348403494035040351403524035340354403554035640357403584035940360403614036240363403644036540366403674036840369403704037140372403734037440375403764037740378403794038040381403824038340384403854038640387403884038940390403914039240393403944039540396403974039840399404004040140402404034040440405404064040740408404094041040411404124041340414404154041640417404184041940420404214042240423404244042540426404274042840429404304043140432404334043440435404364043740438404394044040441404424044340444404454044640447404484044940450404514045240453404544045540456404574045840459404604046140462404634046440465404664046740468404694047040471404724047340474404754047640477404784047940480404814048240483404844048540486404874048840489404904049140492404934049440495404964049740498404994050040501405024050340504405054050640507405084050940510405114051240513405144051540516405174051840519405204052140522405234052440525405264052740528405294053040531405324053340534405354053640537405384053940540405414054240543405444054540546405474054840549405504055140552405534055440555405564055740558405594056040561405624056340564405654056640567405684056940570405714057240573405744057540576405774057840579405804058140582405834058440585405864058740588405894059040591405924059340594405954059640597405984059940600406014060240603406044060540606406074060840609406104061140612406134061440615406164061740618406194062040621406224062340624406254062640627406284062940630406314063240633406344063540636406374063840639406404064140642406434064440645406464064740648406494065040651406524065340654406554065640657406584065940660406614066240663406644066540666406674066840669406704067140672406734067440675406764067740678406794068040681406824068340684406854068640687406884068940690406914069240693406944069540696406974069840699407004070140702407034070440705407064070740708407094071040711407124071340714407154071640717407184071940720407214072240723407244072540726407274072840729407304073140732407334073440735407364073740738407394074040741407424074340744407454074640747407484074940750407514075240753407544075540756407574075840759407604076140762407634076440765407664076740768407694077040771407724077340774407754077640777407784077940780407814078240783407844078540786407874078840789407904079140792407934079440795407964079740798407994080040801408024080340804408054080640807408084080940810408114081240813408144081540816408174081840819408204082140822408234082440825408264082740828408294083040831408324083340834408354083640837408384083940840408414084240843408444084540846408474084840849408504085140852408534085440855408564085740858408594086040861408624086340864408654086640867408684086940870408714087240873408744087540876408774087840879408804088140882408834088440885408864088740888408894089040891408924089340894408954089640897408984089940900409014090240903409044090540906409074090840909409104091140912409134091440915409164091740918409194092040921409224092340924409254092640927409284092940930409314093240933409344093540936409374093840939409404094140942409434094440945409464094740948409494095040951409524095340954409554095640957409584095940960409614096240963409644096540966409674096840969409704097140972409734097440975409764097740978409794098040981409824098340984409854098640987409884098940990409914099240993409944099540996409974099840999410004100141002410034100441005410064100741008410094101041011410124101341014410154101641017410184101941020410214102241023410244102541026410274102841029410304103141032410334103441035410364103741038410394104041041410424104341044410454104641047410484104941050410514105241053410544105541056410574105841059410604106141062410634106441065410664106741068410694107041071410724107341074410754107641077410784107941080410814108241083410844108541086410874108841089410904109141092410934109441095410964109741098410994110041101411024110341104411054110641107411084110941110411114111241113411144111541116411174111841119411204112141122411234112441125411264112741128411294113041131411324113341134411354113641137411384113941140411414114241143411444114541146411474114841149411504115141152411534115441155411564115741158411594116041161411624116341164411654116641167411684116941170411714117241173411744117541176411774117841179411804118141182411834118441185411864118741188411894119041191411924119341194411954119641197411984119941200412014120241203412044120541206412074120841209412104121141212412134121441215412164121741218412194122041221412224122341224412254122641227412284122941230412314123241233412344123541236412374123841239412404124141242412434124441245412464124741248412494125041251412524125341254412554125641257412584125941260412614126241263412644126541266412674126841269412704127141272412734127441275412764127741278412794128041281412824128341284412854128641287412884128941290412914129241293412944129541296412974129841299413004130141302413034130441305413064130741308413094131041311413124131341314413154131641317413184131941320413214132241323413244132541326413274132841329413304133141332413334133441335413364133741338413394134041341413424134341344413454134641347413484134941350413514135241353413544135541356413574135841359413604136141362413634136441365413664136741368413694137041371413724137341374413754137641377413784137941380413814138241383413844138541386413874138841389413904139141392413934139441395413964139741398413994140041401414024140341404414054140641407414084140941410414114141241413414144141541416414174141841419414204142141422414234142441425414264142741428414294143041431414324143341434414354143641437414384143941440414414144241443414444144541446414474144841449414504145141452414534145441455414564145741458414594146041461414624146341464414654146641467414684146941470414714147241473414744147541476414774147841479414804148141482414834148441485414864148741488414894149041491414924149341494414954149641497414984149941500415014150241503415044150541506415074150841509415104151141512415134151441515415164151741518415194152041521415224152341524415254152641527415284152941530415314153241533415344153541536415374153841539415404154141542415434154441545415464154741548415494155041551415524155341554415554155641557415584155941560415614156241563415644156541566415674156841569415704157141572415734157441575415764157741578415794158041581415824158341584415854158641587415884158941590415914159241593415944159541596415974159841599416004160141602416034160441605416064160741608416094161041611416124161341614416154161641617416184161941620416214162241623416244162541626416274162841629416304163141632416334163441635416364163741638416394164041641416424164341644416454164641647416484164941650416514165241653416544165541656416574165841659416604166141662416634166441665416664166741668416694167041671416724167341674416754167641677416784167941680416814168241683416844168541686416874168841689416904169141692416934169441695416964169741698416994170041701417024170341704417054170641707417084170941710417114171241713417144171541716417174171841719417204172141722417234172441725417264172741728417294173041731417324173341734417354173641737417384173941740417414174241743417444174541746417474174841749417504175141752417534175441755417564175741758417594176041761417624176341764417654176641767417684176941770417714177241773417744177541776417774177841779417804178141782417834178441785417864178741788417894179041791417924179341794417954179641797417984179941800418014180241803418044180541806418074180841809418104181141812418134181441815418164181741818418194182041821418224182341824418254182641827418284182941830418314183241833418344183541836418374183841839418404184141842418434184441845418464184741848418494185041851418524185341854418554185641857418584185941860418614186241863418644186541866418674186841869418704187141872418734187441875418764187741878418794188041881418824188341884418854188641887418884188941890418914189241893418944189541896418974189841899419004190141902419034190441905419064190741908419094191041911419124191341914419154191641917419184191941920419214192241923419244192541926419274192841929419304193141932419334193441935419364193741938419394194041941419424194341944419454194641947419484194941950419514195241953419544195541956419574195841959419604196141962419634196441965419664196741968419694197041971419724197341974419754197641977419784197941980419814198241983419844198541986419874198841989419904199141992419934199441995419964199741998419994200042001420024200342004420054200642007420084200942010420114201242013420144201542016420174201842019420204202142022420234202442025420264202742028420294203042031420324203342034420354203642037420384203942040420414204242043420444204542046420474204842049420504205142052420534205442055420564205742058420594206042061420624206342064420654206642067420684206942070420714207242073420744207542076420774207842079420804208142082420834208442085420864208742088420894209042091420924209342094420954209642097420984209942100421014210242103421044210542106421074210842109421104211142112421134211442115421164211742118421194212042121421224212342124421254212642127421284212942130421314213242133421344213542136421374213842139421404214142142421434214442145421464214742148421494215042151421524215342154421554215642157421584215942160421614216242163421644216542166421674216842169421704217142172421734217442175421764217742178421794218042181421824218342184421854218642187421884218942190421914219242193421944219542196421974219842199422004220142202422034220442205422064220742208422094221042211422124221342214422154221642217422184221942220422214222242223422244222542226422274222842229422304223142232422334223442235422364223742238422394224042241422424224342244422454224642247422484224942250422514225242253422544225542256422574225842259422604226142262422634226442265422664226742268422694227042271422724227342274422754227642277422784227942280422814228242283422844228542286422874228842289422904229142292422934229442295422964229742298422994230042301423024230342304423054230642307423084230942310423114231242313423144231542316423174231842319423204232142322423234232442325423264232742328423294233042331423324233342334423354233642337423384233942340423414234242343423444234542346423474234842349423504235142352423534235442355423564235742358423594236042361423624236342364423654236642367423684236942370423714237242373423744237542376423774237842379423804238142382423834238442385423864238742388423894239042391423924239342394423954239642397423984239942400424014240242403424044240542406424074240842409424104241142412424134241442415424164241742418424194242042421424224242342424424254242642427424284242942430424314243242433424344243542436424374243842439424404244142442424434244442445424464244742448424494245042451424524245342454424554245642457424584245942460424614246242463424644246542466424674246842469424704247142472424734247442475424764247742478424794248042481424824248342484424854248642487424884248942490424914249242493424944249542496424974249842499425004250142502425034250442505425064250742508425094251042511425124251342514425154251642517425184251942520425214252242523425244252542526425274252842529425304253142532425334253442535425364253742538425394254042541425424254342544425454254642547425484254942550425514255242553425544255542556425574255842559425604256142562425634256442565425664256742568425694257042571425724257342574425754257642577425784257942580425814258242583425844258542586425874258842589425904259142592425934259442595425964259742598425994260042601426024260342604426054260642607426084260942610426114261242613426144261542616426174261842619426204262142622426234262442625426264262742628426294263042631426324263342634426354263642637426384263942640426414264242643426444264542646426474264842649426504265142652426534265442655426564265742658426594266042661426624266342664426654266642667426684266942670426714267242673426744267542676426774267842679426804268142682426834268442685426864268742688426894269042691426924269342694426954269642697426984269942700427014270242703427044270542706427074270842709427104271142712427134271442715427164271742718427194272042721427224272342724427254272642727427284272942730427314273242733427344273542736427374273842739427404274142742427434274442745427464274742748427494275042751427524275342754427554275642757427584275942760427614276242763427644276542766427674276842769427704277142772427734277442775427764277742778427794278042781427824278342784427854278642787427884278942790427914279242793427944279542796427974279842799428004280142802428034280442805428064280742808428094281042811428124281342814428154281642817428184281942820428214282242823428244282542826428274282842829428304283142832428334283442835428364283742838428394284042841428424284342844428454284642847428484284942850428514285242853428544285542856428574285842859428604286142862428634286442865428664286742868428694287042871428724287342874428754287642877428784287942880428814288242883428844288542886428874288842889428904289142892428934289442895428964289742898428994290042901429024290342904429054290642907429084290942910429114291242913429144291542916429174291842919429204292142922429234292442925429264292742928429294293042931429324293342934429354293642937429384293942940429414294242943429444294542946429474294842949429504295142952429534295442955429564295742958429594296042961429624296342964429654296642967429684296942970429714297242973429744297542976429774297842979429804298142982429834298442985429864298742988429894299042991429924299342994429954299642997429984299943000430014300243003430044300543006430074300843009430104301143012430134301443015430164301743018430194302043021430224302343024430254302643027430284302943030430314303243033430344303543036430374303843039430404304143042430434304443045430464304743048430494305043051430524305343054430554305643057430584305943060430614306243063430644306543066430674306843069430704307143072430734307443075430764307743078430794308043081430824308343084430854308643087430884308943090430914309243093430944309543096430974309843099431004310143102431034310443105431064310743108431094311043111431124311343114431154311643117431184311943120431214312243123431244312543126431274312843129431304313143132431334313443135431364313743138431394314043141431424314343144431454314643147431484314943150431514315243153431544315543156431574315843159431604316143162431634316443165431664316743168431694317043171431724317343174431754317643177431784317943180431814318243183431844318543186431874318843189431904319143192431934319443195431964319743198431994320043201432024320343204432054320643207432084320943210432114321243213432144321543216432174321843219432204322143222432234322443225432264322743228432294323043231432324323343234432354323643237432384323943240432414324243243432444324543246432474324843249432504325143252432534325443255432564325743258432594326043261432624326343264432654326643267432684326943270432714327243273432744327543276432774327843279432804328143282432834328443285432864328743288432894329043291432924329343294432954329643297432984329943300433014330243303433044330543306433074330843309433104331143312433134331443315433164331743318433194332043321433224332343324433254332643327433284332943330433314333243333433344333543336433374333843339433404334143342433434334443345433464334743348433494335043351433524335343354433554335643357433584335943360433614336243363433644336543366433674336843369433704337143372433734337443375433764337743378433794338043381433824338343384433854338643387433884338943390433914339243393433944339543396433974339843399434004340143402434034340443405434064340743408434094341043411434124341343414434154341643417434184341943420434214342243423434244342543426434274342843429434304343143432434334343443435434364343743438434394344043441434424344343444434454344643447434484344943450434514345243453434544345543456434574345843459434604346143462434634346443465434664346743468434694347043471434724347343474434754347643477434784347943480434814348243483434844348543486434874348843489434904349143492434934349443495434964349743498434994350043501435024350343504435054350643507435084350943510435114351243513435144351543516435174351843519435204352143522435234352443525435264352743528435294353043531435324353343534435354353643537435384353943540435414354243543435444354543546435474354843549435504355143552435534355443555435564355743558435594356043561435624356343564435654356643567435684356943570435714357243573435744357543576435774357843579435804358143582435834358443585435864358743588435894359043591435924359343594435954359643597435984359943600436014360243603436044360543606436074360843609436104361143612436134361443615436164361743618436194362043621436224362343624436254362643627436284362943630436314363243633436344363543636436374363843639436404364143642436434364443645436464364743648436494365043651436524365343654436554365643657436584365943660436614366243663436644366543666436674366843669436704367143672436734367443675436764367743678436794368043681436824368343684436854368643687436884368943690436914369243693436944369543696436974369843699437004370143702437034370443705437064370743708437094371043711437124371343714437154371643717437184371943720437214372243723437244372543726437274372843729437304373143732437334373443735437364373743738437394374043741437424374343744437454374643747437484374943750437514375243753437544375543756437574375843759437604376143762437634376443765437664376743768437694377043771437724377343774437754377643777437784377943780437814378243783437844378543786437874378843789437904379143792437934379443795437964379743798437994380043801438024380343804438054380643807438084380943810438114381243813438144381543816438174381843819438204382143822438234382443825438264382743828438294383043831438324383343834438354383643837438384383943840438414384243843438444384543846438474384843849438504385143852438534385443855438564385743858438594386043861438624386343864438654386643867438684386943870438714387243873438744387543876438774387843879438804388143882438834388443885438864388743888438894389043891438924389343894438954389643897438984389943900439014390243903439044390543906439074390843909439104391143912439134391443915439164391743918439194392043921439224392343924439254392643927439284392943930439314393243933439344393543936439374393843939439404394143942439434394443945439464394743948439494395043951439524395343954439554395643957439584395943960439614396243963439644396543966439674396843969439704397143972439734397443975439764397743978439794398043981439824398343984439854398643987439884398943990439914399243993439944399543996439974399843999440004400144002440034400444005440064400744008440094401044011440124401344014440154401644017440184401944020440214402244023440244402544026440274402844029440304403144032440334403444035440364403744038440394404044041440424404344044440454404644047440484404944050440514405244053440544405544056440574405844059440604406144062440634406444065440664406744068440694407044071440724407344074440754407644077440784407944080440814408244083440844408544086440874408844089440904409144092440934409444095440964409744098440994410044101441024410344104441054410644107441084410944110441114411244113441144411544116441174411844119441204412144122441234412444125441264412744128441294413044131441324413344134441354413644137441384413944140441414414244143441444414544146441474414844149441504415144152441534415444155441564415744158441594416044161441624416344164441654416644167441684416944170441714417244173441744417544176441774417844179441804418144182441834418444185441864418744188441894419044191441924419344194441954419644197441984419944200442014420244203442044420544206442074420844209442104421144212442134421444215442164421744218442194422044221442224422344224442254422644227442284422944230442314423244233442344423544236442374423844239442404424144242442434424444245442464424744248442494425044251442524425344254442554425644257442584425944260442614426244263442644426544266442674426844269442704427144272442734427444275442764427744278442794428044281442824428344284442854428644287442884428944290442914429244293442944429544296442974429844299443004430144302443034430444305443064430744308443094431044311443124431344314443154431644317443184431944320443214432244323443244432544326443274432844329443304433144332443334433444335443364433744338443394434044341443424434344344443454434644347443484434944350443514435244353443544435544356443574435844359443604436144362443634436444365443664436744368443694437044371443724437344374443754437644377443784437944380443814438244383443844438544386443874438844389443904439144392443934439444395443964439744398443994440044401444024440344404444054440644407444084440944410444114441244413444144441544416444174441844419444204442144422444234442444425444264442744428444294443044431444324443344434444354443644437444384443944440444414444244443444444444544446444474444844449444504445144452444534445444455444564445744458444594446044461444624446344464444654446644467444684446944470444714447244473444744447544476444774447844479444804448144482444834448444485444864448744488444894449044491444924449344494444954449644497444984449944500445014450244503445044450544506445074450844509445104451144512445134451444515445164451744518445194452044521445224452344524445254452644527445284452944530445314453244533445344453544536445374453844539445404454144542445434454444545445464454744548445494455044551445524455344554445554455644557445584455944560445614456244563445644456544566445674456844569445704457144572445734457444575445764457744578445794458044581445824458344584445854458644587445884458944590445914459244593445944459544596445974459844599446004460144602446034460444605446064460744608446094461044611446124461344614446154461644617446184461944620446214462244623446244462544626446274462844629446304463144632446334463444635446364463744638446394464044641446424464344644446454464644647446484464944650446514465244653446544465544656446574465844659446604466144662446634466444665446664466744668446694467044671446724467344674446754467644677446784467944680446814468244683446844468544686446874468844689446904469144692446934469444695446964469744698446994470044701447024470344704447054470644707447084470944710447114471244713447144471544716447174471844719447204472144722447234472444725447264472744728447294473044731447324473344734447354473644737447384473944740447414474244743447444474544746447474474844749447504475144752447534475444755447564475744758447594476044761447624476344764447654476644767447684476944770447714477244773447744477544776447774477844779447804478144782447834478444785447864478744788447894479044791447924479344794447954479644797447984479944800448014480244803448044480544806448074480844809448104481144812448134481444815448164481744818448194482044821448224482344824448254482644827448284482944830448314483244833448344483544836448374483844839448404484144842448434484444845448464484744848448494485044851448524485344854448554485644857448584485944860448614486244863448644486544866448674486844869448704487144872448734487444875448764487744878448794488044881448824488344884448854488644887448884488944890448914489244893448944489544896448974489844899449004490144902449034490444905449064490744908449094491044911449124491344914449154491644917449184491944920449214492244923449244492544926449274492844929449304493144932449334493444935449364493744938449394494044941449424494344944449454494644947449484494944950449514495244953449544495544956449574495844959449604496144962449634496444965449664496744968449694497044971449724497344974449754497644977449784497944980449814498244983449844498544986449874498844989449904499144992449934499444995449964499744998449994500045001450024500345004450054500645007450084500945010450114501245013450144501545016450174501845019450204502145022450234502445025450264502745028450294503045031450324503345034450354503645037450384503945040450414504245043450444504545046450474504845049450504505145052450534505445055450564505745058450594506045061450624506345064450654506645067450684506945070450714507245073450744507545076450774507845079450804508145082450834508445085450864508745088450894509045091450924509345094450954509645097450984509945100451014510245103451044510545106451074510845109451104511145112451134511445115451164511745118451194512045121451224512345124451254512645127451284512945130451314513245133451344513545136451374513845139451404514145142451434514445145451464514745148451494515045151451524515345154451554515645157451584515945160451614516245163451644516545166451674516845169451704517145172451734517445175451764517745178451794518045181451824518345184451854518645187451884518945190451914519245193451944519545196451974519845199452004520145202452034520445205452064520745208452094521045211452124521345214452154521645217452184521945220452214522245223452244522545226452274522845229452304523145232452334523445235452364523745238452394524045241452424524345244452454524645247452484524945250452514525245253452544525545256452574525845259452604526145262452634526445265452664526745268452694527045271452724527345274452754527645277452784527945280452814528245283452844528545286452874528845289452904529145292452934529445295452964529745298452994530045301453024530345304453054530645307453084530945310453114531245313453144531545316453174531845319453204532145322453234532445325453264532745328453294533045331453324533345334453354533645337453384533945340453414534245343453444534545346453474534845349453504535145352453534535445355453564535745358453594536045361453624536345364453654536645367453684536945370453714537245373453744537545376453774537845379453804538145382453834538445385453864538745388453894539045391453924539345394453954539645397453984539945400454014540245403454044540545406454074540845409454104541145412454134541445415454164541745418454194542045421454224542345424454254542645427454284542945430454314543245433454344543545436454374543845439454404544145442454434544445445454464544745448454494545045451454524545345454454554545645457454584545945460454614546245463454644546545466454674546845469454704547145472454734547445475454764547745478454794548045481454824548345484454854548645487454884548945490454914549245493454944549545496454974549845499455004550145502455034550445505455064550745508455094551045511455124551345514455154551645517455184551945520455214552245523455244552545526455274552845529455304553145532455334553445535455364553745538455394554045541455424554345544455454554645547455484554945550455514555245553455544555545556455574555845559455604556145562455634556445565455664556745568455694557045571455724557345574455754557645577455784557945580455814558245583455844558545586455874558845589455904559145592455934559445595455964559745598455994560045601456024560345604456054560645607456084560945610456114561245613456144561545616456174561845619456204562145622456234562445625456264562745628456294563045631456324563345634456354563645637456384563945640456414564245643456444564545646456474564845649456504565145652456534565445655456564565745658456594566045661456624566345664456654566645667456684566945670456714567245673456744567545676456774567845679456804568145682456834568445685456864568745688456894569045691456924569345694456954569645697456984569945700457014570245703457044570545706457074570845709457104571145712457134571445715457164571745718457194572045721457224572345724457254572645727457284572945730457314573245733457344573545736457374573845739457404574145742457434574445745457464574745748457494575045751457524575345754457554575645757457584575945760457614576245763457644576545766457674576845769457704577145772457734577445775457764577745778457794578045781457824578345784457854578645787457884578945790457914579245793457944579545796457974579845799458004580145802458034580445805458064580745808458094581045811458124581345814458154581645817458184581945820458214582245823458244582545826458274582845829458304583145832458334583445835458364583745838458394584045841458424584345844458454584645847458484584945850458514585245853458544585545856458574585845859458604586145862458634586445865458664586745868458694587045871458724587345874458754587645877458784587945880458814588245883458844588545886458874588845889458904589145892458934589445895458964589745898458994590045901459024590345904459054590645907459084590945910459114591245913459144591545916459174591845919459204592145922459234592445925459264592745928459294593045931459324593345934459354593645937459384593945940459414594245943459444594545946459474594845949459504595145952459534595445955459564595745958459594596045961459624596345964459654596645967459684596945970459714597245973459744597545976459774597845979459804598145982459834598445985459864598745988459894599045991459924599345994459954599645997459984599946000460014600246003460044600546006460074600846009460104601146012460134601446015460164601746018460194602046021460224602346024460254602646027460284602946030460314603246033460344603546036460374603846039460404604146042460434604446045460464604746048460494605046051460524605346054460554605646057460584605946060460614606246063460644606546066460674606846069460704607146072460734607446075460764607746078460794608046081460824608346084460854608646087460884608946090460914609246093460944609546096460974609846099461004610146102461034610446105461064610746108461094611046111461124611346114461154611646117461184611946120461214612246123461244612546126461274612846129461304613146132461334613446135461364613746138461394614046141461424614346144461454614646147461484614946150461514615246153461544615546156461574615846159461604616146162461634616446165461664616746168461694617046171461724617346174461754617646177461784617946180461814618246183461844618546186461874618846189461904619146192461934619446195461964619746198461994620046201462024620346204462054620646207462084620946210462114621246213462144621546216462174621846219462204622146222462234622446225462264622746228462294623046231462324623346234462354623646237462384623946240462414624246243462444624546246462474624846249462504625146252462534625446255462564625746258462594626046261462624626346264462654626646267462684626946270462714627246273462744627546276462774627846279462804628146282462834628446285462864628746288462894629046291462924629346294462954629646297462984629946300463014630246303463044630546306463074630846309463104631146312463134631446315463164631746318463194632046321463224632346324463254632646327463284632946330463314633246333463344633546336463374633846339463404634146342463434634446345463464634746348463494635046351463524635346354463554635646357463584635946360463614636246363463644636546366463674636846369463704637146372463734637446375463764637746378463794638046381463824638346384463854638646387463884638946390463914639246393463944639546396463974639846399464004640146402464034640446405464064640746408464094641046411464124641346414464154641646417464184641946420464214642246423464244642546426464274642846429464304643146432464334643446435464364643746438464394644046441464424644346444464454644646447464484644946450464514645246453464544645546456464574645846459464604646146462464634646446465464664646746468464694647046471464724647346474464754647646477464784647946480464814648246483464844648546486464874648846489464904649146492464934649446495464964649746498464994650046501465024650346504465054650646507465084650946510465114651246513465144651546516465174651846519465204652146522465234652446525465264652746528465294653046531465324653346534465354653646537465384653946540465414654246543465444654546546465474654846549465504655146552465534655446555465564655746558465594656046561465624656346564465654656646567465684656946570465714657246573465744657546576465774657846579465804658146582465834658446585465864658746588465894659046591465924659346594465954659646597465984659946600466014660246603466044660546606466074660846609466104661146612466134661446615466164661746618466194662046621466224662346624466254662646627466284662946630466314663246633466344663546636466374663846639466404664146642466434664446645466464664746648466494665046651466524665346654466554665646657466584665946660466614666246663466644666546666466674666846669466704667146672466734667446675466764667746678466794668046681466824668346684466854668646687466884668946690466914669246693466944669546696466974669846699467004670146702467034670446705467064670746708467094671046711467124671346714467154671646717467184671946720467214672246723467244672546726467274672846729467304673146732467334673446735467364673746738467394674046741467424674346744467454674646747467484674946750467514675246753467544675546756467574675846759467604676146762467634676446765467664676746768467694677046771467724677346774467754677646777467784677946780467814678246783467844678546786467874678846789467904679146792467934679446795467964679746798467994680046801468024680346804468054680646807468084680946810468114681246813468144681546816468174681846819468204682146822468234682446825468264682746828468294683046831468324683346834468354683646837468384683946840468414684246843468444684546846468474684846849468504685146852468534685446855468564685746858468594686046861468624686346864468654686646867468684686946870468714687246873468744687546876468774687846879468804688146882468834688446885468864688746888468894689046891468924689346894468954689646897468984689946900469014690246903469044690546906469074690846909469104691146912469134691446915469164691746918469194692046921469224692346924469254692646927469284692946930469314693246933469344693546936469374693846939469404694146942469434694446945469464694746948469494695046951469524695346954469554695646957469584695946960469614696246963469644696546966469674696846969469704697146972469734697446975469764697746978469794698046981469824698346984469854698646987469884698946990469914699246993469944699546996469974699846999470004700147002470034700447005470064700747008470094701047011470124701347014470154701647017470184701947020470214702247023470244702547026470274702847029470304703147032470334703447035470364703747038470394704047041470424704347044470454704647047470484704947050470514705247053470544705547056470574705847059470604706147062470634706447065470664706747068470694707047071470724707347074470754707647077470784707947080470814708247083470844708547086470874708847089470904709147092470934709447095470964709747098470994710047101471024710347104471054710647107471084710947110471114711247113471144711547116471174711847119471204712147122471234712447125471264712747128471294713047131471324713347134471354713647137471384713947140471414714247143471444714547146471474714847149471504715147152471534715447155471564715747158471594716047161471624716347164471654716647167471684716947170471714717247173471744717547176471774717847179471804718147182471834718447185471864718747188471894719047191471924719347194471954719647197471984719947200472014720247203472044720547206472074720847209472104721147212472134721447215472164721747218472194722047221472224722347224472254722647227472284722947230472314723247233472344723547236472374723847239472404724147242472434724447245472464724747248472494725047251472524725347254472554725647257472584725947260472614726247263472644726547266472674726847269472704727147272472734727447275472764727747278472794728047281472824728347284472854728647287472884728947290472914729247293472944729547296472974729847299473004730147302473034730447305473064730747308473094731047311473124731347314473154731647317473184731947320473214732247323473244732547326473274732847329473304733147332473334733447335473364733747338473394734047341473424734347344473454734647347473484734947350473514735247353473544735547356473574735847359473604736147362473634736447365473664736747368473694737047371473724737347374473754737647377473784737947380473814738247383473844738547386473874738847389473904739147392473934739447395473964739747398473994740047401474024740347404474054740647407474084740947410474114741247413474144741547416474174741847419474204742147422474234742447425474264742747428474294743047431474324743347434474354743647437474384743947440474414744247443474444744547446474474744847449474504745147452474534745447455474564745747458474594746047461474624746347464474654746647467474684746947470474714747247473474744747547476474774747847479474804748147482474834748447485474864748747488474894749047491474924749347494474954749647497474984749947500475014750247503475044750547506475074750847509475104751147512475134751447515475164751747518475194752047521475224752347524475254752647527475284752947530475314753247533475344753547536475374753847539475404754147542475434754447545475464754747548475494755047551475524755347554475554755647557475584755947560475614756247563475644756547566475674756847569475704757147572475734757447575475764757747578475794758047581475824758347584475854758647587475884758947590475914759247593475944759547596475974759847599476004760147602476034760447605476064760747608476094761047611476124761347614476154761647617476184761947620476214762247623476244762547626476274762847629476304763147632476334763447635476364763747638476394764047641476424764347644476454764647647476484764947650476514765247653476544765547656476574765847659476604766147662476634766447665476664766747668476694767047671476724767347674476754767647677476784767947680476814768247683476844768547686476874768847689476904769147692476934769447695476964769747698476994770047701477024770347704477054770647707477084770947710477114771247713477144771547716477174771847719477204772147722477234772447725477264772747728477294773047731477324773347734477354773647737477384773947740477414774247743477444774547746477474774847749477504775147752477534775447755477564775747758477594776047761477624776347764477654776647767477684776947770477714777247773477744777547776477774777847779477804778147782477834778447785477864778747788477894779047791477924779347794477954779647797477984779947800478014780247803478044780547806478074780847809478104781147812478134781447815478164781747818478194782047821478224782347824478254782647827478284782947830478314783247833478344783547836478374783847839478404784147842478434784447845478464784747848478494785047851478524785347854478554785647857478584785947860478614786247863478644786547866478674786847869478704787147872478734787447875478764787747878478794788047881478824788347884478854788647887478884788947890478914789247893478944789547896478974789847899479004790147902479034790447905479064790747908479094791047911479124791347914479154791647917479184791947920479214792247923479244792547926479274792847929479304793147932479334793447935479364793747938479394794047941479424794347944479454794647947479484794947950479514795247953479544795547956479574795847959479604796147962479634796447965479664796747968479694797047971479724797347974479754797647977479784797947980479814798247983479844798547986479874798847989479904799147992479934799447995479964799747998479994800048001480024800348004480054800648007480084800948010480114801248013480144801548016480174801848019480204802148022480234802448025480264802748028480294803048031480324803348034480354803648037480384803948040480414804248043480444804548046480474804848049480504805148052480534805448055480564805748058480594806048061480624806348064480654806648067480684806948070480714807248073480744807548076480774807848079480804808148082480834808448085480864808748088480894809048091480924809348094480954809648097480984809948100481014810248103481044810548106481074810848109481104811148112481134811448115481164811748118481194812048121481224812348124481254812648127481284812948130481314813248133481344813548136481374813848139481404814148142481434814448145481464814748148481494815048151481524815348154481554815648157481584815948160481614816248163481644816548166481674816848169481704817148172481734817448175481764817748178481794818048181481824818348184481854818648187481884818948190481914819248193481944819548196481974819848199482004820148202482034820448205482064820748208482094821048211482124821348214482154821648217482184821948220482214822248223482244822548226482274822848229482304823148232482334823448235482364823748238482394824048241482424824348244482454824648247482484824948250482514825248253482544825548256482574825848259482604826148262482634826448265482664826748268482694827048271482724827348274482754827648277482784827948280482814828248283482844828548286482874828848289482904829148292482934829448295482964829748298482994830048301483024830348304483054830648307483084830948310483114831248313483144831548316483174831848319483204832148322483234832448325483264832748328483294833048331483324833348334483354833648337483384833948340483414834248343483444834548346483474834848349483504835148352483534835448355483564835748358483594836048361483624836348364483654836648367483684836948370483714837248373483744837548376483774837848379483804838148382483834838448385483864838748388483894839048391483924839348394483954839648397483984839948400484014840248403484044840548406484074840848409484104841148412484134841448415484164841748418484194842048421484224842348424484254842648427484284842948430484314843248433484344843548436484374843848439484404844148442484434844448445484464844748448484494845048451484524845348454484554845648457484584845948460484614846248463484644846548466484674846848469484704847148472484734847448475484764847748478484794848048481484824848348484484854848648487484884848948490484914849248493484944849548496484974849848499485004850148502485034850448505485064850748508485094851048511485124851348514485154851648517485184851948520485214852248523485244852548526485274852848529485304853148532485334853448535485364853748538485394854048541485424854348544485454854648547485484854948550485514855248553485544855548556485574855848559485604856148562485634856448565485664856748568485694857048571485724857348574485754857648577485784857948580485814858248583485844858548586485874858848589485904859148592485934859448595485964859748598485994860048601486024860348604486054860648607486084860948610486114861248613486144861548616486174861848619486204862148622486234862448625486264862748628486294863048631486324863348634486354863648637486384863948640486414864248643486444864548646486474864848649486504865148652486534865448655486564865748658486594866048661486624866348664486654866648667486684866948670486714867248673486744867548676486774867848679486804868148682486834868448685486864868748688486894869048691486924869348694486954869648697486984869948700487014870248703487044870548706487074870848709487104871148712487134871448715487164871748718487194872048721487224872348724487254872648727487284872948730487314873248733487344873548736487374873848739487404874148742487434874448745487464874748748487494875048751487524875348754487554875648757487584875948760487614876248763487644876548766487674876848769487704877148772487734877448775487764877748778487794878048781487824878348784487854878648787487884878948790487914879248793487944879548796487974879848799488004880148802488034880448805488064880748808488094881048811488124881348814488154881648817488184881948820488214882248823488244882548826488274882848829488304883148832488334883448835488364883748838488394884048841488424884348844488454884648847488484884948850488514885248853488544885548856488574885848859488604886148862488634886448865488664886748868488694887048871488724887348874488754887648877488784887948880488814888248883488844888548886488874888848889488904889148892488934889448895488964889748898488994890048901489024890348904489054890648907489084890948910489114891248913489144891548916489174891848919489204892148922489234892448925489264892748928489294893048931489324893348934489354893648937489384893948940489414894248943489444894548946489474894848949489504895148952489534895448955489564895748958489594896048961489624896348964489654896648967489684896948970489714897248973489744897548976489774897848979489804898148982489834898448985489864898748988489894899048991489924899348994489954899648997489984899949000490014900249003490044900549006490074900849009490104901149012490134901449015490164901749018490194902049021490224902349024490254902649027490284902949030490314903249033490344903549036490374903849039490404904149042490434904449045490464904749048490494905049051490524905349054490554905649057490584905949060490614906249063490644906549066490674906849069490704907149072490734907449075490764907749078490794908049081490824908349084490854908649087490884908949090490914909249093490944909549096490974909849099491004910149102491034910449105491064910749108491094911049111491124911349114491154911649117491184911949120491214912249123491244912549126491274912849129491304913149132491334913449135491364913749138491394914049141491424914349144491454914649147491484914949150491514915249153491544915549156491574915849159491604916149162491634916449165491664916749168491694917049171491724917349174491754917649177491784917949180491814918249183491844918549186491874918849189491904919149192491934919449195491964919749198491994920049201492024920349204492054920649207492084920949210492114921249213492144921549216492174921849219492204922149222492234922449225492264922749228492294923049231492324923349234492354923649237492384923949240492414924249243492444924549246492474924849249492504925149252492534925449255492564925749258492594926049261492624926349264492654926649267492684926949270492714927249273492744927549276492774927849279492804928149282492834928449285492864928749288492894929049291492924929349294492954929649297492984929949300493014930249303493044930549306493074930849309493104931149312493134931449315493164931749318493194932049321493224932349324493254932649327493284932949330493314933249333493344933549336493374933849339493404934149342493434934449345493464934749348493494935049351493524935349354493554935649357493584935949360493614936249363493644936549366493674936849369493704937149372493734937449375493764937749378493794938049381493824938349384493854938649387493884938949390493914939249393493944939549396493974939849399494004940149402494034940449405494064940749408494094941049411494124941349414494154941649417494184941949420494214942249423494244942549426494274942849429494304943149432494334943449435494364943749438494394944049441494424944349444494454944649447494484944949450494514945249453494544945549456494574945849459494604946149462494634946449465494664946749468494694947049471494724947349474494754947649477494784947949480494814948249483494844948549486494874948849489494904949149492494934949449495494964949749498494994950049501495024950349504495054950649507495084950949510495114951249513495144951549516495174951849519495204952149522495234952449525495264952749528495294953049531495324953349534495354953649537495384953949540495414954249543495444954549546495474954849549495504955149552495534955449555495564955749558495594956049561495624956349564495654956649567495684956949570495714957249573495744957549576495774957849579495804958149582495834958449585495864958749588495894959049591495924959349594495954959649597495984959949600496014960249603496044960549606496074960849609496104961149612496134961449615496164961749618496194962049621496224962349624496254962649627496284962949630496314963249633496344963549636496374963849639496404964149642496434964449645496464964749648496494965049651496524965349654496554965649657496584965949660496614966249663496644966549666496674966849669496704967149672496734967449675496764967749678496794968049681496824968349684496854968649687496884968949690496914969249693496944969549696496974969849699497004970149702497034970449705497064970749708497094971049711497124971349714497154971649717497184971949720497214972249723497244972549726497274972849729497304973149732497334973449735497364973749738497394974049741497424974349744497454974649747497484974949750497514975249753497544975549756497574975849759497604976149762497634976449765497664976749768497694977049771497724977349774497754977649777497784977949780497814978249783497844978549786497874978849789497904979149792497934979449795497964979749798497994980049801498024980349804498054980649807498084980949810498114981249813498144981549816498174981849819498204982149822498234982449825498264982749828498294983049831498324983349834498354983649837498384983949840498414984249843498444984549846498474984849849498504985149852498534985449855498564985749858498594986049861498624986349864498654986649867498684986949870498714987249873498744987549876498774987849879498804988149882498834988449885498864988749888498894989049891498924989349894498954989649897498984989949900499014990249903499044990549906499074990849909499104991149912499134991449915499164991749918499194992049921499224992349924499254992649927499284992949930499314993249933499344993549936499374993849939499404994149942499434994449945499464994749948499494995049951499524995349954499554995649957499584995949960499614996249963499644996549966499674996849969499704997149972499734997449975499764997749978499794998049981499824998349984499854998649987499884998949990499914999249993499944999549996499974999849999500005000150002500035000450005500065000750008500095001050011500125001350014500155001650017500185001950020500215002250023500245002550026500275002850029500305003150032500335003450035500365003750038500395004050041500425004350044500455004650047500485004950050500515005250053500545005550056500575005850059500605006150062500635006450065500665006750068500695007050071500725007350074500755007650077500785007950080500815008250083500845008550086500875008850089500905009150092500935009450095500965009750098500995010050101501025010350104501055010650107501085010950110501115011250113501145011550116501175011850119501205012150122501235012450125501265012750128501295013050131501325013350134501355013650137501385013950140501415014250143501445014550146501475014850149501505015150152501535015450155501565015750158501595016050161501625016350164501655016650167501685016950170501715017250173501745017550176501775017850179501805018150182501835018450185501865018750188501895019050191501925019350194501955019650197501985019950200502015020250203502045020550206502075020850209502105021150212502135021450215502165021750218502195022050221502225022350224502255022650227502285022950230502315023250233502345023550236502375023850239502405024150242502435024450245502465024750248502495025050251502525025350254502555025650257502585025950260502615026250263502645026550266502675026850269502705027150272502735027450275502765027750278502795028050281502825028350284502855028650287502885028950290502915029250293502945029550296502975029850299503005030150302503035030450305503065030750308503095031050311503125031350314503155031650317503185031950320503215032250323503245032550326503275032850329503305033150332503335033450335503365033750338503395034050341503425034350344503455034650347503485034950350503515035250353503545035550356503575035850359503605036150362503635036450365503665036750368503695037050371503725037350374503755037650377503785037950380503815038250383503845038550386503875038850389503905039150392503935039450395503965039750398503995040050401504025040350404504055040650407504085040950410504115041250413504145041550416504175041850419504205042150422504235042450425504265042750428504295043050431504325043350434504355043650437504385043950440504415044250443504445044550446504475044850449504505045150452504535045450455504565045750458504595046050461504625046350464504655046650467504685046950470504715047250473504745047550476504775047850479504805048150482504835048450485504865048750488504895049050491504925049350494504955049650497504985049950500505015050250503505045050550506505075050850509505105051150512505135051450515505165051750518505195052050521505225052350524505255052650527505285052950530505315053250533505345053550536505375053850539505405054150542505435054450545505465054750548505495055050551505525055350554505555055650557505585055950560505615056250563505645056550566505675056850569505705057150572505735057450575505765057750578505795058050581505825058350584505855058650587505885058950590505915059250593505945059550596505975059850599506005060150602506035060450605506065060750608506095061050611506125061350614506155061650617506185061950620506215062250623506245062550626506275062850629506305063150632506335063450635506365063750638506395064050641506425064350644506455064650647506485064950650506515065250653506545065550656506575065850659506605066150662506635066450665506665066750668506695067050671506725067350674506755067650677506785067950680506815068250683506845068550686506875068850689506905069150692506935069450695506965069750698506995070050701507025070350704507055070650707507085070950710507115071250713507145071550716507175071850719507205072150722507235072450725507265072750728507295073050731507325073350734507355073650737507385073950740507415074250743507445074550746507475074850749507505075150752507535075450755507565075750758507595076050761507625076350764507655076650767507685076950770507715077250773507745077550776507775077850779507805078150782507835078450785507865078750788507895079050791507925079350794507955079650797507985079950800508015080250803508045080550806508075080850809508105081150812508135081450815508165081750818508195082050821508225082350824508255082650827508285082950830508315083250833508345083550836508375083850839508405084150842508435084450845508465084750848508495085050851508525085350854508555085650857508585085950860508615086250863508645086550866508675086850869508705087150872508735087450875508765087750878508795088050881508825088350884508855088650887508885088950890508915089250893508945089550896508975089850899509005090150902509035090450905509065090750908509095091050911509125091350914509155091650917509185091950920509215092250923509245092550926509275092850929509305093150932509335093450935509365093750938509395094050941509425094350944509455094650947509485094950950509515095250953509545095550956509575095850959509605096150962509635096450965509665096750968509695097050971509725097350974509755097650977509785097950980509815098250983509845098550986509875098850989509905099150992509935099450995509965099750998509995100051001510025100351004510055100651007510085100951010510115101251013510145101551016510175101851019510205102151022510235102451025510265102751028510295103051031510325103351034510355103651037510385103951040510415104251043510445104551046510475104851049510505105151052510535105451055510565105751058510595106051061510625106351064510655106651067510685106951070510715107251073510745107551076510775107851079510805108151082510835108451085510865108751088510895109051091510925109351094510955109651097510985109951100511015110251103511045110551106511075110851109511105111151112511135111451115511165111751118511195112051121511225112351124511255112651127511285112951130511315113251133511345113551136511375113851139511405114151142511435114451145511465114751148511495115051151511525115351154511555115651157511585115951160511615116251163511645116551166511675116851169511705117151172511735117451175511765117751178511795118051181511825118351184511855118651187511885118951190511915119251193511945119551196511975119851199512005120151202512035120451205512065120751208512095121051211512125121351214512155121651217512185121951220512215122251223512245122551226512275122851229512305123151232512335123451235512365123751238512395124051241512425124351244512455124651247512485124951250512515125251253512545125551256512575125851259512605126151262512635126451265512665126751268512695127051271512725127351274512755127651277512785127951280512815128251283512845128551286512875128851289512905129151292512935129451295512965129751298512995130051301513025130351304513055130651307513085130951310513115131251313513145131551316513175131851319513205132151322513235132451325513265132751328513295133051331513325133351334513355133651337513385133951340513415134251343513445134551346513475134851349513505135151352513535135451355513565135751358513595136051361513625136351364513655136651367513685136951370513715137251373513745137551376513775137851379513805138151382513835138451385513865138751388513895139051391513925139351394513955139651397513985139951400514015140251403514045140551406514075140851409514105141151412514135141451415514165141751418514195142051421514225142351424514255142651427514285142951430514315143251433514345143551436514375143851439514405144151442514435144451445514465144751448514495145051451514525145351454514555145651457514585145951460514615146251463514645146551466514675146851469514705147151472514735147451475514765147751478514795148051481514825148351484514855148651487514885148951490514915149251493514945149551496514975149851499515005150151502515035150451505515065150751508515095151051511515125151351514515155151651517515185151951520515215152251523515245152551526515275152851529515305153151532515335153451535515365153751538515395154051541515425154351544515455154651547515485154951550515515155251553515545155551556515575155851559515605156151562515635156451565515665156751568515695157051571515725157351574515755157651577515785157951580515815158251583515845158551586515875158851589515905159151592515935159451595515965159751598515995160051601516025160351604516055160651607516085160951610516115161251613516145161551616516175161851619516205162151622516235162451625516265162751628516295163051631516325163351634516355163651637516385163951640516415164251643516445164551646516475164851649516505165151652516535165451655516565165751658516595166051661516625166351664516655166651667516685166951670516715167251673516745167551676516775167851679516805168151682516835168451685516865168751688516895169051691516925169351694516955169651697516985169951700517015170251703517045170551706517075170851709517105171151712517135171451715517165171751718517195172051721517225172351724517255172651727517285172951730517315173251733517345173551736517375173851739517405174151742517435174451745517465174751748517495175051751517525175351754517555175651757517585175951760517615176251763517645176551766517675176851769517705177151772517735177451775517765177751778517795178051781517825178351784517855178651787517885178951790517915179251793517945179551796517975179851799518005180151802518035180451805518065180751808518095181051811518125181351814518155181651817518185181951820518215182251823518245182551826518275182851829518305183151832518335183451835518365183751838518395184051841518425184351844518455184651847518485184951850518515185251853518545185551856518575185851859518605186151862518635186451865518665186751868518695187051871518725187351874518755187651877518785187951880518815188251883518845188551886518875188851889518905189151892518935189451895518965189751898518995190051901519025190351904519055190651907519085190951910519115191251913519145191551916519175191851919519205192151922519235192451925519265192751928519295193051931519325193351934519355193651937519385193951940519415194251943519445194551946519475194851949519505195151952519535195451955519565195751958519595196051961519625196351964519655196651967519685196951970519715197251973519745197551976519775197851979519805198151982519835198451985519865198751988519895199051991519925199351994519955199651997519985199952000520015200252003520045200552006520075200852009520105201152012520135201452015520165201752018520195202052021520225202352024520255202652027520285202952030520315203252033520345203552036520375203852039520405204152042520435204452045520465204752048520495205052051520525205352054520555205652057520585205952060520615206252063520645206552066520675206852069520705207152072520735207452075520765207752078520795208052081520825208352084520855208652087520885208952090520915209252093520945209552096520975209852099521005210152102521035210452105521065210752108521095211052111521125211352114521155211652117521185211952120521215212252123521245212552126521275212852129521305213152132521335213452135521365213752138521395214052141521425214352144521455214652147521485214952150521515215252153521545215552156521575215852159521605216152162521635216452165521665216752168521695217052171521725217352174521755217652177521785217952180521815218252183521845218552186521875218852189521905219152192521935219452195521965219752198521995220052201522025220352204522055220652207522085220952210522115221252213522145221552216522175221852219522205222152222522235222452225522265222752228522295223052231522325223352234522355223652237522385223952240522415224252243522445224552246522475224852249522505225152252522535225452255522565225752258522595226052261522625226352264522655226652267522685226952270522715227252273522745227552276522775227852279522805228152282522835228452285522865228752288522895229052291522925229352294522955229652297522985229952300523015230252303523045230552306523075230852309523105231152312523135231452315523165231752318523195232052321523225232352324523255232652327523285232952330523315233252333523345233552336523375233852339523405234152342523435234452345523465234752348523495235052351523525235352354523555235652357523585235952360523615236252363523645236552366523675236852369523705237152372523735237452375523765237752378523795238052381523825238352384523855238652387523885238952390523915239252393523945239552396523975239852399524005240152402524035240452405524065240752408524095241052411524125241352414524155241652417524185241952420524215242252423524245242552426524275242852429524305243152432524335243452435524365243752438524395244052441524425244352444524455244652447524485244952450524515245252453524545245552456524575245852459524605246152462524635246452465524665246752468524695247052471524725247352474524755247652477524785247952480524815248252483524845248552486524875248852489524905249152492524935249452495524965249752498524995250052501525025250352504525055250652507525085250952510525115251252513525145251552516525175251852519525205252152522525235252452525525265252752528525295253052531525325253352534525355253652537525385253952540525415254252543525445254552546525475254852549525505255152552525535255452555525565255752558525595256052561525625256352564525655256652567525685256952570525715257252573525745257552576525775257852579525805258152582525835258452585525865258752588525895259052591525925259352594525955259652597525985259952600526015260252603526045260552606526075260852609526105261152612526135261452615526165261752618526195262052621526225262352624526255262652627526285262952630526315263252633526345263552636526375263852639526405264152642526435264452645526465264752648526495265052651526525265352654526555265652657526585265952660526615266252663526645266552666526675266852669526705267152672526735267452675526765267752678526795268052681526825268352684526855268652687526885268952690526915269252693526945269552696526975269852699527005270152702527035270452705527065270752708527095271052711527125271352714527155271652717527185271952720527215272252723527245272552726527275272852729527305273152732527335273452735527365273752738527395274052741527425274352744527455274652747527485274952750527515275252753527545275552756527575275852759527605276152762527635276452765527665276752768527695277052771527725277352774527755277652777527785277952780527815278252783527845278552786527875278852789527905279152792527935279452795527965279752798527995280052801528025280352804528055280652807528085280952810528115281252813528145281552816528175281852819528205282152822528235282452825528265282752828528295283052831528325283352834528355283652837528385283952840528415284252843528445284552846528475284852849528505285152852528535285452855528565285752858528595286052861528625286352864528655286652867528685286952870528715287252873528745287552876528775287852879528805288152882528835288452885528865288752888528895289052891528925289352894528955289652897528985289952900529015290252903529045290552906529075290852909529105291152912529135291452915529165291752918529195292052921529225292352924529255292652927529285292952930529315293252933529345293552936529375293852939529405294152942529435294452945529465294752948529495295052951529525295352954529555295652957529585295952960529615296252963529645296552966529675296852969529705297152972529735297452975529765297752978529795298052981529825298352984529855298652987529885298952990529915299252993529945299552996529975299852999530005300153002530035300453005530065300753008530095301053011530125301353014530155301653017530185301953020530215302253023530245302553026530275302853029530305303153032530335303453035530365303753038530395304053041530425304353044530455304653047530485304953050530515305253053530545305553056530575305853059530605306153062530635306453065530665306753068530695307053071530725307353074530755307653077530785307953080530815308253083530845308553086530875308853089530905309153092530935309453095530965309753098530995310053101531025310353104531055310653107531085310953110531115311253113531145311553116531175311853119531205312153122531235312453125531265312753128531295313053131531325313353134531355313653137531385313953140531415314253143531445314553146531475314853149531505315153152531535315453155531565315753158531595316053161531625316353164531655316653167531685316953170531715317253173531745317553176531775317853179531805318153182531835318453185531865318753188531895319053191531925319353194531955319653197531985319953200532015320253203532045320553206532075320853209532105321153212532135321453215532165321753218532195322053221532225322353224532255322653227532285322953230532315323253233532345323553236532375323853239532405324153242532435324453245532465324753248532495325053251532525325353254532555325653257532585325953260532615326253263532645326553266532675326853269532705327153272532735327453275532765327753278532795328053281532825328353284532855328653287532885328953290532915329253293532945329553296532975329853299533005330153302533035330453305533065330753308533095331053311533125331353314533155331653317533185331953320533215332253323533245332553326533275332853329533305333153332533335333453335533365333753338533395334053341533425334353344533455334653347533485334953350533515335253353533545335553356533575335853359533605336153362533635336453365533665336753368533695337053371533725337353374533755337653377533785337953380533815338253383533845338553386533875338853389533905339153392533935339453395533965339753398533995340053401534025340353404534055340653407534085340953410534115341253413534145341553416534175341853419534205342153422534235342453425534265342753428534295343053431534325343353434534355343653437534385343953440534415344253443534445344553446534475344853449534505345153452534535345453455534565345753458534595346053461534625346353464534655346653467534685346953470534715347253473534745347553476534775347853479534805348153482534835348453485534865348753488534895349053491534925349353494534955349653497534985349953500535015350253503535045350553506535075350853509535105351153512535135351453515535165351753518535195352053521535225352353524535255352653527535285352953530535315353253533535345353553536535375353853539535405354153542535435354453545535465354753548535495355053551535525355353554535555355653557535585355953560535615356253563535645356553566535675356853569535705357153572535735357453575535765357753578535795358053581535825358353584535855358653587535885358953590535915359253593535945359553596535975359853599536005360153602536035360453605536065360753608536095361053611536125361353614536155361653617536185361953620536215362253623536245362553626536275362853629536305363153632536335363453635536365363753638536395364053641536425364353644536455364653647536485364953650536515365253653536545365553656536575365853659536605366153662536635366453665536665366753668536695367053671536725367353674536755367653677536785367953680536815368253683536845368553686536875368853689536905369153692536935369453695536965369753698536995370053701537025370353704537055370653707537085370953710537115371253713537145371553716537175371853719537205372153722537235372453725537265372753728537295373053731537325373353734537355373653737537385373953740537415374253743537445374553746537475374853749537505375153752537535375453755537565375753758537595376053761537625376353764537655376653767537685376953770537715377253773537745377553776537775377853779537805378153782537835378453785537865378753788537895379053791537925379353794537955379653797537985379953800538015380253803538045380553806538075380853809538105381153812538135381453815538165381753818538195382053821538225382353824538255382653827538285382953830538315383253833538345383553836538375383853839538405384153842538435384453845538465384753848538495385053851538525385353854538555385653857538585385953860538615386253863538645386553866538675386853869538705387153872538735387453875538765387753878538795388053881538825388353884538855388653887538885388953890538915389253893538945389553896538975389853899539005390153902539035390453905539065390753908539095391053911539125391353914539155391653917539185391953920539215392253923539245392553926539275392853929539305393153932539335393453935539365393753938539395394053941539425394353944539455394653947539485394953950539515395253953539545395553956539575395853959539605396153962539635396453965539665396753968539695397053971539725397353974539755397653977539785397953980539815398253983539845398553986539875398853989539905399153992539935399453995539965399753998539995400054001540025400354004540055400654007540085400954010540115401254013540145401554016540175401854019540205402154022540235402454025540265402754028540295403054031540325403354034540355403654037540385403954040540415404254043540445404554046540475404854049540505405154052540535405454055540565405754058540595406054061540625406354064540655406654067540685406954070540715407254073540745407554076540775407854079540805408154082540835408454085540865408754088540895409054091540925409354094540955409654097540985409954100541015410254103541045410554106541075410854109541105411154112541135411454115541165411754118541195412054121541225412354124541255412654127541285412954130541315413254133541345413554136541375413854139541405414154142541435414454145541465414754148541495415054151541525415354154541555415654157541585415954160541615416254163541645416554166541675416854169541705417154172541735417454175541765417754178541795418054181541825418354184541855418654187541885418954190541915419254193541945419554196541975419854199542005420154202542035420454205542065420754208542095421054211542125421354214542155421654217542185421954220542215422254223542245422554226542275422854229542305423154232542335423454235542365423754238542395424054241542425424354244542455424654247542485424954250542515425254253542545425554256542575425854259542605426154262542635426454265542665426754268542695427054271542725427354274542755427654277542785427954280542815428254283542845428554286542875428854289542905429154292542935429454295542965429754298542995430054301543025430354304543055430654307543085430954310543115431254313543145431554316543175431854319543205432154322543235432454325543265432754328543295433054331543325433354334543355433654337543385433954340543415434254343543445434554346543475434854349543505435154352543535435454355543565435754358543595436054361543625436354364543655436654367543685436954370543715437254373543745437554376543775437854379543805438154382543835438454385543865438754388543895439054391543925439354394543955439654397543985439954400544015440254403544045440554406544075440854409544105441154412544135441454415544165441754418544195442054421544225442354424544255442654427544285442954430544315443254433544345443554436544375443854439544405444154442544435444454445544465444754448544495445054451544525445354454544555445654457544585445954460544615446254463544645446554466544675446854469544705447154472544735447454475544765447754478544795448054481544825448354484544855448654487544885448954490544915449254493544945449554496544975449854499545005450154502545035450454505545065450754508545095451054511545125451354514545155451654517545185451954520545215452254523545245452554526545275452854529545305453154532545335453454535545365453754538545395454054541545425454354544545455454654547545485454954550545515455254553545545455554556545575455854559545605456154562545635456454565545665456754568545695457054571545725457354574545755457654577545785457954580545815458254583545845458554586545875458854589545905459154592545935459454595545965459754598545995460054601546025460354604546055460654607546085460954610546115461254613546145461554616546175461854619546205462154622546235462454625546265462754628546295463054631546325463354634546355463654637546385463954640546415464254643546445464554646546475464854649546505465154652546535465454655546565465754658546595466054661546625466354664546655466654667546685466954670546715467254673546745467554676546775467854679546805468154682546835468454685546865468754688546895469054691546925469354694546955469654697546985469954700547015470254703547045470554706547075470854709547105471154712547135471454715547165471754718547195472054721547225472354724547255472654727547285472954730547315473254733547345473554736547375473854739547405474154742547435474454745547465474754748547495475054751547525475354754547555475654757547585475954760547615476254763547645476554766547675476854769547705477154772547735477454775547765477754778547795478054781547825478354784547855478654787547885478954790547915479254793547945479554796547975479854799548005480154802548035480454805548065480754808548095481054811548125481354814548155481654817548185481954820548215482254823548245482554826548275482854829548305483154832548335483454835548365483754838548395484054841548425484354844548455484654847548485484954850548515485254853548545485554856548575485854859548605486154862548635486454865548665486754868548695487054871548725487354874548755487654877548785487954880548815488254883548845488554886548875488854889548905489154892548935489454895548965489754898548995490054901549025490354904549055490654907549085490954910549115491254913549145491554916549175491854919549205492154922549235492454925549265492754928549295493054931549325493354934549355493654937549385493954940549415494254943549445494554946549475494854949549505495154952549535495454955549565495754958549595496054961549625496354964549655496654967549685496954970549715497254973549745497554976549775497854979549805498154982549835498454985549865498754988549895499054991549925499354994549955499654997549985499955000550015500255003550045500555006550075500855009550105501155012550135501455015550165501755018550195502055021550225502355024550255502655027550285502955030550315503255033550345503555036550375503855039550405504155042550435504455045550465504755048550495505055051550525505355054550555505655057550585505955060550615506255063550645506555066550675506855069550705507155072550735507455075550765507755078550795508055081550825508355084550855508655087550885508955090550915509255093550945509555096550975509855099551005510155102551035510455105551065510755108551095511055111551125511355114551155511655117551185511955120551215512255123551245512555126551275512855129551305513155132551335513455135551365513755138551395514055141551425514355144551455514655147551485514955150551515515255153551545515555156551575515855159551605516155162551635516455165551665516755168551695517055171551725517355174551755517655177551785517955180551815518255183551845518555186551875518855189551905519155192551935519455195551965519755198551995520055201552025520355204552055520655207552085520955210552115521255213552145521555216552175521855219552205522155222552235522455225552265522755228552295523055231552325523355234552355523655237552385523955240552415524255243552445524555246552475524855249552505525155252552535525455255552565525755258552595526055261552625526355264552655526655267552685526955270552715527255273552745527555276552775527855279552805528155282552835528455285552865528755288552895529055291552925529355294552955529655297552985529955300553015530255303553045530555306553075530855309553105531155312553135531455315553165531755318553195532055321553225532355324553255532655327553285532955330553315533255333553345533555336553375533855339553405534155342553435534455345553465534755348553495535055351553525535355354553555535655357553585535955360553615536255363553645536555366553675536855369553705537155372553735537455375553765537755378553795538055381553825538355384553855538655387553885538955390553915539255393553945539555396553975539855399554005540155402554035540455405554065540755408554095541055411554125541355414554155541655417554185541955420554215542255423554245542555426554275542855429554305543155432554335543455435554365543755438554395544055441554425544355444554455544655447554485544955450554515545255453554545545555456554575545855459554605546155462554635546455465554665546755468554695547055471554725547355474554755547655477554785547955480554815548255483554845548555486554875548855489554905549155492554935549455495554965549755498554995550055501555025550355504555055550655507555085550955510555115551255513555145551555516555175551855519555205552155522555235552455525555265552755528555295553055531555325553355534555355553655537555385553955540555415554255543555445554555546555475554855549555505555155552555535555455555555565555755558555595556055561555625556355564555655556655567555685556955570555715557255573555745557555576555775557855579555805558155582555835558455585555865558755588555895559055591555925559355594555955559655597555985559955600556015560255603556045560555606556075560855609556105561155612556135561455615556165561755618556195562055621556225562355624556255562655627556285562955630556315563255633556345563555636556375563855639556405564155642556435564455645556465564755648556495565055651556525565355654556555565655657556585565955660556615566255663556645566555666556675566855669556705567155672556735567455675556765567755678556795568055681556825568355684556855568655687556885568955690556915569255693556945569555696556975569855699557005570155702557035570455705557065570755708557095571055711557125571355714557155571655717557185571955720557215572255723557245572555726557275572855729557305573155732557335573455735557365573755738557395574055741557425574355744557455574655747557485574955750557515575255753557545575555756557575575855759557605576155762557635576455765557665576755768557695577055771557725577355774557755577655777557785577955780557815578255783557845578555786557875578855789557905579155792557935579455795557965579755798557995580055801558025580355804558055580655807558085580955810558115581255813558145581555816558175581855819558205582155822558235582455825558265582755828558295583055831558325583355834558355583655837558385583955840558415584255843558445584555846558475584855849558505585155852558535585455855558565585755858558595586055861558625586355864558655586655867558685586955870558715587255873558745587555876558775587855879558805588155882558835588455885558865588755888558895589055891558925589355894558955589655897558985589955900559015590255903559045590555906559075590855909559105591155912559135591455915559165591755918559195592055921559225592355924559255592655927559285592955930559315593255933559345593555936559375593855939559405594155942559435594455945559465594755948559495595055951559525595355954559555595655957559585595955960559615596255963559645596555966559675596855969559705597155972559735597455975559765597755978559795598055981559825598355984559855598655987559885598955990559915599255993559945599555996559975599855999560005600156002560035600456005560065600756008560095601056011560125601356014560155601656017560185601956020560215602256023560245602556026560275602856029560305603156032560335603456035560365603756038560395604056041560425604356044560455604656047560485604956050560515605256053560545605556056560575605856059560605606156062560635606456065560665606756068560695607056071560725607356074560755607656077560785607956080560815608256083560845608556086560875608856089560905609156092560935609456095560965609756098560995610056101561025610356104561055610656107561085610956110561115611256113561145611556116561175611856119561205612156122561235612456125561265612756128561295613056131561325613356134561355613656137561385613956140561415614256143561445614556146561475614856149561505615156152561535615456155561565615756158561595616056161561625616356164561655616656167561685616956170561715617256173561745617556176561775617856179561805618156182561835618456185561865618756188561895619056191561925619356194561955619656197561985619956200562015620256203562045620556206562075620856209562105621156212562135621456215562165621756218562195622056221562225622356224562255622656227562285622956230562315623256233562345623556236562375623856239562405624156242562435624456245562465624756248562495625056251562525625356254562555625656257562585625956260562615626256263562645626556266562675626856269562705627156272562735627456275562765627756278562795628056281562825628356284562855628656287562885628956290562915629256293562945629556296562975629856299563005630156302563035630456305563065630756308563095631056311563125631356314563155631656317563185631956320563215632256323563245632556326563275632856329563305633156332563335633456335563365633756338563395634056341563425634356344563455634656347563485634956350563515635256353563545635556356563575635856359563605636156362563635636456365563665636756368563695637056371563725637356374563755637656377563785637956380563815638256383563845638556386563875638856389563905639156392563935639456395563965639756398563995640056401564025640356404564055640656407564085640956410564115641256413564145641556416564175641856419564205642156422564235642456425564265642756428564295643056431564325643356434564355643656437564385643956440564415644256443564445644556446564475644856449564505645156452564535645456455564565645756458564595646056461564625646356464564655646656467564685646956470564715647256473564745647556476564775647856479564805648156482564835648456485564865648756488564895649056491564925649356494564955649656497564985649956500565015650256503565045650556506565075650856509565105651156512565135651456515565165651756518565195652056521565225652356524565255652656527565285652956530565315653256533565345653556536565375653856539565405654156542565435654456545565465654756548565495655056551565525655356554565555655656557565585655956560565615656256563565645656556566565675656856569565705657156572565735657456575565765657756578565795658056581565825658356584565855658656587565885658956590565915659256593565945659556596565975659856599566005660156602566035660456605566065660756608566095661056611566125661356614566155661656617566185661956620566215662256623566245662556626566275662856629566305663156632566335663456635566365663756638566395664056641566425664356644566455664656647566485664956650566515665256653566545665556656566575665856659566605666156662566635666456665566665666756668566695667056671566725667356674566755667656677566785667956680566815668256683566845668556686566875668856689566905669156692566935669456695566965669756698566995670056701567025670356704567055670656707567085670956710567115671256713567145671556716567175671856719567205672156722567235672456725567265672756728567295673056731567325673356734567355673656737567385673956740567415674256743567445674556746567475674856749567505675156752567535675456755567565675756758567595676056761567625676356764567655676656767567685676956770567715677256773567745677556776567775677856779567805678156782567835678456785567865678756788567895679056791567925679356794567955679656797567985679956800568015680256803568045680556806568075680856809568105681156812568135681456815568165681756818568195682056821568225682356824568255682656827568285682956830568315683256833568345683556836568375683856839568405684156842568435684456845568465684756848568495685056851568525685356854568555685656857568585685956860568615686256863568645686556866568675686856869568705687156872568735687456875568765687756878568795688056881568825688356884568855688656887568885688956890568915689256893568945689556896568975689856899569005690156902569035690456905569065690756908569095691056911569125691356914569155691656917569185691956920569215692256923569245692556926569275692856929569305693156932569335693456935569365693756938569395694056941569425694356944569455694656947569485694956950569515695256953569545695556956569575695856959569605696156962569635696456965569665696756968569695697056971569725697356974569755697656977569785697956980569815698256983569845698556986569875698856989569905699156992569935699456995569965699756998569995700057001570025700357004570055700657007570085700957010570115701257013570145701557016570175701857019570205702157022570235702457025570265702757028570295703057031570325703357034570355703657037570385703957040570415704257043570445704557046570475704857049570505705157052570535705457055570565705757058570595706057061570625706357064570655706657067570685706957070570715707257073570745707557076570775707857079570805708157082570835708457085570865708757088570895709057091570925709357094570955709657097570985709957100571015710257103571045710557106571075710857109571105711157112571135711457115571165711757118571195712057121571225712357124571255712657127571285712957130571315713257133571345713557136571375713857139571405714157142571435714457145571465714757148571495715057151571525715357154571555715657157571585715957160571615716257163571645716557166571675716857169571705717157172571735717457175571765717757178571795718057181571825718357184571855718657187571885718957190571915719257193571945719557196571975719857199572005720157202572035720457205572065720757208572095721057211572125721357214572155721657217572185721957220572215722257223572245722557226572275722857229572305723157232572335723457235572365723757238572395724057241572425724357244572455724657247572485724957250572515725257253572545725557256572575725857259572605726157262572635726457265572665726757268572695727057271572725727357274572755727657277572785727957280572815728257283572845728557286572875728857289572905729157292572935729457295572965729757298572995730057301573025730357304573055730657307573085730957310573115731257313573145731557316573175731857319573205732157322573235732457325573265732757328573295733057331573325733357334573355733657337573385733957340573415734257343573445734557346573475734857349573505735157352573535735457355573565735757358573595736057361573625736357364573655736657367573685736957370573715737257373573745737557376573775737857379573805738157382573835738457385573865738757388573895739057391573925739357394573955739657397573985739957400574015740257403574045740557406574075740857409574105741157412574135741457415574165741757418574195742057421574225742357424574255742657427574285742957430574315743257433574345743557436574375743857439574405744157442574435744457445574465744757448574495745057451574525745357454574555745657457574585745957460574615746257463574645746557466574675746857469574705747157472574735747457475574765747757478574795748057481574825748357484574855748657487574885748957490574915749257493574945749557496574975749857499575005750157502575035750457505575065750757508575095751057511575125751357514575155751657517575185751957520575215752257523575245752557526575275752857529575305753157532575335753457535575365753757538575395754057541575425754357544575455754657547575485754957550575515755257553575545755557556575575755857559575605756157562575635756457565575665756757568575695757057571575725757357574575755757657577575785757957580575815758257583575845758557586575875758857589575905759157592575935759457595575965759757598575995760057601576025760357604576055760657607576085760957610576115761257613576145761557616576175761857619576205762157622576235762457625576265762757628576295763057631576325763357634576355763657637576385763957640576415764257643576445764557646576475764857649576505765157652576535765457655576565765757658576595766057661576625766357664576655766657667576685766957670576715767257673576745767557676576775767857679576805768157682576835768457685576865768757688576895769057691576925769357694576955769657697576985769957700577015770257703577045770557706577075770857709577105771157712577135771457715577165771757718577195772057721577225772357724577255772657727577285772957730577315773257733577345773557736577375773857739577405774157742577435774457745577465774757748577495775057751577525775357754577555775657757577585775957760577615776257763577645776557766577675776857769577705777157772577735777457775577765777757778577795778057781577825778357784577855778657787577885778957790577915779257793577945779557796577975779857799578005780157802578035780457805578065780757808578095781057811578125781357814578155781657817578185781957820578215782257823578245782557826578275782857829578305783157832578335783457835578365783757838578395784057841578425784357844578455784657847578485784957850578515785257853578545785557856578575785857859578605786157862578635786457865578665786757868578695787057871578725787357874578755787657877578785787957880578815788257883578845788557886578875788857889578905789157892578935789457895578965789757898578995790057901579025790357904579055790657907579085790957910579115791257913579145791557916579175791857919579205792157922579235792457925579265792757928579295793057931579325793357934579355793657937579385793957940579415794257943579445794557946579475794857949579505795157952579535795457955579565795757958579595796057961579625796357964579655796657967579685796957970579715797257973579745797557976579775797857979579805798157982579835798457985579865798757988579895799057991579925799357994579955799657997579985799958000580015800258003580045800558006580075800858009580105801158012580135801458015580165801758018580195802058021580225802358024580255802658027580285802958030580315803258033580345803558036580375803858039580405804158042580435804458045580465804758048580495805058051580525805358054580555805658057580585805958060580615806258063580645806558066580675806858069580705807158072580735807458075580765807758078580795808058081580825808358084580855808658087580885808958090580915809258093580945809558096580975809858099581005810158102581035810458105581065810758108581095811058111581125811358114581155811658117581185811958120581215812258123581245812558126581275812858129581305813158132581335813458135581365813758138581395814058141581425814358144581455814658147581485814958150581515815258153581545815558156581575815858159581605816158162581635816458165581665816758168581695817058171581725817358174581755817658177581785817958180581815818258183581845818558186581875818858189581905819158192581935819458195581965819758198581995820058201582025820358204582055820658207582085820958210582115821258213582145821558216582175821858219582205822158222582235822458225582265822758228582295823058231582325823358234582355823658237582385823958240582415824258243582445824558246582475824858249582505825158252582535825458255582565825758258582595826058261582625826358264582655826658267582685826958270582715827258273582745827558276582775827858279582805828158282582835828458285582865828758288582895829058291582925829358294582955829658297582985829958300583015830258303583045830558306583075830858309583105831158312583135831458315583165831758318583195832058321583225832358324583255832658327583285832958330583315833258333583345833558336583375833858339583405834158342583435834458345583465834758348583495835058351583525835358354583555835658357583585835958360583615836258363583645836558366583675836858369583705837158372583735837458375583765837758378583795838058381583825838358384583855838658387583885838958390583915839258393583945839558396583975839858399584005840158402584035840458405584065840758408584095841058411584125841358414584155841658417584185841958420584215842258423584245842558426584275842858429584305843158432584335843458435584365843758438584395844058441584425844358444584455844658447584485844958450584515845258453584545845558456584575845858459584605846158462584635846458465584665846758468584695847058471584725847358474584755847658477584785847958480584815848258483584845848558486584875848858489584905849158492584935849458495584965849758498584995850058501585025850358504585055850658507585085850958510585115851258513585145851558516585175851858519585205852158522585235852458525585265852758528585295853058531585325853358534585355853658537585385853958540585415854258543585445854558546585475854858549585505855158552585535855458555585565855758558585595856058561585625856358564585655856658567585685856958570585715857258573585745857558576585775857858579585805858158582585835858458585585865858758588585895859058591585925859358594585955859658597585985859958600586015860258603586045860558606586075860858609586105861158612586135861458615586165861758618586195862058621586225862358624586255862658627586285862958630586315863258633586345863558636586375863858639586405864158642586435864458645586465864758648586495865058651586525865358654586555865658657586585865958660586615866258663586645866558666586675866858669586705867158672586735867458675586765867758678586795868058681586825868358684586855868658687586885868958690586915869258693586945869558696586975869858699587005870158702587035870458705587065870758708587095871058711587125871358714587155871658717587185871958720587215872258723587245872558726587275872858729587305873158732587335873458735587365873758738587395874058741587425874358744587455874658747587485874958750587515875258753587545875558756587575875858759587605876158762587635876458765587665876758768587695877058771587725877358774587755877658777587785877958780587815878258783587845878558786587875878858789587905879158792587935879458795587965879758798587995880058801588025880358804588055880658807588085880958810588115881258813588145881558816588175881858819588205882158822588235882458825588265882758828588295883058831588325883358834588355883658837588385883958840588415884258843588445884558846588475884858849588505885158852588535885458855588565885758858588595886058861588625886358864588655886658867588685886958870588715887258873588745887558876588775887858879588805888158882588835888458885588865888758888588895889058891588925889358894588955889658897588985889958900589015890258903589045890558906589075890858909589105891158912589135891458915589165891758918589195892058921589225892358924589255892658927589285892958930589315893258933589345893558936589375893858939589405894158942589435894458945589465894758948589495895058951589525895358954589555895658957589585895958960589615896258963589645896558966589675896858969589705897158972589735897458975589765897758978589795898058981589825898358984589855898658987589885898958990589915899258993589945899558996589975899858999590005900159002590035900459005590065900759008590095901059011590125901359014590155901659017590185901959020590215902259023590245902559026590275902859029590305903159032590335903459035590365903759038590395904059041590425904359044590455904659047590485904959050590515905259053590545905559056590575905859059590605906159062590635906459065590665906759068590695907059071590725907359074590755907659077590785907959080590815908259083590845908559086590875908859089590905909159092590935909459095590965909759098590995910059101591025910359104591055910659107591085910959110591115911259113591145911559116591175911859119591205912159122591235912459125591265912759128591295913059131591325913359134591355913659137591385913959140591415914259143591445914559146591475914859149591505915159152591535915459155591565915759158591595916059161591625916359164591655916659167591685916959170591715917259173591745917559176591775917859179591805918159182591835918459185591865918759188591895919059191591925919359194591955919659197591985919959200592015920259203592045920559206592075920859209592105921159212592135921459215592165921759218592195922059221592225922359224592255922659227592285922959230592315923259233592345923559236592375923859239592405924159242592435924459245592465924759248592495925059251592525925359254592555925659257592585925959260592615926259263592645926559266592675926859269592705927159272592735927459275592765927759278592795928059281592825928359284592855928659287592885928959290592915929259293592945929559296592975929859299593005930159302593035930459305593065930759308593095931059311593125931359314593155931659317593185931959320593215932259323593245932559326593275932859329593305933159332593335933459335593365933759338593395934059341593425934359344593455934659347593485934959350593515935259353593545935559356593575935859359593605936159362593635936459365593665936759368593695937059371593725937359374593755937659377593785937959380593815938259383593845938559386593875938859389593905939159392593935939459395593965939759398593995940059401594025940359404594055940659407594085940959410594115941259413594145941559416594175941859419594205942159422594235942459425594265942759428594295943059431594325943359434594355943659437594385943959440594415944259443594445944559446594475944859449594505945159452594535945459455594565945759458594595946059461594625946359464594655946659467594685946959470594715947259473594745947559476594775947859479594805948159482594835948459485594865948759488594895949059491594925949359494594955949659497594985949959500595015950259503595045950559506595075950859509595105951159512595135951459515595165951759518595195952059521595225952359524595255952659527595285952959530595315953259533595345953559536595375953859539595405954159542595435954459545595465954759548595495955059551595525955359554595555955659557595585955959560595615956259563595645956559566595675956859569595705957159572595735957459575595765957759578595795958059581595825958359584595855958659587595885958959590595915959259593595945959559596595975959859599596005960159602596035960459605596065960759608596095961059611596125961359614596155961659617596185961959620596215962259623596245962559626596275962859629596305963159632596335963459635596365963759638596395964059641596425964359644596455964659647596485964959650596515965259653596545965559656596575965859659596605966159662596635966459665596665966759668596695967059671596725967359674596755967659677596785967959680596815968259683596845968559686596875968859689596905969159692596935969459695596965969759698596995970059701597025970359704597055970659707597085970959710597115971259713597145971559716597175971859719597205972159722597235972459725597265972759728597295973059731597325973359734597355973659737597385973959740597415974259743597445974559746597475974859749597505975159752597535975459755597565975759758597595976059761597625976359764597655976659767597685976959770597715977259773597745977559776597775977859779597805978159782597835978459785597865978759788597895979059791597925979359794597955979659797597985979959800598015980259803598045980559806598075980859809598105981159812598135981459815598165981759818598195982059821598225982359824598255982659827598285982959830598315983259833598345983559836598375983859839598405984159842598435984459845598465984759848598495985059851598525985359854598555985659857598585985959860598615986259863598645986559866598675986859869598705987159872598735987459875598765987759878598795988059881598825988359884598855988659887598885988959890598915989259893598945989559896598975989859899599005990159902599035990459905599065990759908599095991059911599125991359914599155991659917599185991959920599215992259923599245992559926599275992859929599305993159932599335993459935599365993759938599395994059941599425994359944599455994659947599485994959950599515995259953599545995559956599575995859959599605996159962599635996459965599665996759968599695997059971599725997359974599755997659977599785997959980599815998259983599845998559986599875998859989599905999159992599935999459995599965999759998599996000060001600026000360004600056000660007600086000960010600116001260013600146001560016600176001860019600206002160022600236002460025600266002760028600296003060031600326003360034600356003660037600386003960040600416004260043600446004560046600476004860049600506005160052600536005460055600566005760058600596006060061600626006360064600656006660067600686006960070600716007260073600746007560076600776007860079600806008160082600836008460085600866008760088600896009060091600926009360094600956009660097600986009960100601016010260103601046010560106601076010860109601106011160112601136011460115601166011760118601196012060121601226012360124601256012660127601286012960130601316013260133601346013560136601376013860139601406014160142601436014460145601466014760148601496015060151601526015360154601556015660157601586015960160601616016260163601646016560166601676016860169601706017160172601736017460175601766017760178601796018060181601826018360184601856018660187601886018960190601916019260193601946019560196601976019860199602006020160202602036020460205602066020760208602096021060211602126021360214602156021660217602186021960220602216022260223602246022560226602276022860229602306023160232602336023460235602366023760238602396024060241602426024360244602456024660247602486024960250602516025260253602546025560256602576025860259602606026160262602636026460265602666026760268602696027060271602726027360274602756027660277602786027960280602816028260283602846028560286602876028860289602906029160292602936029460295602966029760298602996030060301603026030360304603056030660307603086030960310603116031260313603146031560316603176031860319603206032160322603236032460325603266032760328603296033060331603326033360334603356033660337603386033960340603416034260343603446034560346603476034860349603506035160352603536035460355603566035760358603596036060361603626036360364603656036660367603686036960370603716037260373603746037560376603776037860379603806038160382603836038460385603866038760388603896039060391603926039360394603956039660397603986039960400604016040260403604046040560406604076040860409604106041160412604136041460415604166041760418604196042060421604226042360424604256042660427604286042960430604316043260433604346043560436604376043860439604406044160442604436044460445604466044760448604496045060451604526045360454604556045660457604586045960460604616046260463604646046560466604676046860469604706047160472604736047460475604766047760478604796048060481604826048360484604856048660487604886048960490604916049260493604946049560496604976049860499605006050160502605036050460505605066050760508605096051060511605126051360514605156051660517605186051960520605216052260523605246052560526605276052860529605306053160532605336053460535605366053760538605396054060541605426054360544605456054660547605486054960550605516055260553605546055560556605576055860559605606056160562605636056460565605666056760568605696057060571605726057360574605756057660577605786057960580605816058260583605846058560586605876058860589605906059160592605936059460595605966059760598605996060060601606026060360604606056060660607606086060960610606116061260613606146061560616606176061860619606206062160622606236062460625606266062760628606296063060631606326063360634606356063660637606386063960640606416064260643606446064560646606476064860649606506065160652606536065460655606566065760658606596066060661606626066360664606656066660667606686066960670606716067260673606746067560676606776067860679606806068160682606836068460685606866068760688606896069060691606926069360694606956069660697606986069960700607016070260703607046070560706607076070860709607106071160712607136071460715607166071760718607196072060721607226072360724607256072660727607286072960730607316073260733607346073560736607376073860739607406074160742607436074460745607466074760748607496075060751607526075360754607556075660757607586075960760607616076260763607646076560766607676076860769607706077160772607736077460775607766077760778607796078060781607826078360784607856078660787607886078960790607916079260793607946079560796607976079860799608006080160802608036080460805608066080760808608096081060811608126081360814608156081660817608186081960820608216082260823608246082560826608276082860829608306083160832608336083460835608366083760838608396084060841608426084360844608456084660847608486084960850608516085260853608546085560856608576085860859608606086160862608636086460865608666086760868608696087060871608726087360874608756087660877608786087960880608816088260883608846088560886608876088860889608906089160892608936089460895608966089760898608996090060901609026090360904609056090660907609086090960910609116091260913609146091560916609176091860919609206092160922609236092460925609266092760928609296093060931609326093360934609356093660937609386093960940609416094260943609446094560946609476094860949609506095160952609536095460955609566095760958609596096060961609626096360964609656096660967609686096960970609716097260973609746097560976609776097860979609806098160982609836098460985609866098760988609896099060991609926099360994609956099660997609986099961000610016100261003610046100561006610076100861009610106101161012610136101461015610166101761018610196102061021610226102361024610256102661027610286102961030610316103261033610346103561036610376103861039610406104161042610436104461045610466104761048610496105061051610526105361054610556105661057610586105961060610616106261063610646106561066610676106861069610706107161072610736107461075610766107761078610796108061081610826108361084610856108661087610886108961090610916109261093610946109561096610976109861099611006110161102611036110461105611066110761108611096111061111611126111361114611156111661117611186111961120611216112261123611246112561126611276112861129611306113161132611336113461135611366113761138611396114061141611426114361144611456114661147611486114961150611516115261153611546115561156611576115861159611606116161162611636116461165611666116761168611696117061171611726117361174611756117661177611786117961180611816118261183611846118561186611876118861189611906119161192611936119461195611966119761198611996120061201612026120361204612056120661207612086120961210612116121261213612146121561216612176121861219612206122161222612236122461225612266122761228612296123061231612326123361234612356123661237612386123961240612416124261243612446124561246612476124861249612506125161252612536125461255612566125761258612596126061261612626126361264612656126661267612686126961270612716127261273612746127561276612776127861279612806128161282612836128461285612866128761288612896129061291612926129361294612956129661297612986129961300613016130261303613046130561306613076130861309613106131161312613136131461315613166131761318613196132061321613226132361324613256132661327613286132961330613316133261333613346133561336613376133861339613406134161342613436134461345613466134761348613496135061351613526135361354613556135661357613586135961360613616136261363613646136561366613676136861369613706137161372613736137461375613766137761378613796138061381613826138361384613856138661387613886138961390613916139261393613946139561396613976139861399614006140161402614036140461405614066140761408614096141061411614126141361414614156141661417614186141961420614216142261423614246142561426614276142861429614306143161432614336143461435614366143761438614396144061441614426144361444614456144661447614486144961450614516145261453614546145561456614576145861459614606146161462614636146461465614666146761468614696147061471614726147361474614756147661477614786147961480614816148261483614846148561486614876148861489614906149161492614936149461495614966149761498614996150061501615026150361504615056150661507615086150961510615116151261513615146151561516615176151861519615206152161522615236152461525615266152761528615296153061531615326153361534615356153661537615386153961540615416154261543615446154561546615476154861549615506155161552615536155461555615566155761558615596156061561615626156361564615656156661567615686156961570615716157261573615746157561576615776157861579615806158161582615836158461585615866158761588615896159061591615926159361594615956159661597615986159961600616016160261603616046160561606616076160861609616106161161612616136161461615616166161761618616196162061621616226162361624616256162661627616286162961630616316163261633616346163561636616376163861639616406164161642616436164461645616466164761648616496165061651616526165361654616556165661657616586165961660616616166261663616646166561666616676166861669616706167161672616736167461675616766167761678616796168061681616826168361684616856168661687616886168961690616916169261693616946169561696616976169861699617006170161702617036170461705617066170761708617096171061711617126171361714617156171661717617186171961720617216172261723617246172561726617276172861729617306173161732617336173461735617366173761738617396174061741617426174361744617456174661747617486174961750617516175261753617546175561756617576175861759617606176161762617636176461765617666176761768617696177061771617726177361774617756177661777617786177961780617816178261783617846178561786617876178861789617906179161792617936179461795617966179761798617996180061801618026180361804618056180661807618086180961810618116181261813618146181561816618176181861819618206182161822618236182461825618266182761828618296183061831618326183361834618356183661837618386183961840618416184261843618446184561846618476184861849618506185161852618536185461855618566185761858618596186061861618626186361864618656186661867618686186961870618716187261873618746187561876618776187861879618806188161882618836188461885618866188761888618896189061891618926189361894618956189661897618986189961900619016190261903619046190561906619076190861909619106191161912619136191461915619166191761918619196192061921619226192361924619256192661927619286192961930619316193261933619346193561936619376193861939619406194161942619436194461945619466194761948619496195061951619526195361954619556195661957619586195961960619616196261963619646196561966619676196861969619706197161972619736197461975619766197761978619796198061981619826198361984619856198661987619886198961990619916199261993619946199561996619976199861999620006200162002620036200462005620066200762008620096201062011620126201362014620156201662017620186201962020620216202262023620246202562026620276202862029620306203162032620336203462035620366203762038620396204062041620426204362044620456204662047620486204962050620516205262053620546205562056620576205862059620606206162062620636206462065620666206762068620696207062071620726207362074620756207662077620786207962080620816208262083620846208562086620876208862089620906209162092620936209462095620966209762098620996210062101621026210362104621056210662107621086210962110621116211262113621146211562116621176211862119621206212162122621236212462125621266212762128621296213062131621326213362134621356213662137621386213962140621416214262143621446214562146621476214862149621506215162152621536215462155621566215762158621596216062161621626216362164621656216662167621686216962170621716217262173621746217562176621776217862179621806218162182621836218462185621866218762188621896219062191621926219362194621956219662197621986219962200622016220262203622046220562206622076220862209622106221162212622136221462215622166221762218622196222062221622226222362224622256222662227622286222962230622316223262233622346223562236622376223862239622406224162242622436224462245622466224762248622496225062251622526225362254622556225662257622586225962260622616226262263622646226562266622676226862269622706227162272622736227462275622766227762278622796228062281622826228362284622856228662287622886228962290622916229262293622946229562296622976229862299623006230162302623036230462305623066230762308623096231062311623126231362314623156231662317623186231962320623216232262323623246232562326623276232862329623306233162332623336233462335623366233762338623396234062341623426234362344623456234662347623486234962350623516235262353623546235562356623576235862359623606236162362623636236462365623666236762368623696237062371623726237362374623756237662377623786237962380623816238262383623846238562386623876238862389623906239162392623936239462395623966239762398623996240062401624026240362404624056240662407624086240962410624116241262413624146241562416624176241862419624206242162422624236242462425624266242762428624296243062431624326243362434624356243662437624386243962440624416244262443624446244562446624476244862449624506245162452624536245462455624566245762458624596246062461624626246362464624656246662467624686246962470624716247262473624746247562476624776247862479624806248162482624836248462485624866248762488624896249062491624926249362494624956249662497624986249962500625016250262503625046250562506625076250862509625106251162512625136251462515625166251762518625196252062521625226252362524625256252662527625286252962530625316253262533625346253562536625376253862539625406254162542625436254462545625466254762548625496255062551625526255362554625556255662557625586255962560625616256262563625646256562566625676256862569625706257162572625736257462575625766257762578625796258062581625826258362584625856258662587625886258962590625916259262593625946259562596625976259862599626006260162602626036260462605626066260762608626096261062611626126261362614626156261662617626186261962620626216262262623626246262562626626276262862629626306263162632626336263462635626366263762638626396264062641626426264362644626456264662647626486264962650626516265262653626546265562656626576265862659626606266162662626636266462665626666266762668626696267062671626726267362674626756267662677626786267962680626816268262683626846268562686626876268862689626906269162692626936269462695626966269762698626996270062701627026270362704627056270662707627086270962710627116271262713627146271562716627176271862719627206272162722627236272462725627266272762728627296273062731627326273362734627356273662737627386273962740627416274262743627446274562746627476274862749627506275162752627536275462755627566275762758627596276062761627626276362764627656276662767627686276962770627716277262773627746277562776627776277862779627806278162782627836278462785627866278762788627896279062791627926279362794627956279662797627986279962800628016280262803628046280562806628076280862809628106281162812628136281462815628166281762818628196282062821628226282362824628256282662827628286282962830628316283262833628346283562836628376283862839628406284162842628436284462845628466284762848628496285062851628526285362854628556285662857628586285962860628616286262863628646286562866628676286862869628706287162872628736287462875628766287762878628796288062881628826288362884628856288662887628886288962890628916289262893628946289562896628976289862899629006290162902629036290462905629066290762908629096291062911629126291362914629156291662917629186291962920629216292262923629246292562926629276292862929629306293162932629336293462935629366293762938629396294062941629426294362944629456294662947629486294962950629516295262953629546295562956629576295862959629606296162962629636296462965629666296762968629696297062971629726297362974629756297662977629786297962980629816298262983629846298562986629876298862989629906299162992629936299462995629966299762998629996300063001630026300363004630056300663007630086300963010630116301263013630146301563016630176301863019630206302163022630236302463025630266302763028630296303063031630326303363034630356303663037630386303963040630416304263043630446304563046630476304863049630506305163052630536305463055630566305763058630596306063061630626306363064630656306663067630686306963070630716307263073630746307563076630776307863079630806308163082630836308463085630866308763088630896309063091630926309363094630956309663097630986309963100631016310263103631046310563106631076310863109631106311163112631136311463115631166311763118631196312063121631226312363124631256312663127631286312963130631316313263133631346313563136631376313863139631406314163142631436314463145631466314763148631496315063151631526315363154631556315663157631586315963160631616316263163631646316563166631676316863169631706317163172631736317463175631766317763178631796318063181631826318363184631856318663187631886318963190631916319263193631946319563196631976319863199632006320163202632036320463205632066320763208632096321063211632126321363214632156321663217632186321963220632216322263223632246322563226632276322863229632306323163232632336323463235632366323763238632396324063241632426324363244632456324663247632486324963250632516325263253632546325563256632576325863259632606326163262632636326463265632666326763268632696327063271632726327363274632756327663277632786327963280632816328263283632846328563286632876328863289632906329163292632936329463295632966329763298632996330063301633026330363304633056330663307633086330963310633116331263313633146331563316633176331863319633206332163322633236332463325633266332763328633296333063331633326333363334633356333663337633386333963340633416334263343633446334563346633476334863349633506335163352633536335463355633566335763358633596336063361633626336363364633656336663367633686336963370633716337263373633746337563376633776337863379633806338163382633836338463385633866338763388633896339063391633926339363394633956339663397633986339963400634016340263403634046340563406634076340863409634106341163412634136341463415634166341763418634196342063421634226342363424634256342663427634286342963430634316343263433634346343563436634376343863439634406344163442634436344463445634466344763448634496345063451634526345363454634556345663457634586345963460634616346263463634646346563466634676346863469634706347163472634736347463475634766347763478634796348063481634826348363484634856348663487634886348963490634916349263493634946349563496634976349863499635006350163502635036350463505635066350763508635096351063511635126351363514635156351663517635186351963520635216352263523635246352563526635276352863529635306353163532635336353463535635366353763538635396354063541635426354363544635456354663547635486354963550635516355263553635546355563556635576355863559635606356163562635636356463565635666356763568635696357063571635726357363574635756357663577635786357963580635816358263583635846358563586635876358863589635906359163592635936359463595635966359763598635996360063601636026360363604636056360663607636086360963610636116361263613636146361563616636176361863619636206362163622636236362463625636266362763628636296363063631636326363363634636356363663637636386363963640636416364263643636446364563646636476364863649636506365163652636536365463655636566365763658636596366063661636626366363664636656366663667636686366963670636716367263673636746367563676636776367863679636806368163682636836368463685636866368763688636896369063691636926369363694636956369663697636986369963700637016370263703637046370563706637076370863709637106371163712637136371463715637166371763718637196372063721637226372363724637256372663727637286372963730637316373263733637346373563736637376373863739637406374163742637436374463745637466374763748637496375063751637526375363754637556375663757637586375963760637616376263763637646376563766637676376863769637706377163772637736377463775637766377763778637796378063781637826378363784637856378663787637886378963790637916379263793637946379563796637976379863799638006380163802638036380463805638066380763808638096381063811638126381363814638156381663817638186381963820638216382263823638246382563826638276382863829638306383163832638336383463835638366383763838638396384063841638426384363844638456384663847638486384963850638516385263853638546385563856638576385863859638606386163862638636386463865638666386763868638696387063871638726387363874638756387663877638786387963880638816388263883638846388563886638876388863889638906389163892638936389463895638966389763898638996390063901639026390363904639056390663907639086390963910639116391263913639146391563916639176391863919639206392163922639236392463925639266392763928639296393063931639326393363934639356393663937639386393963940639416394263943639446394563946639476394863949639506395163952639536395463955639566395763958639596396063961639626396363964639656396663967639686396963970639716397263973639746397563976639776397863979639806398163982639836398463985639866398763988639896399063991639926399363994639956399663997639986399964000640016400264003640046400564006640076400864009640106401164012640136401464015640166401764018640196402064021640226402364024640256402664027640286402964030640316403264033640346403564036640376403864039640406404164042640436404464045640466404764048640496405064051640526405364054640556405664057640586405964060640616406264063640646406564066640676406864069640706407164072640736407464075640766407764078640796408064081640826408364084640856408664087640886408964090640916409264093640946409564096640976409864099641006410164102641036410464105641066410764108641096411064111641126411364114641156411664117641186411964120641216412264123641246412564126641276412864129641306413164132641336413464135641366413764138641396414064141641426414364144641456414664147641486414964150641516415264153641546415564156641576415864159641606416164162641636416464165641666416764168641696417064171641726417364174641756417664177641786417964180641816418264183641846418564186641876418864189641906419164192641936419464195641966419764198641996420064201642026420364204642056420664207642086420964210642116421264213642146421564216642176421864219642206422164222642236422464225642266422764228642296423064231642326423364234642356423664237642386423964240642416424264243642446424564246642476424864249642506425164252642536425464255642566425764258642596426064261642626426364264642656426664267642686426964270642716427264273642746427564276642776427864279642806428164282642836428464285642866428764288642896429064291642926429364294642956429664297642986429964300643016430264303643046430564306643076430864309643106431164312643136431464315643166431764318643196432064321643226432364324643256432664327643286432964330643316433264333643346433564336643376433864339643406434164342643436434464345643466434764348643496435064351643526435364354643556435664357643586435964360643616436264363643646436564366643676436864369643706437164372643736437464375643766437764378643796438064381643826438364384643856438664387643886438964390643916439264393643946439564396643976439864399644006440164402644036440464405644066440764408644096441064411644126441364414644156441664417644186441964420644216442264423644246442564426644276442864429644306443164432644336443464435644366443764438644396444064441644426444364444644456444664447644486444964450644516445264453644546445564456644576445864459644606446164462644636446464465644666446764468644696447064471644726447364474644756447664477644786447964480644816448264483644846448564486644876448864489644906449164492644936449464495644966449764498644996450064501645026450364504645056450664507645086450964510645116451264513645146451564516645176451864519645206452164522645236452464525645266452764528645296453064531645326453364534645356453664537645386453964540645416454264543645446454564546645476454864549645506455164552645536455464555645566455764558645596456064561645626456364564645656456664567645686456964570645716457264573645746457564576645776457864579645806458164582645836458464585645866458764588645896459064591645926459364594645956459664597645986459964600646016460264603646046460564606646076460864609646106461164612646136461464615646166461764618646196462064621646226462364624646256462664627646286462964630646316463264633646346463564636646376463864639646406464164642646436464464645646466464764648646496465064651646526465364654646556465664657646586465964660646616466264663646646466564666646676466864669646706467164672646736467464675646766467764678646796468064681646826468364684646856468664687646886468964690646916469264693646946469564696646976469864699647006470164702647036470464705647066470764708647096471064711647126471364714647156471664717647186471964720647216472264723647246472564726647276472864729647306473164732647336473464735647366473764738647396474064741647426474364744647456474664747647486474964750647516475264753647546475564756647576475864759647606476164762647636476464765647666476764768647696477064771647726477364774647756477664777647786477964780647816478264783647846478564786647876478864789647906479164792647936479464795647966479764798647996480064801648026480364804648056480664807648086480964810648116481264813648146481564816648176481864819648206482164822648236482464825648266482764828648296483064831648326483364834648356483664837648386483964840648416484264843648446484564846648476484864849648506485164852648536485464855648566485764858648596486064861648626486364864648656486664867648686486964870648716487264873648746487564876648776487864879648806488164882648836488464885648866488764888648896489064891648926489364894648956489664897648986489964900649016490264903649046490564906649076490864909649106491164912649136491464915649166491764918649196492064921649226492364924649256492664927649286492964930649316493264933649346493564936649376493864939649406494164942649436494464945649466494764948649496495064951649526495364954649556495664957649586495964960649616496264963649646496564966649676496864969649706497164972649736497464975649766497764978649796498064981649826498364984649856498664987649886498964990649916499264993649946499564996649976499864999650006500165002650036500465005650066500765008650096501065011650126501365014650156501665017650186501965020650216502265023650246502565026650276502865029650306503165032650336503465035650366503765038650396504065041650426504365044650456504665047650486504965050650516505265053650546505565056650576505865059650606506165062650636506465065650666506765068650696507065071650726507365074650756507665077650786507965080650816508265083650846508565086650876508865089650906509165092650936509465095650966509765098650996510065101651026510365104651056510665107651086510965110651116511265113651146511565116651176511865119651206512165122651236512465125651266512765128651296513065131651326513365134651356513665137651386513965140651416514265143651446514565146651476514865149651506515165152651536515465155651566515765158651596516065161651626516365164651656516665167651686516965170651716517265173651746517565176651776517865179651806518165182651836518465185651866518765188651896519065191651926519365194651956519665197651986519965200652016520265203652046520565206652076520865209652106521165212652136521465215652166521765218652196522065221652226522365224652256522665227652286522965230652316523265233652346523565236652376523865239652406524165242652436524465245652466524765248652496525065251652526525365254652556525665257652586525965260652616526265263652646526565266652676526865269652706527165272652736527465275652766527765278652796528065281652826528365284652856528665287652886528965290652916529265293652946529565296652976529865299653006530165302653036530465305653066530765308653096531065311653126531365314653156531665317653186531965320653216532265323653246532565326653276532865329653306533165332653336533465335653366533765338653396534065341653426534365344653456534665347653486534965350653516535265353653546535565356653576535865359653606536165362653636536465365653666536765368653696537065371653726537365374653756537665377653786537965380653816538265383653846538565386653876538865389653906539165392653936539465395653966539765398653996540065401654026540365404654056540665407654086540965410654116541265413654146541565416654176541865419654206542165422654236542465425654266542765428654296543065431654326543365434654356543665437654386543965440654416544265443654446544565446654476544865449654506545165452654536545465455654566545765458654596546065461654626546365464654656546665467654686546965470654716547265473654746547565476654776547865479654806548165482654836548465485654866548765488654896549065491654926549365494654956549665497654986549965500655016550265503655046550565506655076550865509655106551165512655136551465515655166551765518655196552065521655226552365524655256552665527655286552965530655316553265533655346553565536655376553865539655406554165542655436554465545655466554765548655496555065551655526555365554655556555665557655586555965560655616556265563655646556565566655676556865569655706557165572655736557465575655766557765578655796558065581655826558365584655856558665587655886558965590655916559265593655946559565596655976559865599656006560165602656036560465605656066560765608656096561065611656126561365614656156561665617656186561965620656216562265623656246562565626656276562865629656306563165632656336563465635656366563765638656396564065641656426564365644656456564665647656486564965650656516565265653656546565565656656576565865659656606566165662656636566465665656666566765668656696567065671656726567365674656756567665677656786567965680656816568265683656846568565686656876568865689656906569165692656936569465695656966569765698656996570065701657026570365704657056570665707657086570965710657116571265713657146571565716657176571865719657206572165722657236572465725657266572765728657296573065731657326573365734657356573665737657386573965740657416574265743657446574565746657476574865749657506575165752657536575465755657566575765758657596576065761657626576365764657656576665767657686576965770657716577265773657746577565776657776577865779657806578165782657836578465785657866578765788657896579065791657926579365794657956579665797657986579965800658016580265803658046580565806658076580865809658106581165812658136581465815658166581765818658196582065821658226582365824658256582665827658286582965830658316583265833658346583565836658376583865839658406584165842658436584465845658466584765848658496585065851658526585365854658556585665857658586585965860658616586265863658646586565866658676586865869658706587165872658736587465875658766587765878658796588065881658826588365884658856588665887658886588965890658916589265893658946589565896658976589865899659006590165902659036590465905659066590765908659096591065911659126591365914659156591665917659186591965920659216592265923659246592565926659276592865929659306593165932659336593465935659366593765938659396594065941659426594365944659456594665947659486594965950659516595265953659546595565956659576595865959659606596165962659636596465965659666596765968659696597065971659726597365974659756597665977659786597965980659816598265983659846598565986659876598865989659906599165992659936599465995659966599765998659996600066001660026600366004660056600666007660086600966010660116601266013660146601566016660176601866019660206602166022660236602466025660266602766028660296603066031660326603366034660356603666037660386603966040660416604266043660446604566046660476604866049660506605166052660536605466055660566605766058660596606066061660626606366064660656606666067660686606966070660716607266073660746607566076660776607866079660806608166082660836608466085660866608766088660896609066091660926609366094660956609666097660986609966100661016610266103661046610566106661076610866109661106611166112661136611466115661166611766118661196612066121661226612366124661256612666127661286612966130661316613266133661346613566136661376613866139661406614166142661436614466145661466614766148661496615066151661526615366154661556615666157661586615966160661616616266163661646616566166661676616866169661706617166172661736617466175661766617766178661796618066181661826618366184661856618666187661886618966190661916619266193661946619566196661976619866199662006620166202662036620466205662066620766208662096621066211662126621366214662156621666217662186621966220662216622266223662246622566226662276622866229662306623166232662336623466235662366623766238662396624066241662426624366244662456624666247662486624966250662516625266253662546625566256662576625866259662606626166262662636626466265662666626766268662696627066271662726627366274662756627666277662786627966280662816628266283662846628566286662876628866289662906629166292662936629466295662966629766298662996630066301663026630366304663056630666307663086630966310663116631266313663146631566316663176631866319663206632166322663236632466325663266632766328663296633066331663326633366334663356633666337663386633966340663416634266343663446634566346663476634866349663506635166352663536635466355663566635766358663596636066361663626636366364663656636666367663686636966370663716637266373663746637566376663776637866379663806638166382663836638466385663866638766388663896639066391663926639366394663956639666397663986639966400664016640266403664046640566406664076640866409664106641166412664136641466415664166641766418664196642066421664226642366424664256642666427664286642966430664316643266433664346643566436664376643866439664406644166442664436644466445664466644766448664496645066451664526645366454664556645666457664586645966460664616646266463664646646566466664676646866469664706647166472664736647466475664766647766478664796648066481664826648366484664856648666487664886648966490664916649266493664946649566496664976649866499665006650166502665036650466505665066650766508665096651066511665126651366514665156651666517665186651966520665216652266523665246652566526665276652866529665306653166532665336653466535665366653766538665396654066541665426654366544665456654666547665486654966550665516655266553665546655566556665576655866559665606656166562665636656466565665666656766568665696657066571665726657366574665756657666577665786657966580665816658266583665846658566586665876658866589665906659166592665936659466595665966659766598665996660066601666026660366604666056660666607666086660966610666116661266613666146661566616666176661866619666206662166622666236662466625666266662766628666296663066631666326663366634666356663666637666386663966640666416664266643666446664566646666476664866649666506665166652666536665466655666566665766658666596666066661666626666366664666656666666667666686666966670666716667266673666746667566676666776667866679666806668166682666836668466685666866668766688666896669066691666926669366694666956669666697666986669966700667016670266703667046670566706667076670866709667106671166712667136671466715667166671766718667196672066721667226672366724667256672666727667286672966730667316673266733667346673566736667376673866739667406674166742667436674466745667466674766748667496675066751667526675366754667556675666757667586675966760667616676266763667646676566766667676676866769667706677166772667736677466775667766677766778667796678066781667826678366784667856678666787667886678966790667916679266793667946679566796667976679866799668006680166802668036680466805668066680766808668096681066811668126681366814668156681666817668186681966820668216682266823668246682566826668276682866829668306683166832668336683466835668366683766838668396684066841668426684366844668456684666847668486684966850668516685266853668546685566856668576685866859668606686166862668636686466865668666686766868668696687066871668726687366874668756687666877668786687966880668816688266883668846688566886668876688866889668906689166892668936689466895668966689766898668996690066901669026690366904669056690666907669086690966910669116691266913669146691566916669176691866919669206692166922669236692466925669266692766928669296693066931669326693366934669356693666937669386693966940669416694266943669446694566946669476694866949669506695166952669536695466955669566695766958669596696066961669626696366964669656696666967669686696966970669716697266973669746697566976669776697866979669806698166982669836698466985669866698766988669896699066991669926699366994669956699666997669986699967000670016700267003670046700567006670076700867009670106701167012670136701467015670166701767018670196702067021670226702367024670256702667027670286702967030670316703267033670346703567036670376703867039670406704167042670436704467045670466704767048670496705067051670526705367054670556705667057670586705967060670616706267063670646706567066670676706867069670706707167072670736707467075670766707767078670796708067081670826708367084670856708667087670886708967090670916709267093670946709567096670976709867099671006710167102671036710467105671066710767108671096711067111671126711367114671156711667117671186711967120671216712267123671246712567126671276712867129671306713167132671336713467135671366713767138671396714067141671426714367144671456714667147671486714967150671516715267153671546715567156671576715867159671606716167162671636716467165671666716767168671696717067171671726717367174671756717667177671786717967180671816718267183671846718567186671876718867189671906719167192671936719467195671966719767198671996720067201672026720367204672056720667207672086720967210672116721267213672146721567216672176721867219672206722167222672236722467225672266722767228672296723067231672326723367234672356723667237672386723967240672416724267243672446724567246672476724867249672506725167252672536725467255672566725767258672596726067261672626726367264672656726667267672686726967270672716727267273672746727567276672776727867279672806728167282672836728467285672866728767288672896729067291672926729367294672956729667297672986729967300673016730267303673046730567306673076730867309673106731167312673136731467315673166731767318673196732067321673226732367324673256732667327673286732967330673316733267333673346733567336673376733867339673406734167342673436734467345673466734767348673496735067351673526735367354673556735667357673586735967360673616736267363673646736567366673676736867369673706737167372673736737467375673766737767378673796738067381673826738367384673856738667387673886738967390673916739267393673946739567396673976739867399674006740167402674036740467405674066740767408674096741067411674126741367414674156741667417674186741967420674216742267423674246742567426674276742867429674306743167432674336743467435674366743767438674396744067441674426744367444674456744667447674486744967450674516745267453674546745567456674576745867459674606746167462674636746467465674666746767468674696747067471674726747367474674756747667477674786747967480674816748267483674846748567486674876748867489674906749167492674936749467495674966749767498674996750067501675026750367504675056750667507675086750967510675116751267513675146751567516675176751867519675206752167522675236752467525675266752767528675296753067531675326753367534675356753667537675386753967540675416754267543675446754567546675476754867549675506755167552675536755467555675566755767558675596756067561675626756367564675656756667567675686756967570675716757267573675746757567576675776757867579675806758167582675836758467585675866758767588675896759067591675926759367594675956759667597675986759967600676016760267603676046760567606676076760867609676106761167612676136761467615676166761767618676196762067621676226762367624676256762667627676286762967630676316763267633676346763567636676376763867639676406764167642676436764467645676466764767648676496765067651676526765367654676556765667657676586765967660676616766267663676646766567666676676766867669676706767167672676736767467675676766767767678676796768067681676826768367684676856768667687676886768967690676916769267693676946769567696676976769867699677006770167702677036770467705677066770767708677096771067711677126771367714677156771667717677186771967720677216772267723677246772567726677276772867729677306773167732677336773467735677366773767738677396774067741677426774367744677456774667747677486774967750677516775267753677546775567756677576775867759677606776167762677636776467765677666776767768677696777067771677726777367774677756777667777677786777967780677816778267783677846778567786677876778867789677906779167792677936779467795677966779767798677996780067801678026780367804678056780667807678086780967810678116781267813678146781567816678176781867819678206782167822678236782467825678266782767828678296783067831678326783367834678356783667837678386783967840678416784267843678446784567846678476784867849678506785167852678536785467855678566785767858678596786067861678626786367864678656786667867678686786967870678716787267873678746787567876678776787867879678806788167882678836788467885678866788767888678896789067891678926789367894678956789667897678986789967900679016790267903679046790567906679076790867909679106791167912679136791467915679166791767918679196792067921679226792367924679256792667927679286792967930679316793267933679346793567936679376793867939679406794167942679436794467945679466794767948679496795067951679526795367954679556795667957679586795967960679616796267963679646796567966679676796867969679706797167972679736797467975679766797767978679796798067981679826798367984679856798667987679886798967990679916799267993679946799567996679976799867999680006800168002680036800468005680066800768008680096801068011680126801368014680156801668017680186801968020680216802268023680246802568026680276802868029680306803168032680336803468035680366803768038680396804068041680426804368044680456804668047680486804968050680516805268053680546805568056680576805868059680606806168062680636806468065680666806768068680696807068071680726807368074680756807668077680786807968080680816808268083680846808568086680876808868089680906809168092680936809468095680966809768098680996810068101681026810368104681056810668107681086810968110681116811268113681146811568116681176811868119681206812168122681236812468125681266812768128681296813068131681326813368134681356813668137681386813968140681416814268143681446814568146681476814868149681506815168152681536815468155681566815768158681596816068161681626816368164681656816668167681686816968170681716817268173681746817568176681776817868179681806818168182681836818468185681866818768188681896819068191681926819368194681956819668197681986819968200682016820268203682046820568206682076820868209682106821168212682136821468215682166821768218682196822068221682226822368224682256822668227682286822968230682316823268233682346823568236682376823868239682406824168242682436824468245682466824768248682496825068251682526825368254682556825668257682586825968260682616826268263682646826568266682676826868269682706827168272682736827468275682766827768278682796828068281682826828368284682856828668287682886828968290682916829268293682946829568296682976829868299683006830168302683036830468305683066830768308683096831068311683126831368314683156831668317683186831968320683216832268323683246832568326683276832868329683306833168332683336833468335683366833768338683396834068341683426834368344683456834668347683486834968350683516835268353683546835568356683576835868359683606836168362683636836468365683666836768368683696837068371683726837368374683756837668377683786837968380683816838268383683846838568386683876838868389683906839168392683936839468395683966839768398683996840068401684026840368404684056840668407684086840968410684116841268413684146841568416684176841868419684206842168422684236842468425684266842768428684296843068431684326843368434684356843668437684386843968440684416844268443684446844568446684476844868449684506845168452684536845468455684566845768458684596846068461684626846368464684656846668467684686846968470684716847268473684746847568476684776847868479684806848168482684836848468485684866848768488684896849068491684926849368494684956849668497684986849968500685016850268503685046850568506685076850868509685106851168512685136851468515685166851768518685196852068521685226852368524685256852668527685286852968530685316853268533685346853568536685376853868539685406854168542685436854468545685466854768548685496855068551685526855368554685556855668557685586855968560685616856268563685646856568566685676856868569685706857168572685736857468575685766857768578685796858068581685826858368584685856858668587685886858968590685916859268593685946859568596685976859868599686006860168602686036860468605686066860768608686096861068611686126861368614686156861668617686186861968620686216862268623686246862568626686276862868629686306863168632686336863468635686366863768638686396864068641686426864368644686456864668647686486864968650686516865268653686546865568656686576865868659686606866168662686636866468665686666866768668686696867068671686726867368674686756867668677686786867968680686816868268683686846868568686686876868868689686906869168692686936869468695686966869768698686996870068701687026870368704687056870668707687086870968710687116871268713687146871568716687176871868719687206872168722687236872468725687266872768728687296873068731687326873368734687356873668737687386873968740687416874268743687446874568746687476874868749687506875168752687536875468755687566875768758687596876068761687626876368764687656876668767687686876968770687716877268773687746877568776687776877868779687806878168782687836878468785687866878768788687896879068791687926879368794687956879668797687986879968800688016880268803688046880568806688076880868809688106881168812688136881468815688166881768818688196882068821688226882368824688256882668827688286882968830688316883268833688346883568836688376883868839688406884168842688436884468845688466884768848688496885068851688526885368854688556885668857688586885968860688616886268863688646886568866688676886868869688706887168872688736887468875688766887768878688796888068881688826888368884688856888668887688886888968890688916889268893688946889568896688976889868899689006890168902689036890468905689066890768908689096891068911689126891368914689156891668917689186891968920689216892268923689246892568926689276892868929689306893168932689336893468935689366893768938689396894068941689426894368944689456894668947689486894968950689516895268953689546895568956689576895868959689606896168962689636896468965689666896768968689696897068971689726897368974689756897668977689786897968980689816898268983689846898568986689876898868989689906899168992689936899468995689966899768998689996900069001690026900369004690056900669007690086900969010690116901269013690146901569016690176901869019690206902169022690236902469025690266902769028690296903069031690326903369034690356903669037690386903969040690416904269043690446904569046690476904869049690506905169052690536905469055690566905769058690596906069061690626906369064690656906669067690686906969070690716907269073690746907569076690776907869079690806908169082690836908469085690866908769088690896909069091690926909369094690956909669097690986909969100691016910269103691046910569106691076910869109691106911169112691136911469115691166911769118691196912069121691226912369124691256912669127691286912969130691316913269133691346913569136691376913869139691406914169142691436914469145691466914769148691496915069151691526915369154691556915669157691586915969160691616916269163691646916569166691676916869169691706917169172691736917469175691766917769178691796918069181691826918369184691856918669187691886918969190691916919269193691946919569196691976919869199692006920169202692036920469205692066920769208692096921069211692126921369214692156921669217692186921969220692216922269223692246922569226692276922869229692306923169232692336923469235692366923769238692396924069241692426924369244692456924669247692486924969250692516925269253692546925569256692576925869259692606926169262692636926469265692666926769268692696927069271692726927369274692756927669277692786927969280692816928269283692846928569286692876928869289692906929169292692936929469295692966929769298692996930069301693026930369304693056930669307693086930969310693116931269313693146931569316693176931869319693206932169322693236932469325693266932769328693296933069331693326933369334693356933669337693386933969340693416934269343693446934569346693476934869349693506935169352693536935469355693566935769358693596936069361693626936369364693656936669367693686936969370693716937269373693746937569376693776937869379693806938169382693836938469385693866938769388693896939069391693926939369394693956939669397693986939969400694016940269403694046940569406694076940869409694106941169412694136941469415694166941769418694196942069421694226942369424694256942669427694286942969430694316943269433694346943569436694376943869439694406944169442694436944469445694466944769448694496945069451694526945369454694556945669457694586945969460694616946269463694646946569466694676946869469694706947169472694736947469475694766947769478694796948069481694826948369484694856948669487694886948969490694916949269493694946949569496694976949869499695006950169502695036950469505695066950769508695096951069511695126951369514695156951669517695186951969520695216952269523695246952569526695276952869529695306953169532695336953469535695366953769538695396954069541695426954369544695456954669547695486954969550695516955269553695546955569556695576955869559695606956169562695636956469565695666956769568695696957069571695726957369574695756957669577695786957969580695816958269583695846958569586695876958869589695906959169592695936959469595695966959769598695996960069601696026960369604696056960669607696086960969610696116961269613696146961569616696176961869619696206962169622696236962469625696266962769628696296963069631696326963369634696356963669637696386963969640696416964269643696446964569646696476964869649696506965169652696536965469655696566965769658696596966069661696626966369664696656966669667696686966969670696716967269673696746967569676696776967869679696806968169682696836968469685696866968769688696896969069691696926969369694696956969669697696986969969700697016970269703697046970569706697076970869709697106971169712697136971469715697166971769718697196972069721697226972369724697256972669727697286972969730697316973269733697346973569736697376973869739697406974169742697436974469745697466974769748697496975069751697526975369754697556975669757697586975969760697616976269763697646976569766697676976869769697706977169772697736977469775697766977769778697796978069781697826978369784697856978669787697886978969790697916979269793697946979569796697976979869799698006980169802698036980469805698066980769808698096981069811698126981369814698156981669817698186981969820698216982269823698246982569826698276982869829698306983169832698336983469835698366983769838698396984069841698426984369844698456984669847698486984969850698516985269853698546985569856698576985869859698606986169862698636986469865698666986769868698696987069871698726987369874698756987669877698786987969880698816988269883698846988569886698876988869889698906989169892698936989469895698966989769898698996990069901699026990369904699056990669907699086990969910699116991269913699146991569916699176991869919699206992169922699236992469925699266992769928699296993069931699326993369934699356993669937699386993969940699416994269943699446994569946699476994869949699506995169952699536995469955699566995769958699596996069961699626996369964699656996669967699686996969970699716997269973699746997569976699776997869979699806998169982699836998469985699866998769988699896999069991699926999369994699956999669997699986999970000700017000270003700047000570006700077000870009700107001170012700137001470015700167001770018700197002070021700227002370024700257002670027700287002970030700317003270033700347003570036700377003870039700407004170042700437004470045700467004770048700497005070051700527005370054700557005670057700587005970060700617006270063700647006570066700677006870069700707007170072700737007470075700767007770078700797008070081700827008370084700857008670087700887008970090700917009270093700947009570096700977009870099701007010170102701037010470105701067010770108701097011070111701127011370114701157011670117701187011970120701217012270123701247012570126701277012870129701307013170132701337013470135701367013770138701397014070141701427014370144701457014670147701487014970150701517015270153701547015570156701577015870159701607016170162701637016470165701667016770168701697017070171701727017370174701757017670177701787017970180701817018270183701847018570186701877018870189701907019170192701937019470195701967019770198701997020070201702027020370204702057020670207702087020970210702117021270213702147021570216702177021870219702207022170222702237022470225702267022770228702297023070231702327023370234702357023670237702387023970240702417024270243702447024570246702477024870249702507025170252702537025470255702567025770258702597026070261702627026370264702657026670267702687026970270702717027270273702747027570276702777027870279702807028170282702837028470285702867028770288702897029070291702927029370294702957029670297702987029970300703017030270303703047030570306703077030870309703107031170312703137031470315703167031770318703197032070321703227032370324703257032670327703287032970330703317033270333703347033570336703377033870339703407034170342703437034470345703467034770348703497035070351703527035370354703557035670357703587035970360703617036270363703647036570366703677036870369703707037170372703737037470375703767037770378703797038070381703827038370384703857038670387703887038970390703917039270393703947039570396703977039870399704007040170402704037040470405704067040770408704097041070411704127041370414704157041670417704187041970420704217042270423704247042570426704277042870429704307043170432704337043470435704367043770438704397044070441704427044370444704457044670447704487044970450704517045270453704547045570456704577045870459704607046170462704637046470465704667046770468704697047070471704727047370474704757047670477704787047970480704817048270483704847048570486704877048870489704907049170492704937049470495704967049770498704997050070501705027050370504705057050670507705087050970510705117051270513705147051570516705177051870519705207052170522705237052470525705267052770528705297053070531705327053370534705357053670537705387053970540705417054270543705447054570546705477054870549705507055170552705537055470555705567055770558705597056070561705627056370564705657056670567705687056970570705717057270573705747057570576705777057870579705807058170582705837058470585705867058770588705897059070591705927059370594705957059670597705987059970600706017060270603706047060570606706077060870609706107061170612706137061470615706167061770618706197062070621706227062370624706257062670627706287062970630706317063270633706347063570636706377063870639706407064170642706437064470645706467064770648706497065070651706527065370654706557065670657706587065970660706617066270663706647066570666706677066870669706707067170672706737067470675706767067770678706797068070681706827068370684706857068670687706887068970690706917069270693706947069570696706977069870699707007070170702707037070470705707067070770708707097071070711707127071370714707157071670717707187071970720707217072270723707247072570726707277072870729707307073170732707337073470735707367073770738707397074070741707427074370744707457074670747707487074970750707517075270753707547075570756707577075870759707607076170762707637076470765707667076770768707697077070771707727077370774707757077670777707787077970780707817078270783707847078570786707877078870789707907079170792707937079470795707967079770798707997080070801708027080370804708057080670807708087080970810708117081270813708147081570816708177081870819708207082170822708237082470825708267082770828708297083070831708327083370834708357083670837708387083970840708417084270843708447084570846708477084870849708507085170852708537085470855708567085770858708597086070861708627086370864708657086670867708687086970870708717087270873708747087570876708777087870879708807088170882708837088470885708867088770888708897089070891708927089370894708957089670897708987089970900709017090270903709047090570906709077090870909709107091170912709137091470915709167091770918709197092070921709227092370924709257092670927709287092970930709317093270933709347093570936709377093870939709407094170942709437094470945709467094770948709497095070951709527095370954709557095670957709587095970960709617096270963709647096570966709677096870969709707097170972709737097470975709767097770978709797098070981709827098370984709857098670987709887098970990709917099270993709947099570996709977099870999710007100171002710037100471005710067100771008710097101071011710127101371014710157101671017710187101971020710217102271023710247102571026710277102871029710307103171032710337103471035710367103771038710397104071041710427104371044710457104671047710487104971050710517105271053710547105571056710577105871059710607106171062710637106471065710667106771068710697107071071710727107371074710757107671077710787107971080710817108271083710847108571086710877108871089710907109171092710937109471095710967109771098710997110071101711027110371104711057110671107711087110971110711117111271113711147111571116711177111871119711207112171122711237112471125711267112771128711297113071131711327113371134711357113671137711387113971140711417114271143711447114571146711477114871149711507115171152711537115471155711567115771158711597116071161711627116371164711657116671167711687116971170711717117271173711747117571176711777117871179711807118171182711837118471185711867118771188711897119071191711927119371194711957119671197711987119971200712017120271203712047120571206712077120871209712107121171212712137121471215712167121771218712197122071221712227122371224712257122671227712287122971230712317123271233712347123571236712377123871239712407124171242712437124471245712467124771248712497125071251712527125371254712557125671257712587125971260712617126271263712647126571266712677126871269712707127171272712737127471275712767127771278712797128071281712827128371284712857128671287712887128971290712917129271293712947129571296712977129871299713007130171302713037130471305713067130771308713097131071311713127131371314713157131671317713187131971320713217132271323713247132571326713277132871329713307133171332713337133471335713367133771338713397134071341713427134371344713457134671347713487134971350713517135271353713547135571356713577135871359713607136171362713637136471365713667136771368713697137071371713727137371374713757137671377713787137971380713817138271383713847138571386713877138871389713907139171392713937139471395713967139771398713997140071401714027140371404714057140671407714087140971410714117141271413714147141571416714177141871419714207142171422714237142471425714267142771428714297143071431714327143371434714357143671437714387143971440714417144271443714447144571446714477144871449714507145171452714537145471455714567145771458714597146071461714627146371464714657146671467714687146971470714717147271473714747147571476714777147871479714807148171482714837148471485714867148771488714897149071491714927149371494714957149671497714987149971500715017150271503715047150571506715077150871509715107151171512715137151471515715167151771518715197152071521715227152371524715257152671527715287152971530715317153271533715347153571536715377153871539715407154171542715437154471545715467154771548715497155071551715527155371554715557155671557715587155971560715617156271563715647156571566715677156871569715707157171572715737157471575715767157771578715797158071581715827158371584715857158671587715887158971590715917159271593715947159571596715977159871599716007160171602716037160471605716067160771608716097161071611716127161371614716157161671617716187161971620716217162271623716247162571626716277162871629716307163171632716337163471635716367163771638716397164071641716427164371644716457164671647716487164971650716517165271653716547165571656716577165871659716607166171662716637166471665716667166771668716697167071671716727167371674716757167671677716787167971680716817168271683716847168571686716877168871689716907169171692716937169471695716967169771698716997170071701717027170371704717057170671707717087170971710717117171271713717147171571716717177171871719717207172171722717237172471725717267172771728717297173071731717327173371734717357173671737717387173971740717417174271743717447174571746717477174871749717507175171752717537175471755717567175771758717597176071761717627176371764717657176671767717687176971770717717177271773717747177571776717777177871779717807178171782717837178471785717867178771788717897179071791717927179371794717957179671797717987179971800718017180271803718047180571806718077180871809718107181171812718137181471815718167181771818718197182071821718227182371824718257182671827718287182971830718317183271833718347183571836718377183871839718407184171842718437184471845718467184771848718497185071851718527185371854718557185671857718587185971860718617186271863718647186571866718677186871869718707187171872718737187471875718767187771878718797188071881718827188371884718857188671887718887188971890718917189271893718947189571896718977189871899719007190171902719037190471905719067190771908719097191071911719127191371914719157191671917719187191971920719217192271923719247192571926719277192871929719307193171932719337193471935719367193771938719397194071941719427194371944719457194671947719487194971950719517195271953719547195571956719577195871959719607196171962719637196471965719667196771968719697197071971719727197371974719757197671977719787197971980719817198271983719847198571986719877198871989719907199171992719937199471995719967199771998719997200072001720027200372004720057200672007720087200972010720117201272013720147201572016720177201872019720207202172022720237202472025720267202772028720297203072031720327203372034720357203672037720387203972040720417204272043720447204572046720477204872049720507205172052720537205472055720567205772058720597206072061720627206372064720657206672067720687206972070720717207272073720747207572076720777207872079720807208172082720837208472085720867208772088720897209072091720927209372094720957209672097720987209972100721017210272103721047210572106721077210872109721107211172112721137211472115721167211772118721197212072121721227212372124721257212672127721287212972130721317213272133721347213572136721377213872139721407214172142721437214472145721467214772148721497215072151721527215372154721557215672157721587215972160721617216272163721647216572166721677216872169721707217172172721737217472175721767217772178721797218072181721827218372184721857218672187721887218972190721917219272193721947219572196721977219872199722007220172202722037220472205722067220772208722097221072211722127221372214722157221672217722187221972220722217222272223722247222572226722277222872229722307223172232722337223472235722367223772238722397224072241722427224372244722457224672247722487224972250722517225272253722547225572256722577225872259722607226172262722637226472265722667226772268722697227072271722727227372274722757227672277722787227972280722817228272283722847228572286722877228872289722907229172292722937229472295722967229772298722997230072301723027230372304723057230672307723087230972310723117231272313723147231572316723177231872319723207232172322723237232472325723267232772328723297233072331723327233372334723357233672337723387233972340723417234272343723447234572346723477234872349723507235172352723537235472355723567235772358723597236072361723627236372364723657236672367723687236972370723717237272373723747237572376723777237872379723807238172382723837238472385723867238772388723897239072391723927239372394723957239672397723987239972400724017240272403724047240572406724077240872409724107241172412724137241472415724167241772418724197242072421724227242372424724257242672427724287242972430724317243272433724347243572436724377243872439724407244172442724437244472445724467244772448724497245072451724527245372454724557245672457724587245972460724617246272463724647246572466724677246872469724707247172472724737247472475724767247772478724797248072481724827248372484724857248672487724887248972490724917249272493724947249572496724977249872499725007250172502725037250472505725067250772508725097251072511725127251372514725157251672517725187251972520725217252272523725247252572526725277252872529725307253172532725337253472535725367253772538725397254072541725427254372544725457254672547725487254972550725517255272553725547255572556725577255872559725607256172562725637256472565725667256772568725697257072571725727257372574725757257672577725787257972580725817258272583725847258572586725877258872589725907259172592725937259472595725967259772598725997260072601726027260372604726057260672607726087260972610726117261272613726147261572616726177261872619726207262172622726237262472625726267262772628726297263072631726327263372634726357263672637726387263972640726417264272643726447264572646726477264872649726507265172652726537265472655726567265772658726597266072661726627266372664726657266672667726687266972670726717267272673726747267572676726777267872679726807268172682726837268472685726867268772688726897269072691726927269372694726957269672697726987269972700727017270272703727047270572706727077270872709727107271172712727137271472715727167271772718727197272072721727227272372724727257272672727727287272972730727317273272733727347273572736727377273872739727407274172742727437274472745727467274772748727497275072751727527275372754727557275672757727587275972760727617276272763727647276572766727677276872769727707277172772727737277472775727767277772778727797278072781727827278372784727857278672787727887278972790727917279272793727947279572796727977279872799728007280172802728037280472805728067280772808728097281072811728127281372814728157281672817728187281972820728217282272823728247282572826728277282872829728307283172832728337283472835728367283772838728397284072841728427284372844728457284672847728487284972850728517285272853728547285572856728577285872859728607286172862728637286472865728667286772868728697287072871728727287372874728757287672877728787287972880728817288272883728847288572886728877288872889728907289172892728937289472895728967289772898728997290072901729027290372904729057290672907729087290972910729117291272913729147291572916729177291872919729207292172922729237292472925729267292772928729297293072931729327293372934729357293672937729387293972940729417294272943729447294572946729477294872949729507295172952729537295472955729567295772958729597296072961729627296372964729657296672967729687296972970729717297272973729747297572976729777297872979729807298172982729837298472985729867298772988729897299072991729927299372994729957299672997729987299973000730017300273003730047300573006730077300873009730107301173012730137301473015730167301773018730197302073021730227302373024730257302673027730287302973030730317303273033730347303573036730377303873039730407304173042730437304473045730467304773048730497305073051730527305373054730557305673057730587305973060730617306273063730647306573066730677306873069730707307173072730737307473075730767307773078730797308073081730827308373084730857308673087730887308973090730917309273093730947309573096730977309873099731007310173102731037310473105731067310773108731097311073111731127311373114731157311673117731187311973120731217312273123731247312573126731277312873129731307313173132731337313473135731367313773138731397314073141731427314373144731457314673147731487314973150731517315273153731547315573156731577315873159731607316173162731637316473165731667316773168731697317073171731727317373174731757317673177731787317973180731817318273183731847318573186731877318873189731907319173192731937319473195731967319773198731997320073201732027320373204732057320673207732087320973210732117321273213732147321573216732177321873219732207322173222732237322473225732267322773228732297323073231732327323373234732357323673237732387323973240732417324273243732447324573246732477324873249732507325173252732537325473255732567325773258732597326073261732627326373264732657326673267732687326973270732717327273273732747327573276732777327873279732807328173282732837328473285732867328773288732897329073291732927329373294732957329673297732987329973300733017330273303733047330573306733077330873309733107331173312733137331473315733167331773318733197332073321733227332373324733257332673327733287332973330733317333273333733347333573336733377333873339733407334173342733437334473345733467334773348733497335073351733527335373354733557335673357733587335973360733617336273363733647336573366733677336873369733707337173372733737337473375733767337773378733797338073381733827338373384733857338673387733887338973390733917339273393733947339573396733977339873399734007340173402734037340473405734067340773408734097341073411734127341373414734157341673417734187341973420734217342273423734247342573426734277342873429734307343173432734337343473435734367343773438734397344073441734427344373444734457344673447734487344973450734517345273453734547345573456734577345873459734607346173462734637346473465734667346773468734697347073471734727347373474734757347673477734787347973480734817348273483734847348573486734877348873489734907349173492734937349473495734967349773498734997350073501735027350373504735057350673507735087350973510735117351273513735147351573516735177351873519735207352173522735237352473525735267352773528735297353073531735327353373534735357353673537735387353973540735417354273543735447354573546735477354873549735507355173552735537355473555735567355773558735597356073561735627356373564735657356673567735687356973570735717357273573735747357573576735777357873579735807358173582735837358473585735867358773588735897359073591735927359373594735957359673597735987359973600736017360273603736047360573606736077360873609736107361173612736137361473615736167361773618736197362073621736227362373624736257362673627736287362973630736317363273633736347363573636736377363873639736407364173642736437364473645736467364773648736497365073651736527365373654736557365673657736587365973660736617366273663736647366573666736677366873669736707367173672736737367473675736767367773678736797368073681736827368373684736857368673687736887368973690736917369273693736947369573696736977369873699737007370173702737037370473705737067370773708737097371073711737127371373714737157371673717737187371973720737217372273723737247372573726737277372873729737307373173732737337373473735737367373773738737397374073741737427374373744737457374673747737487374973750737517375273753737547375573756737577375873759737607376173762737637376473765737667376773768737697377073771737727377373774737757377673777737787377973780737817378273783737847378573786737877378873789737907379173792737937379473795737967379773798737997380073801738027380373804738057380673807738087380973810738117381273813738147381573816738177381873819738207382173822738237382473825738267382773828738297383073831738327383373834738357383673837738387383973840738417384273843738447384573846738477384873849738507385173852738537385473855738567385773858738597386073861738627386373864738657386673867738687386973870738717387273873738747387573876738777387873879738807388173882738837388473885738867388773888738897389073891738927389373894738957389673897738987389973900739017390273903739047390573906739077390873909739107391173912739137391473915739167391773918739197392073921739227392373924739257392673927739287392973930739317393273933739347393573936739377393873939739407394173942739437394473945739467394773948739497395073951739527395373954739557395673957739587395973960739617396273963739647396573966739677396873969739707397173972739737397473975739767397773978739797398073981739827398373984739857398673987739887398973990739917399273993739947399573996739977399873999740007400174002740037400474005740067400774008740097401074011740127401374014740157401674017740187401974020740217402274023740247402574026740277402874029740307403174032740337403474035740367403774038740397404074041740427404374044740457404674047740487404974050740517405274053740547405574056740577405874059740607406174062740637406474065740667406774068740697407074071740727407374074740757407674077740787407974080740817408274083740847408574086740877408874089740907409174092740937409474095740967409774098740997410074101741027410374104741057410674107741087410974110741117411274113741147411574116741177411874119741207412174122741237412474125741267412774128741297413074131741327413374134741357413674137741387413974140741417414274143741447414574146741477414874149741507415174152741537415474155741567415774158741597416074161741627416374164741657416674167741687416974170741717417274173741747417574176741777417874179741807418174182741837418474185741867418774188741897419074191741927419374194741957419674197741987419974200742017420274203742047420574206742077420874209742107421174212742137421474215742167421774218742197422074221742227422374224742257422674227742287422974230742317423274233742347423574236742377423874239742407424174242742437424474245742467424774248742497425074251742527425374254742557425674257742587425974260742617426274263742647426574266742677426874269742707427174272742737427474275742767427774278742797428074281742827428374284742857428674287742887428974290742917429274293742947429574296742977429874299743007430174302743037430474305743067430774308743097431074311743127431374314743157431674317743187431974320743217432274323743247432574326743277432874329743307433174332743337433474335743367433774338743397434074341743427434374344743457434674347743487434974350743517435274353743547435574356743577435874359743607436174362743637436474365743667436774368743697437074371743727437374374743757437674377743787437974380743817438274383743847438574386743877438874389743907439174392743937439474395743967439774398743997440074401744027440374404744057440674407744087440974410744117441274413744147441574416744177441874419744207442174422744237442474425744267442774428744297443074431744327443374434744357443674437744387443974440744417444274443744447444574446744477444874449744507445174452744537445474455744567445774458744597446074461744627446374464744657446674467744687446974470744717447274473744747447574476744777447874479744807448174482744837448474485744867448774488744897449074491744927449374494744957449674497744987449974500745017450274503745047450574506745077450874509745107451174512745137451474515745167451774518745197452074521745227452374524745257452674527745287452974530745317453274533745347453574536745377453874539745407454174542745437454474545745467454774548745497455074551745527455374554745557455674557745587455974560745617456274563745647456574566745677456874569745707457174572745737457474575745767457774578745797458074581745827458374584745857458674587745887458974590745917459274593745947459574596745977459874599746007460174602746037460474605746067460774608746097461074611746127461374614746157461674617746187461974620746217462274623746247462574626746277462874629746307463174632746337463474635746367463774638746397464074641746427464374644746457464674647746487464974650746517465274653746547465574656746577465874659746607466174662746637466474665746667466774668746697467074671746727467374674746757467674677746787467974680746817468274683746847468574686746877468874689746907469174692746937469474695746967469774698746997470074701747027470374704747057470674707747087470974710747117471274713747147471574716747177471874719747207472174722747237472474725747267472774728747297473074731747327473374734747357473674737747387473974740747417474274743747447474574746747477474874749747507475174752747537475474755747567475774758747597476074761747627476374764747657476674767747687476974770747717477274773747747477574776747777477874779747807478174782747837478474785747867478774788747897479074791747927479374794747957479674797747987479974800748017480274803748047480574806748077480874809748107481174812748137481474815748167481774818748197482074821748227482374824748257482674827748287482974830748317483274833748347483574836748377483874839748407484174842748437484474845748467484774848748497485074851748527485374854748557485674857748587485974860748617486274863748647486574866748677486874869748707487174872748737487474875748767487774878748797488074881748827488374884748857488674887748887488974890748917489274893748947489574896748977489874899749007490174902749037490474905749067490774908749097491074911749127491374914749157491674917749187491974920749217492274923749247492574926749277492874929749307493174932749337493474935749367493774938749397494074941749427494374944749457494674947749487494974950749517495274953749547495574956749577495874959749607496174962749637496474965749667496774968749697497074971749727497374974749757497674977749787497974980749817498274983749847498574986749877498874989749907499174992749937499474995749967499774998749997500075001750027500375004750057500675007750087500975010750117501275013750147501575016750177501875019750207502175022750237502475025750267502775028750297503075031750327503375034750357503675037750387503975040750417504275043750447504575046750477504875049750507505175052750537505475055750567505775058750597506075061750627506375064750657506675067750687506975070750717507275073750747507575076750777507875079750807508175082750837508475085750867508775088750897509075091750927509375094750957509675097750987509975100751017510275103751047510575106751077510875109751107511175112751137511475115751167511775118751197512075121751227512375124751257512675127751287512975130751317513275133751347513575136751377513875139751407514175142751437514475145751467514775148751497515075151751527515375154751557515675157751587515975160751617516275163751647516575166751677516875169751707517175172751737517475175751767517775178751797518075181751827518375184751857518675187751887518975190751917519275193751947519575196751977519875199752007520175202752037520475205752067520775208752097521075211752127521375214752157521675217752187521975220752217522275223752247522575226752277522875229752307523175232752337523475235752367523775238752397524075241752427524375244752457524675247752487524975250752517525275253752547525575256752577525875259752607526175262752637526475265752667526775268752697527075271752727527375274752757527675277752787527975280752817528275283752847528575286752877528875289752907529175292752937529475295752967529775298752997530075301753027530375304753057530675307753087530975310753117531275313753147531575316753177531875319753207532175322753237532475325753267532775328753297533075331753327533375334753357533675337753387533975340753417534275343753447534575346753477534875349753507535175352753537535475355753567535775358753597536075361753627536375364753657536675367753687536975370753717537275373753747537575376753777537875379753807538175382753837538475385753867538775388753897539075391753927539375394753957539675397753987539975400754017540275403754047540575406754077540875409754107541175412754137541475415754167541775418754197542075421754227542375424754257542675427754287542975430754317543275433754347543575436754377543875439754407544175442754437544475445754467544775448754497545075451754527545375454754557545675457754587545975460754617546275463754647546575466754677546875469754707547175472754737547475475754767547775478754797548075481754827548375484754857548675487754887548975490754917549275493754947549575496754977549875499755007550175502755037550475505755067550775508755097551075511755127551375514755157551675517755187551975520755217552275523755247552575526755277552875529755307553175532755337553475535755367553775538755397554075541755427554375544755457554675547755487554975550755517555275553755547555575556755577555875559755607556175562755637556475565755667556775568755697557075571755727557375574755757557675577755787557975580755817558275583755847558575586755877558875589755907559175592755937559475595755967559775598755997560075601756027560375604756057560675607756087560975610756117561275613756147561575616756177561875619756207562175622756237562475625756267562775628756297563075631756327563375634756357563675637756387563975640756417564275643756447564575646756477564875649756507565175652756537565475655756567565775658756597566075661756627566375664756657566675667756687566975670756717567275673756747567575676756777567875679756807568175682756837568475685756867568775688756897569075691756927569375694756957569675697756987569975700757017570275703757047570575706757077570875709757107571175712757137571475715757167571775718757197572075721757227572375724757257572675727757287572975730757317573275733757347573575736757377573875739757407574175742757437574475745757467574775748757497575075751757527575375754757557575675757757587575975760757617576275763757647576575766757677576875769757707577175772757737577475775757767577775778757797578075781757827578375784757857578675787757887578975790757917579275793757947579575796757977579875799758007580175802758037580475805758067580775808758097581075811758127581375814758157581675817758187581975820758217582275823758247582575826758277582875829758307583175832758337583475835758367583775838758397584075841758427584375844758457584675847758487584975850758517585275853758547585575856758577585875859758607586175862758637586475865758667586775868758697587075871758727587375874758757587675877758787587975880758817588275883758847588575886758877588875889758907589175892758937589475895758967589775898758997590075901759027590375904759057590675907759087590975910759117591275913759147591575916759177591875919759207592175922759237592475925759267592775928759297593075931759327593375934759357593675937759387593975940759417594275943759447594575946759477594875949759507595175952759537595475955759567595775958759597596075961759627596375964759657596675967759687596975970759717597275973759747597575976759777597875979759807598175982759837598475985759867598775988759897599075991759927599375994759957599675997759987599976000760017600276003760047600576006760077600876009760107601176012760137601476015760167601776018760197602076021760227602376024760257602676027760287602976030760317603276033760347603576036760377603876039760407604176042760437604476045760467604776048760497605076051760527605376054760557605676057760587605976060760617606276063760647606576066760677606876069760707607176072760737607476075760767607776078760797608076081760827608376084760857608676087760887608976090760917609276093760947609576096760977609876099761007610176102761037610476105761067610776108761097611076111761127611376114761157611676117761187611976120761217612276123761247612576126761277612876129761307613176132761337613476135761367613776138761397614076141761427614376144761457614676147761487614976150761517615276153761547615576156761577615876159761607616176162761637616476165761667616776168761697617076171761727617376174761757617676177761787617976180761817618276183761847618576186761877618876189761907619176192761937619476195761967619776198761997620076201762027620376204762057620676207762087620976210762117621276213762147621576216762177621876219762207622176222762237622476225762267622776228762297623076231762327623376234762357623676237762387623976240762417624276243762447624576246762477624876249762507625176252762537625476255762567625776258762597626076261762627626376264762657626676267762687626976270762717627276273762747627576276762777627876279762807628176282762837628476285762867628776288762897629076291762927629376294762957629676297762987629976300763017630276303763047630576306763077630876309763107631176312763137631476315763167631776318763197632076321763227632376324763257632676327763287632976330763317633276333763347633576336763377633876339763407634176342763437634476345763467634776348763497635076351763527635376354763557635676357763587635976360763617636276363763647636576366763677636876369763707637176372763737637476375763767637776378763797638076381763827638376384763857638676387763887638976390763917639276393763947639576396763977639876399764007640176402764037640476405764067640776408764097641076411764127641376414764157641676417764187641976420764217642276423764247642576426764277642876429764307643176432764337643476435764367643776438764397644076441764427644376444764457644676447764487644976450764517645276453764547645576456764577645876459764607646176462764637646476465764667646776468764697647076471764727647376474764757647676477764787647976480764817648276483764847648576486764877648876489764907649176492764937649476495764967649776498764997650076501765027650376504765057650676507765087650976510765117651276513765147651576516765177651876519765207652176522765237652476525765267652776528765297653076531765327653376534765357653676537765387653976540765417654276543765447654576546765477654876549765507655176552765537655476555765567655776558765597656076561765627656376564765657656676567765687656976570765717657276573765747657576576765777657876579765807658176582765837658476585765867658776588765897659076591765927659376594765957659676597765987659976600766017660276603766047660576606766077660876609766107661176612766137661476615766167661776618766197662076621766227662376624766257662676627766287662976630766317663276633766347663576636766377663876639766407664176642766437664476645766467664776648766497665076651766527665376654766557665676657766587665976660766617666276663766647666576666766677666876669766707667176672766737667476675766767667776678766797668076681766827668376684766857668676687766887668976690766917669276693766947669576696766977669876699767007670176702767037670476705767067670776708767097671076711767127671376714767157671676717767187671976720767217672276723767247672576726767277672876729767307673176732767337673476735767367673776738767397674076741767427674376744767457674676747767487674976750767517675276753767547675576756767577675876759767607676176762767637676476765767667676776768767697677076771767727677376774767757677676777767787677976780767817678276783767847678576786767877678876789767907679176792767937679476795767967679776798767997680076801768027680376804768057680676807768087680976810768117681276813768147681576816768177681876819768207682176822768237682476825768267682776828768297683076831768327683376834768357683676837768387683976840768417684276843768447684576846768477684876849768507685176852768537685476855768567685776858768597686076861768627686376864768657686676867768687686976870768717687276873768747687576876768777687876879768807688176882768837688476885768867688776888768897689076891768927689376894768957689676897768987689976900769017690276903769047690576906769077690876909769107691176912769137691476915769167691776918769197692076921769227692376924769257692676927769287692976930769317693276933769347693576936769377693876939769407694176942769437694476945769467694776948769497695076951769527695376954769557695676957769587695976960769617696276963769647696576966769677696876969769707697176972769737697476975769767697776978769797698076981769827698376984769857698676987769887698976990769917699276993769947699576996769977699876999770007700177002770037700477005770067700777008770097701077011770127701377014770157701677017770187701977020770217702277023770247702577026770277702877029770307703177032770337703477035770367703777038770397704077041770427704377044770457704677047770487704977050770517705277053770547705577056770577705877059770607706177062770637706477065770667706777068770697707077071770727707377074770757707677077770787707977080770817708277083770847708577086770877708877089770907709177092770937709477095770967709777098770997710077101771027710377104771057710677107771087710977110771117711277113771147711577116771177711877119771207712177122771237712477125771267712777128771297713077131771327713377134771357713677137771387713977140771417714277143771447714577146771477714877149771507715177152771537715477155771567715777158771597716077161771627716377164771657716677167771687716977170771717717277173771747717577176771777717877179771807718177182771837718477185771867718777188771897719077191771927719377194771957719677197771987719977200772017720277203772047720577206772077720877209772107721177212772137721477215772167721777218772197722077221772227722377224772257722677227772287722977230772317723277233772347723577236772377723877239772407724177242772437724477245772467724777248772497725077251772527725377254772557725677257772587725977260772617726277263772647726577266772677726877269772707727177272772737727477275772767727777278772797728077281772827728377284772857728677287772887728977290772917729277293772947729577296772977729877299773007730177302773037730477305773067730777308773097731077311773127731377314773157731677317773187731977320773217732277323773247732577326773277732877329773307733177332773337733477335773367733777338773397734077341773427734377344773457734677347773487734977350773517735277353773547735577356773577735877359773607736177362773637736477365773667736777368773697737077371773727737377374773757737677377773787737977380773817738277383773847738577386773877738877389773907739177392773937739477395773967739777398773997740077401774027740377404774057740677407774087740977410774117741277413774147741577416774177741877419774207742177422774237742477425774267742777428774297743077431774327743377434774357743677437774387743977440774417744277443774447744577446774477744877449774507745177452774537745477455774567745777458774597746077461774627746377464774657746677467774687746977470774717747277473774747747577476774777747877479774807748177482774837748477485774867748777488774897749077491774927749377494774957749677497774987749977500775017750277503775047750577506775077750877509775107751177512775137751477515775167751777518775197752077521775227752377524775257752677527775287752977530775317753277533775347753577536775377753877539775407754177542775437754477545775467754777548775497755077551775527755377554775557755677557775587755977560775617756277563775647756577566775677756877569775707757177572775737757477575775767757777578775797758077581775827758377584775857758677587775887758977590775917759277593775947759577596775977759877599776007760177602776037760477605776067760777608776097761077611776127761377614776157761677617776187761977620776217762277623776247762577626776277762877629776307763177632776337763477635776367763777638776397764077641776427764377644776457764677647776487764977650776517765277653776547765577656776577765877659776607766177662776637766477665776667766777668776697767077671776727767377674776757767677677776787767977680776817768277683776847768577686776877768877689776907769177692776937769477695776967769777698776997770077701777027770377704777057770677707777087770977710777117771277713777147771577716777177771877719777207772177722777237772477725777267772777728777297773077731777327773377734777357773677737777387773977740777417774277743777447774577746777477774877749777507775177752777537775477755777567775777758777597776077761777627776377764777657776677767777687776977770777717777277773777747777577776777777777877779777807778177782777837778477785777867778777788777897779077791777927779377794777957779677797777987779977800778017780277803778047780577806778077780877809778107781177812778137781477815778167781777818778197782077821778227782377824778257782677827778287782977830778317783277833778347783577836778377783877839778407784177842778437784477845778467784777848778497785077851778527785377854778557785677857778587785977860778617786277863778647786577866778677786877869778707787177872778737787477875778767787777878778797788077881778827788377884778857788677887778887788977890778917789277893778947789577896778977789877899779007790177902779037790477905779067790777908779097791077911779127791377914779157791677917779187791977920779217792277923779247792577926779277792877929779307793177932779337793477935779367793777938779397794077941779427794377944779457794677947779487794977950779517795277953779547795577956779577795877959779607796177962779637796477965779667796777968779697797077971779727797377974779757797677977779787797977980779817798277983779847798577986779877798877989779907799177992779937799477995779967799777998779997800078001780027800378004780057800678007780087800978010780117801278013780147801578016780177801878019780207802178022780237802478025780267802778028780297803078031780327803378034780357803678037780387803978040780417804278043780447804578046780477804878049780507805178052780537805478055780567805778058780597806078061780627806378064780657806678067780687806978070780717807278073780747807578076780777807878079780807808178082780837808478085780867808778088780897809078091780927809378094780957809678097780987809978100781017810278103781047810578106781077810878109781107811178112781137811478115781167811778118781197812078121781227812378124781257812678127781287812978130781317813278133781347813578136781377813878139781407814178142781437814478145781467814778148781497815078151781527815378154781557815678157781587815978160781617816278163781647816578166781677816878169781707817178172781737817478175781767817778178781797818078181781827818378184781857818678187781887818978190781917819278193781947819578196781977819878199782007820178202782037820478205782067820778208782097821078211782127821378214782157821678217782187821978220782217822278223782247822578226782277822878229782307823178232782337823478235782367823778238782397824078241782427824378244782457824678247782487824978250782517825278253782547825578256782577825878259782607826178262782637826478265782667826778268782697827078271782727827378274782757827678277782787827978280782817828278283782847828578286782877828878289782907829178292782937829478295782967829778298782997830078301783027830378304783057830678307783087830978310783117831278313783147831578316783177831878319783207832178322783237832478325783267832778328783297833078331783327833378334783357833678337783387833978340783417834278343783447834578346783477834878349783507835178352783537835478355783567835778358783597836078361783627836378364783657836678367783687836978370783717837278373783747837578376783777837878379783807838178382783837838478385783867838778388783897839078391783927839378394783957839678397783987839978400784017840278403784047840578406784077840878409784107841178412784137841478415784167841778418784197842078421784227842378424784257842678427784287842978430784317843278433784347843578436784377843878439784407844178442784437844478445784467844778448784497845078451784527845378454784557845678457784587845978460784617846278463784647846578466784677846878469784707847178472784737847478475784767847778478784797848078481784827848378484784857848678487784887848978490784917849278493784947849578496784977849878499785007850178502785037850478505785067850778508785097851078511785127851378514785157851678517785187851978520785217852278523785247852578526785277852878529785307853178532785337853478535785367853778538785397854078541785427854378544785457854678547785487854978550785517855278553785547855578556785577855878559785607856178562785637856478565785667856778568785697857078571785727857378574785757857678577785787857978580785817858278583785847858578586785877858878589785907859178592785937859478595785967859778598785997860078601786027860378604786057860678607786087860978610786117861278613786147861578616786177861878619786207862178622786237862478625786267862778628786297863078631786327863378634786357863678637786387863978640786417864278643786447864578646786477864878649786507865178652786537865478655786567865778658786597866078661786627866378664786657866678667786687866978670786717867278673786747867578676786777867878679786807868178682786837868478685786867868778688786897869078691786927869378694786957869678697786987869978700787017870278703787047870578706787077870878709787107871178712787137871478715787167871778718787197872078721787227872378724787257872678727787287872978730787317873278733787347873578736787377873878739787407874178742787437874478745787467874778748787497875078751787527875378754787557875678757787587875978760787617876278763787647876578766787677876878769787707877178772787737877478775787767877778778787797878078781787827878378784787857878678787787887878978790787917879278793787947879578796787977879878799788007880178802788037880478805788067880778808788097881078811788127881378814788157881678817788187881978820788217882278823788247882578826788277882878829788307883178832788337883478835788367883778838788397884078841788427884378844788457884678847788487884978850788517885278853788547885578856788577885878859788607886178862788637886478865788667886778868788697887078871788727887378874788757887678877788787887978880788817888278883788847888578886788877888878889788907889178892788937889478895788967889778898788997890078901789027890378904789057890678907789087890978910789117891278913789147891578916789177891878919789207892178922789237892478925789267892778928789297893078931789327893378934789357893678937789387893978940789417894278943789447894578946789477894878949789507895178952789537895478955789567895778958789597896078961789627896378964789657896678967789687896978970789717897278973789747897578976789777897878979789807898178982789837898478985789867898778988789897899078991789927899378994789957899678997789987899979000790017900279003790047900579006790077900879009790107901179012790137901479015790167901779018790197902079021790227902379024790257902679027790287902979030790317903279033790347903579036790377903879039790407904179042790437904479045790467904779048790497905079051790527905379054790557905679057790587905979060790617906279063790647906579066790677906879069790707907179072790737907479075790767907779078790797908079081790827908379084790857908679087790887908979090790917909279093790947909579096790977909879099791007910179102791037910479105791067910779108791097911079111791127911379114791157911679117791187911979120791217912279123791247912579126791277912879129791307913179132791337913479135791367913779138791397914079141791427914379144791457914679147791487914979150791517915279153791547915579156791577915879159791607916179162791637916479165791667916779168791697917079171791727917379174791757917679177791787917979180791817918279183791847918579186791877918879189791907919179192791937919479195791967919779198791997920079201792027920379204792057920679207792087920979210792117921279213792147921579216792177921879219792207922179222792237922479225792267922779228792297923079231792327923379234792357923679237792387923979240792417924279243792447924579246792477924879249792507925179252792537925479255792567925779258792597926079261792627926379264792657926679267792687926979270792717927279273792747927579276792777927879279792807928179282792837928479285792867928779288792897929079291792927929379294792957929679297792987929979300793017930279303793047930579306793077930879309793107931179312793137931479315793167931779318793197932079321793227932379324793257932679327793287932979330793317933279333793347933579336793377933879339793407934179342793437934479345793467934779348793497935079351793527935379354793557935679357793587935979360793617936279363793647936579366793677936879369793707937179372793737937479375793767937779378793797938079381793827938379384793857938679387793887938979390793917939279393793947939579396793977939879399794007940179402794037940479405794067940779408794097941079411794127941379414794157941679417794187941979420794217942279423794247942579426794277942879429794307943179432794337943479435794367943779438794397944079441794427944379444794457944679447794487944979450794517945279453794547945579456794577945879459794607946179462794637946479465794667946779468794697947079471794727947379474794757947679477794787947979480794817948279483794847948579486794877948879489794907949179492794937949479495794967949779498794997950079501795027950379504795057950679507795087950979510795117951279513795147951579516795177951879519795207952179522795237952479525795267952779528795297953079531795327953379534795357953679537795387953979540795417954279543795447954579546795477954879549795507955179552795537955479555795567955779558795597956079561795627956379564795657956679567795687956979570795717957279573795747957579576795777957879579795807958179582795837958479585795867958779588795897959079591795927959379594795957959679597795987959979600796017960279603796047960579606796077960879609796107961179612796137961479615796167961779618796197962079621796227962379624796257962679627796287962979630796317963279633796347963579636796377963879639796407964179642796437964479645796467964779648796497965079651796527965379654796557965679657796587965979660796617966279663796647966579666796677966879669796707967179672796737967479675796767967779678796797968079681796827968379684796857968679687796887968979690796917969279693796947969579696796977969879699797007970179702797037970479705797067970779708797097971079711797127971379714797157971679717797187971979720797217972279723797247972579726797277972879729797307973179732797337973479735797367973779738797397974079741797427974379744797457974679747797487974979750797517975279753797547975579756797577975879759797607976179762797637976479765797667976779768797697977079771797727977379774797757977679777797787977979780797817978279783797847978579786797877978879789797907979179792797937979479795797967979779798797997980079801798027980379804798057980679807798087980979810798117981279813798147981579816798177981879819798207982179822798237982479825798267982779828798297983079831798327983379834798357983679837798387983979840798417984279843798447984579846798477984879849798507985179852798537985479855798567985779858798597986079861798627986379864798657986679867798687986979870798717987279873798747987579876798777987879879798807988179882798837988479885798867988779888798897989079891798927989379894798957989679897798987989979900799017990279903799047990579906799077990879909799107991179912799137991479915799167991779918799197992079921799227992379924799257992679927799287992979930799317993279933799347993579936799377993879939799407994179942799437994479945799467994779948799497995079951799527995379954799557995679957799587995979960799617996279963799647996579966799677996879969799707997179972799737997479975799767997779978799797998079981799827998379984799857998679987799887998979990799917999279993799947999579996799977999879999800008000180002800038000480005800068000780008800098001080011800128001380014800158001680017800188001980020800218002280023800248002580026800278002880029800308003180032800338003480035800368003780038800398004080041800428004380044800458004680047800488004980050800518005280053800548005580056800578005880059800608006180062800638006480065800668006780068800698007080071800728007380074800758007680077800788007980080800818008280083800848008580086800878008880089800908009180092800938009480095800968009780098800998010080101801028010380104801058010680107801088010980110801118011280113801148011580116801178011880119801208012180122801238012480125801268012780128801298013080131801328013380134801358013680137801388013980140801418014280143801448014580146801478014880149801508015180152801538015480155801568015780158801598016080161801628016380164801658016680167801688016980170801718017280173801748017580176801778017880179801808018180182801838018480185801868018780188801898019080191801928019380194801958019680197801988019980200802018020280203802048020580206802078020880209802108021180212802138021480215802168021780218802198022080221802228022380224802258022680227802288022980230802318023280233802348023580236802378023880239802408024180242802438024480245802468024780248802498025080251802528025380254802558025680257802588025980260802618026280263802648026580266802678026880269802708027180272802738027480275802768027780278802798028080281802828028380284802858028680287802888028980290802918029280293802948029580296802978029880299803008030180302803038030480305803068030780308803098031080311803128031380314803158031680317803188031980320803218032280323803248032580326803278032880329803308033180332803338033480335803368033780338803398034080341803428034380344803458034680347803488034980350803518035280353803548035580356803578035880359803608036180362803638036480365803668036780368803698037080371803728037380374803758037680377803788037980380803818038280383803848038580386803878038880389803908039180392803938039480395803968039780398803998040080401804028040380404804058040680407804088040980410804118041280413804148041580416804178041880419804208042180422804238042480425804268042780428804298043080431804328043380434804358043680437804388043980440804418044280443804448044580446804478044880449804508045180452804538045480455804568045780458804598046080461804628046380464804658046680467804688046980470804718047280473804748047580476804778047880479804808048180482804838048480485804868048780488804898049080491804928049380494804958049680497804988049980500805018050280503805048050580506805078050880509805108051180512805138051480515805168051780518805198052080521805228052380524805258052680527805288052980530805318053280533805348053580536805378053880539805408054180542805438054480545805468054780548805498055080551805528055380554805558055680557805588055980560805618056280563805648056580566805678056880569805708057180572805738057480575805768057780578805798058080581805828058380584805858058680587805888058980590805918059280593805948059580596805978059880599806008060180602806038060480605806068060780608806098061080611806128061380614806158061680617806188061980620806218062280623806248062580626806278062880629806308063180632806338063480635806368063780638806398064080641806428064380644806458064680647806488064980650806518065280653806548065580656806578065880659806608066180662806638066480665806668066780668806698067080671806728067380674806758067680677806788067980680806818068280683806848068580686806878068880689806908069180692806938069480695806968069780698806998070080701807028070380704807058070680707807088070980710807118071280713807148071580716807178071880719807208072180722807238072480725807268072780728807298073080731807328073380734807358073680737807388073980740807418074280743807448074580746807478074880749807508075180752807538075480755807568075780758807598076080761807628076380764807658076680767807688076980770807718077280773807748077580776807778077880779807808078180782807838078480785807868078780788807898079080791807928079380794807958079680797807988079980800808018080280803808048080580806808078080880809808108081180812808138081480815808168081780818808198082080821808228082380824808258082680827808288082980830808318083280833808348083580836808378083880839808408084180842808438084480845808468084780848808498085080851808528085380854808558085680857808588085980860808618086280863808648086580866808678086880869808708087180872808738087480875808768087780878808798088080881808828088380884808858088680887808888088980890808918089280893808948089580896808978089880899809008090180902809038090480905809068090780908809098091080911809128091380914809158091680917809188091980920809218092280923809248092580926809278092880929809308093180932809338093480935809368093780938809398094080941809428094380944809458094680947809488094980950809518095280953809548095580956809578095880959809608096180962809638096480965809668096780968809698097080971809728097380974809758097680977809788097980980809818098280983809848098580986809878098880989809908099180992809938099480995809968099780998809998100081001810028100381004810058100681007810088100981010810118101281013810148101581016810178101881019810208102181022810238102481025810268102781028810298103081031810328103381034810358103681037810388103981040810418104281043810448104581046810478104881049810508105181052810538105481055810568105781058810598106081061810628106381064810658106681067810688106981070810718107281073810748107581076810778107881079810808108181082810838108481085810868108781088810898109081091810928109381094810958109681097810988109981100811018110281103811048110581106811078110881109811108111181112811138111481115811168111781118811198112081121811228112381124811258112681127811288112981130811318113281133811348113581136811378113881139811408114181142811438114481145811468114781148811498115081151811528115381154811558115681157811588115981160811618116281163811648116581166811678116881169811708117181172811738117481175811768117781178811798118081181811828118381184811858118681187811888118981190811918119281193811948119581196811978119881199812008120181202812038120481205812068120781208812098121081211812128121381214812158121681217812188121981220812218122281223812248122581226812278122881229812308123181232812338123481235812368123781238812398124081241812428124381244812458124681247812488124981250812518125281253812548125581256812578125881259812608126181262812638126481265812668126781268812698127081271812728127381274812758127681277812788127981280812818128281283812848128581286812878128881289812908129181292812938129481295812968129781298812998130081301813028130381304813058130681307813088130981310813118131281313813148131581316813178131881319813208132181322813238132481325813268132781328813298133081331813328133381334813358133681337813388133981340813418134281343813448134581346813478134881349813508135181352813538135481355813568135781358813598136081361813628136381364813658136681367813688136981370813718137281373813748137581376813778137881379813808138181382813838138481385813868138781388813898139081391813928139381394813958139681397813988139981400814018140281403814048140581406814078140881409814108141181412814138141481415814168141781418814198142081421814228142381424814258142681427814288142981430814318143281433814348143581436814378143881439814408144181442814438144481445814468144781448814498145081451814528145381454814558145681457814588145981460814618146281463814648146581466814678146881469814708147181472814738147481475814768147781478814798148081481814828148381484814858148681487814888148981490814918149281493814948149581496814978149881499815008150181502815038150481505815068150781508815098151081511815128151381514815158151681517815188151981520815218152281523815248152581526815278152881529815308153181532815338153481535815368153781538815398154081541815428154381544815458154681547815488154981550815518155281553815548155581556815578155881559815608156181562815638156481565815668156781568815698157081571815728157381574815758157681577815788157981580815818158281583815848158581586815878158881589815908159181592815938159481595815968159781598815998160081601816028160381604816058160681607816088160981610816118161281613816148161581616816178161881619816208162181622816238162481625816268162781628816298163081631816328163381634816358163681637816388163981640816418164281643816448164581646816478164881649816508165181652816538165481655816568165781658816598166081661816628166381664816658166681667816688166981670816718167281673816748167581676816778167881679816808168181682816838168481685816868168781688816898169081691816928169381694816958169681697816988169981700817018170281703817048170581706817078170881709817108171181712817138171481715817168171781718817198172081721817228172381724817258172681727817288172981730817318173281733817348173581736817378173881739817408174181742817438174481745817468174781748817498175081751817528175381754817558175681757817588175981760817618176281763817648176581766817678176881769817708177181772817738177481775817768177781778817798178081781817828178381784817858178681787817888178981790817918179281793817948179581796817978179881799818008180181802818038180481805818068180781808818098181081811818128181381814818158181681817818188181981820818218182281823818248182581826818278182881829818308183181832818338183481835818368183781838818398184081841818428184381844818458184681847818488184981850818518185281853818548185581856818578185881859818608186181862818638186481865818668186781868818698187081871818728187381874818758187681877818788187981880818818188281883818848188581886818878188881889818908189181892818938189481895818968189781898818998190081901819028190381904819058190681907819088190981910819118191281913819148191581916819178191881919819208192181922819238192481925819268192781928819298193081931819328193381934819358193681937819388193981940819418194281943819448194581946819478194881949819508195181952819538195481955819568195781958819598196081961819628196381964819658196681967819688196981970819718197281973819748197581976819778197881979819808198181982819838198481985819868198781988819898199081991819928199381994819958199681997819988199982000820018200282003820048200582006820078200882009820108201182012820138201482015820168201782018820198202082021820228202382024820258202682027820288202982030820318203282033820348203582036820378203882039820408204182042820438204482045820468204782048820498205082051820528205382054820558205682057820588205982060820618206282063820648206582066820678206882069820708207182072820738207482075820768207782078820798208082081820828208382084820858208682087820888208982090820918209282093820948209582096820978209882099821008210182102821038210482105821068210782108821098211082111821128211382114821158211682117821188211982120821218212282123821248212582126821278212882129821308213182132821338213482135821368213782138821398214082141821428214382144821458214682147821488214982150821518215282153821548215582156821578215882159821608216182162821638216482165821668216782168821698217082171821728217382174821758217682177821788217982180821818218282183821848218582186821878218882189821908219182192821938219482195821968219782198821998220082201822028220382204822058220682207822088220982210822118221282213822148221582216822178221882219822208222182222822238222482225822268222782228822298223082231822328223382234822358223682237822388223982240822418224282243822448224582246822478224882249822508225182252822538225482255822568225782258822598226082261822628226382264822658226682267822688226982270822718227282273822748227582276822778227882279822808228182282822838228482285822868228782288822898229082291822928229382294822958229682297822988229982300823018230282303823048230582306823078230882309823108231182312823138231482315823168231782318823198232082321823228232382324823258232682327823288232982330823318233282333823348233582336823378233882339823408234182342823438234482345823468234782348823498235082351823528235382354823558235682357823588235982360823618236282363823648236582366823678236882369823708237182372823738237482375823768237782378823798238082381823828238382384823858238682387823888238982390823918239282393823948239582396823978239882399824008240182402824038240482405824068240782408824098241082411824128241382414824158241682417824188241982420824218242282423824248242582426824278242882429824308243182432824338243482435824368243782438824398244082441824428244382444824458244682447824488244982450824518245282453824548245582456824578245882459824608246182462824638246482465824668246782468824698247082471824728247382474824758247682477824788247982480824818248282483824848248582486824878248882489824908249182492824938249482495824968249782498824998250082501825028250382504825058250682507825088250982510825118251282513825148251582516825178251882519825208252182522825238252482525825268252782528825298253082531825328253382534825358253682537825388253982540825418254282543825448254582546825478254882549825508255182552825538255482555825568255782558825598256082561825628256382564825658256682567825688256982570825718257282573825748257582576825778257882579825808258182582825838258482585825868258782588825898259082591825928259382594825958259682597825988259982600826018260282603826048260582606826078260882609826108261182612826138261482615826168261782618826198262082621826228262382624826258262682627826288262982630826318263282633826348263582636826378263882639826408264182642826438264482645826468264782648826498265082651826528265382654826558265682657826588265982660826618266282663826648266582666826678266882669826708267182672826738267482675826768267782678826798268082681826828268382684826858268682687826888268982690826918269282693826948269582696826978269882699827008270182702827038270482705827068270782708827098271082711827128271382714827158271682717827188271982720827218272282723827248272582726827278272882729827308273182732827338273482735827368273782738827398274082741827428274382744827458274682747827488274982750827518275282753827548275582756827578275882759827608276182762827638276482765827668276782768827698277082771827728277382774827758277682777827788277982780827818278282783827848278582786827878278882789827908279182792827938279482795827968279782798827998280082801828028280382804828058280682807828088280982810828118281282813828148281582816828178281882819828208282182822828238282482825828268282782828828298283082831828328283382834828358283682837828388283982840828418284282843828448284582846828478284882849828508285182852828538285482855828568285782858828598286082861828628286382864828658286682867828688286982870828718287282873828748287582876828778287882879828808288182882828838288482885828868288782888828898289082891828928289382894828958289682897828988289982900829018290282903829048290582906829078290882909829108291182912829138291482915829168291782918829198292082921829228292382924829258292682927829288292982930829318293282933829348293582936829378293882939829408294182942829438294482945829468294782948829498295082951829528295382954829558295682957829588295982960829618296282963829648296582966829678296882969829708297182972829738297482975829768297782978829798298082981829828298382984829858298682987829888298982990829918299282993829948299582996829978299882999830008300183002830038300483005830068300783008830098301083011830128301383014830158301683017830188301983020830218302283023830248302583026830278302883029830308303183032830338303483035830368303783038830398304083041830428304383044830458304683047830488304983050830518305283053830548305583056830578305883059830608306183062830638306483065830668306783068830698307083071830728307383074830758307683077830788307983080830818308283083830848308583086830878308883089830908309183092830938309483095830968309783098830998310083101831028310383104831058310683107831088310983110831118311283113831148311583116831178311883119831208312183122831238312483125831268312783128831298313083131831328313383134831358313683137831388313983140831418314283143831448314583146831478314883149831508315183152831538315483155831568315783158831598316083161831628316383164831658316683167831688316983170831718317283173831748317583176831778317883179831808318183182831838318483185831868318783188831898319083191831928319383194831958319683197831988319983200832018320283203832048320583206832078320883209832108321183212832138321483215832168321783218832198322083221832228322383224832258322683227832288322983230832318323283233832348323583236832378323883239832408324183242832438324483245832468324783248832498325083251832528325383254832558325683257832588325983260832618326283263832648326583266832678326883269832708327183272832738327483275832768327783278832798328083281832828328383284832858328683287832888328983290832918329283293832948329583296832978329883299833008330183302833038330483305833068330783308833098331083311833128331383314833158331683317833188331983320833218332283323833248332583326833278332883329833308333183332833338333483335833368333783338833398334083341833428334383344833458334683347833488334983350833518335283353833548335583356833578335883359833608336183362833638336483365833668336783368833698337083371833728337383374833758337683377833788337983380833818338283383833848338583386833878338883389833908339183392833938339483395833968339783398833998340083401834028340383404834058340683407834088340983410834118341283413834148341583416834178341883419834208342183422834238342483425834268342783428834298343083431834328343383434834358343683437834388343983440834418344283443834448344583446834478344883449834508345183452834538345483455834568345783458834598346083461834628346383464834658346683467834688346983470834718347283473834748347583476834778347883479834808348183482834838348483485834868348783488834898349083491834928349383494834958349683497834988349983500835018350283503835048350583506835078350883509835108351183512835138351483515835168351783518835198352083521835228352383524835258352683527835288352983530835318353283533835348353583536835378353883539835408354183542835438354483545835468354783548835498355083551835528355383554835558355683557835588355983560835618356283563835648356583566835678356883569835708357183572835738357483575835768357783578835798358083581835828358383584835858358683587835888358983590835918359283593835948359583596835978359883599836008360183602836038360483605836068360783608836098361083611836128361383614836158361683617836188361983620836218362283623836248362583626836278362883629836308363183632836338363483635836368363783638836398364083641836428364383644836458364683647836488364983650836518365283653836548365583656836578365883659836608366183662836638366483665836668366783668836698367083671836728367383674836758367683677836788367983680836818368283683836848368583686836878368883689836908369183692836938369483695836968369783698836998370083701837028370383704837058370683707837088370983710837118371283713837148371583716837178371883719837208372183722837238372483725837268372783728837298373083731837328373383734837358373683737837388373983740837418374283743837448374583746837478374883749837508375183752837538375483755837568375783758837598376083761837628376383764837658376683767837688376983770837718377283773837748377583776837778377883779837808378183782837838378483785837868378783788837898379083791837928379383794837958379683797837988379983800838018380283803838048380583806838078380883809838108381183812838138381483815838168381783818838198382083821838228382383824838258382683827838288382983830838318383283833838348383583836838378383883839838408384183842838438384483845838468384783848838498385083851838528385383854838558385683857838588385983860838618386283863838648386583866838678386883869838708387183872838738387483875838768387783878838798388083881838828388383884838858388683887838888388983890838918389283893838948389583896838978389883899839008390183902839038390483905839068390783908839098391083911839128391383914839158391683917839188391983920839218392283923839248392583926839278392883929839308393183932839338393483935839368393783938839398394083941839428394383944839458394683947839488394983950839518395283953839548395583956839578395883959839608396183962839638396483965839668396783968839698397083971839728397383974839758397683977839788397983980839818398283983839848398583986839878398883989839908399183992839938399483995839968399783998839998400084001840028400384004840058400684007840088400984010840118401284013840148401584016840178401884019840208402184022840238402484025840268402784028840298403084031840328403384034840358403684037840388403984040840418404284043840448404584046840478404884049840508405184052840538405484055840568405784058840598406084061840628406384064840658406684067840688406984070840718407284073840748407584076840778407884079840808408184082840838408484085840868408784088840898409084091840928409384094840958409684097840988409984100841018410284103841048410584106841078410884109841108411184112841138411484115841168411784118841198412084121841228412384124841258412684127841288412984130841318413284133841348413584136841378413884139841408414184142841438414484145841468414784148841498415084151841528415384154841558415684157841588415984160841618416284163841648416584166841678416884169841708417184172841738417484175841768417784178841798418084181841828418384184841858418684187841888418984190841918419284193841948419584196841978419884199842008420184202842038420484205842068420784208842098421084211842128421384214842158421684217842188421984220842218422284223842248422584226842278422884229842308423184232842338423484235842368423784238842398424084241842428424384244842458424684247842488424984250842518425284253842548425584256842578425884259842608426184262842638426484265842668426784268842698427084271842728427384274842758427684277842788427984280842818428284283842848428584286842878428884289842908429184292842938429484295842968429784298842998430084301843028430384304843058430684307843088430984310843118431284313843148431584316843178431884319843208432184322843238432484325843268432784328843298433084331843328433384334843358433684337843388433984340843418434284343843448434584346843478434884349843508435184352843538435484355843568435784358843598436084361843628436384364843658436684367843688436984370843718437284373843748437584376843778437884379843808438184382843838438484385843868438784388843898439084391843928439384394843958439684397843988439984400844018440284403844048440584406844078440884409844108441184412844138441484415844168441784418844198442084421844228442384424844258442684427844288442984430844318443284433844348443584436844378443884439844408444184442844438444484445844468444784448844498445084451844528445384454844558445684457844588445984460844618446284463844648446584466844678446884469844708447184472844738447484475844768447784478844798448084481844828448384484844858448684487844888448984490844918449284493844948449584496844978449884499845008450184502845038450484505845068450784508845098451084511845128451384514845158451684517845188451984520845218452284523845248452584526845278452884529845308453184532845338453484535845368453784538845398454084541845428454384544845458454684547845488454984550845518455284553845548455584556845578455884559845608456184562845638456484565845668456784568845698457084571845728457384574845758457684577845788457984580845818458284583845848458584586845878458884589845908459184592845938459484595845968459784598845998460084601846028460384604846058460684607846088460984610846118461284613846148461584616846178461884619846208462184622846238462484625846268462784628846298463084631846328463384634846358463684637846388463984640846418464284643846448464584646846478464884649846508465184652846538465484655846568465784658846598466084661846628466384664846658466684667846688466984670846718467284673846748467584676846778467884679846808468184682846838468484685846868468784688846898469084691846928469384694846958469684697846988469984700847018470284703847048470584706847078470884709847108471184712847138471484715847168471784718847198472084721847228472384724847258472684727847288472984730847318473284733847348473584736847378473884739847408474184742847438474484745847468474784748847498475084751847528475384754847558475684757847588475984760847618476284763847648476584766847678476884769847708477184772847738477484775847768477784778847798478084781847828478384784847858478684787847888478984790847918479284793847948479584796847978479884799848008480184802848038480484805848068480784808848098481084811848128481384814848158481684817848188481984820848218482284823848248482584826848278482884829848308483184832848338483484835848368483784838848398484084841848428484384844848458484684847848488484984850848518485284853848548485584856848578485884859848608486184862848638486484865848668486784868848698487084871848728487384874848758487684877848788487984880848818488284883848848488584886848878488884889848908489184892848938489484895848968489784898848998490084901849028490384904849058490684907849088490984910849118491284913849148491584916849178491884919849208492184922849238492484925849268492784928849298493084931849328493384934849358493684937849388493984940849418494284943849448494584946849478494884949849508495184952849538495484955849568495784958849598496084961849628496384964849658496684967849688496984970849718497284973849748497584976849778497884979849808498184982849838498484985849868498784988849898499084991849928499384994849958499684997849988499985000850018500285003850048500585006850078500885009850108501185012850138501485015850168501785018850198502085021850228502385024850258502685027850288502985030850318503285033850348503585036850378503885039850408504185042850438504485045850468504785048850498505085051850528505385054850558505685057850588505985060850618506285063850648506585066850678506885069850708507185072850738507485075850768507785078850798508085081850828508385084850858508685087850888508985090850918509285093850948509585096850978509885099851008510185102851038510485105851068510785108851098511085111851128511385114851158511685117851188511985120851218512285123851248512585126851278512885129851308513185132851338513485135851368513785138851398514085141851428514385144851458514685147851488514985150851518515285153851548515585156851578515885159851608516185162851638516485165851668516785168851698517085171851728517385174851758517685177851788517985180851818518285183851848518585186851878518885189851908519185192851938519485195851968519785198851998520085201852028520385204852058520685207852088520985210852118521285213852148521585216852178521885219852208522185222852238522485225852268522785228852298523085231852328523385234852358523685237852388523985240852418524285243852448524585246852478524885249852508525185252852538525485255852568525785258852598526085261852628526385264852658526685267852688526985270852718527285273852748527585276852778527885279852808528185282852838528485285852868528785288852898529085291852928529385294852958529685297852988529985300853018530285303853048530585306853078530885309853108531185312853138531485315853168531785318853198532085321853228532385324853258532685327853288532985330853318533285333853348533585336853378533885339853408534185342853438534485345853468534785348853498535085351853528535385354853558535685357853588535985360853618536285363853648536585366853678536885369853708537185372853738537485375853768537785378853798538085381853828538385384853858538685387853888538985390853918539285393853948539585396853978539885399854008540185402854038540485405854068540785408854098541085411854128541385414854158541685417854188541985420854218542285423854248542585426854278542885429854308543185432854338543485435854368543785438854398544085441854428544385444854458544685447854488544985450854518545285453854548545585456854578545885459854608546185462854638546485465854668546785468854698547085471854728547385474854758547685477854788547985480854818548285483854848548585486854878548885489854908549185492854938549485495854968549785498854998550085501855028550385504855058550685507855088550985510855118551285513855148551585516855178551885519855208552185522855238552485525855268552785528855298553085531855328553385534855358553685537855388553985540855418554285543855448554585546855478554885549855508555185552855538555485555855568555785558855598556085561855628556385564855658556685567855688556985570855718557285573855748557585576855778557885579855808558185582855838558485585855868558785588855898559085591855928559385594855958559685597855988559985600856018560285603856048560585606856078560885609856108561185612856138561485615856168561785618856198562085621856228562385624856258562685627856288562985630856318563285633856348563585636856378563885639856408564185642856438564485645856468564785648856498565085651856528565385654856558565685657856588565985660856618566285663856648566585666856678566885669856708567185672856738567485675856768567785678856798568085681856828568385684856858568685687856888568985690856918569285693856948569585696856978569885699857008570185702857038570485705857068570785708857098571085711857128571385714857158571685717857188571985720857218572285723857248572585726857278572885729857308573185732857338573485735857368573785738857398574085741857428574385744857458574685747857488574985750857518575285753857548575585756857578575885759857608576185762857638576485765857668576785768857698577085771857728577385774857758577685777857788577985780857818578285783857848578585786857878578885789857908579185792857938579485795857968579785798857998580085801858028580385804858058580685807858088580985810858118581285813858148581585816858178581885819858208582185822858238582485825858268582785828858298583085831858328583385834858358583685837858388583985840858418584285843858448584585846858478584885849858508585185852858538585485855858568585785858858598586085861858628586385864858658586685867858688586985870858718587285873858748587585876858778587885879858808588185882858838588485885858868588785888858898589085891858928589385894858958589685897858988589985900859018590285903859048590585906859078590885909859108591185912859138591485915859168591785918859198592085921859228592385924859258592685927859288592985930859318593285933859348593585936859378593885939859408594185942859438594485945859468594785948859498595085951859528595385954859558595685957859588595985960859618596285963859648596585966859678596885969859708597185972859738597485975859768597785978859798598085981859828598385984859858598685987859888598985990859918599285993859948599585996859978599885999860008600186002860038600486005860068600786008860098601086011860128601386014860158601686017860188601986020860218602286023860248602586026860278602886029860308603186032860338603486035860368603786038860398604086041860428604386044860458604686047860488604986050860518605286053860548605586056860578605886059860608606186062860638606486065860668606786068860698607086071860728607386074860758607686077860788607986080860818608286083860848608586086860878608886089860908609186092860938609486095860968609786098860998610086101861028610386104861058610686107861088610986110861118611286113861148611586116861178611886119861208612186122861238612486125861268612786128861298613086131861328613386134861358613686137861388613986140861418614286143861448614586146861478614886149861508615186152861538615486155861568615786158861598616086161861628616386164861658616686167861688616986170861718617286173861748617586176861778617886179861808618186182861838618486185861868618786188861898619086191861928619386194861958619686197861988619986200862018620286203862048620586206862078620886209862108621186212862138621486215862168621786218862198622086221862228622386224862258622686227862288622986230862318623286233862348623586236862378623886239862408624186242862438624486245862468624786248862498625086251862528625386254862558625686257862588625986260862618626286263862648626586266862678626886269862708627186272862738627486275862768627786278862798628086281862828628386284862858628686287862888628986290862918629286293862948629586296862978629886299863008630186302863038630486305863068630786308863098631086311863128631386314863158631686317863188631986320863218632286323863248632586326863278632886329863308633186332863338633486335863368633786338863398634086341863428634386344863458634686347863488634986350863518635286353863548635586356863578635886359863608636186362863638636486365863668636786368863698637086371863728637386374863758637686377863788637986380863818638286383863848638586386863878638886389863908639186392863938639486395863968639786398863998640086401864028640386404864058640686407864088640986410864118641286413864148641586416864178641886419864208642186422864238642486425864268642786428864298643086431864328643386434864358643686437864388643986440864418644286443864448644586446864478644886449864508645186452864538645486455864568645786458864598646086461864628646386464864658646686467864688646986470864718647286473864748647586476864778647886479864808648186482864838648486485864868648786488864898649086491864928649386494864958649686497864988649986500865018650286503865048650586506865078650886509865108651186512865138651486515865168651786518865198652086521865228652386524865258652686527865288652986530865318653286533865348653586536865378653886539865408654186542865438654486545865468654786548865498655086551865528655386554865558655686557865588655986560865618656286563865648656586566865678656886569865708657186572865738657486575865768657786578865798658086581865828658386584865858658686587865888658986590865918659286593865948659586596865978659886599866008660186602866038660486605866068660786608866098661086611866128661386614866158661686617866188661986620866218662286623866248662586626866278662886629866308663186632866338663486635866368663786638866398664086641866428664386644866458664686647866488664986650866518665286653866548665586656866578665886659866608666186662866638666486665866668666786668866698667086671866728667386674866758667686677866788667986680866818668286683866848668586686866878668886689866908669186692866938669486695866968669786698866998670086701867028670386704867058670686707867088670986710867118671286713867148671586716867178671886719867208672186722867238672486725867268672786728867298673086731867328673386734867358673686737867388673986740867418674286743867448674586746867478674886749867508675186752867538675486755867568675786758867598676086761867628676386764867658676686767867688676986770867718677286773867748677586776867778677886779867808678186782867838678486785867868678786788867898679086791867928679386794867958679686797867988679986800868018680286803868048680586806868078680886809868108681186812868138681486815868168681786818868198682086821868228682386824868258682686827868288682986830868318683286833868348683586836868378683886839868408684186842868438684486845868468684786848868498685086851868528685386854868558685686857868588685986860868618686286863868648686586866868678686886869868708687186872868738687486875868768687786878868798688086881868828688386884868858688686887868888688986890868918689286893868948689586896868978689886899869008690186902869038690486905869068690786908869098691086911869128691386914869158691686917869188691986920869218692286923869248692586926869278692886929869308693186932869338693486935869368693786938869398694086941869428694386944869458694686947869488694986950869518695286953869548695586956869578695886959869608696186962869638696486965869668696786968869698697086971869728697386974869758697686977869788697986980869818698286983869848698586986869878698886989869908699186992869938699486995869968699786998869998700087001870028700387004870058700687007870088700987010870118701287013870148701587016870178701887019870208702187022870238702487025870268702787028870298703087031870328703387034870358703687037870388703987040870418704287043870448704587046870478704887049870508705187052870538705487055870568705787058870598706087061870628706387064870658706687067870688706987070870718707287073870748707587076870778707887079870808708187082870838708487085870868708787088870898709087091870928709387094870958709687097870988709987100871018710287103871048710587106871078710887109871108711187112871138711487115871168711787118871198712087121871228712387124871258712687127871288712987130871318713287133871348713587136871378713887139871408714187142871438714487145871468714787148871498715087151871528715387154871558715687157871588715987160871618716287163871648716587166871678716887169871708717187172871738717487175871768717787178871798718087181871828718387184871858718687187871888718987190871918719287193871948719587196871978719887199872008720187202872038720487205872068720787208872098721087211872128721387214872158721687217872188721987220872218722287223872248722587226872278722887229872308723187232872338723487235872368723787238872398724087241872428724387244872458724687247872488724987250872518725287253872548725587256872578725887259872608726187262872638726487265872668726787268872698727087271872728727387274872758727687277872788727987280872818728287283872848728587286872878728887289872908729187292872938729487295872968729787298872998730087301873028730387304873058730687307873088730987310873118731287313873148731587316873178731887319873208732187322873238732487325873268732787328873298733087331873328733387334873358733687337873388733987340873418734287343873448734587346873478734887349873508735187352873538735487355873568735787358873598736087361873628736387364873658736687367873688736987370873718737287373873748737587376873778737887379873808738187382873838738487385873868738787388873898739087391873928739387394873958739687397873988739987400874018740287403874048740587406874078740887409874108741187412874138741487415874168741787418874198742087421874228742387424874258742687427874288742987430874318743287433874348743587436874378743887439874408744187442874438744487445874468744787448874498745087451874528745387454874558745687457874588745987460874618746287463874648746587466874678746887469874708747187472874738747487475874768747787478874798748087481874828748387484874858748687487874888748987490874918749287493874948749587496874978749887499875008750187502875038750487505875068750787508875098751087511875128751387514875158751687517875188751987520875218752287523875248752587526875278752887529875308753187532875338753487535875368753787538875398754087541875428754387544875458754687547875488754987550875518755287553875548755587556875578755887559875608756187562875638756487565875668756787568875698757087571875728757387574875758757687577875788757987580875818758287583875848758587586875878758887589875908759187592875938759487595875968759787598875998760087601876028760387604876058760687607876088760987610876118761287613876148761587616876178761887619876208762187622876238762487625876268762787628876298763087631876328763387634876358763687637876388763987640876418764287643876448764587646876478764887649876508765187652876538765487655876568765787658876598766087661876628766387664876658766687667876688766987670876718767287673876748767587676876778767887679876808768187682876838768487685876868768787688876898769087691876928769387694876958769687697876988769987700877018770287703877048770587706877078770887709877108771187712877138771487715877168771787718877198772087721877228772387724877258772687727877288772987730877318773287733877348773587736877378773887739877408774187742877438774487745877468774787748877498775087751877528775387754877558775687757877588775987760877618776287763877648776587766877678776887769877708777187772877738777487775877768777787778877798778087781877828778387784877858778687787877888778987790877918779287793877948779587796877978779887799878008780187802878038780487805878068780787808878098781087811878128781387814878158781687817878188781987820878218782287823878248782587826878278782887829878308783187832878338783487835878368783787838878398784087841878428784387844878458784687847878488784987850878518785287853878548785587856878578785887859878608786187862878638786487865878668786787868878698787087871878728787387874878758787687877878788787987880878818788287883878848788587886878878788887889878908789187892878938789487895878968789787898878998790087901879028790387904879058790687907879088790987910879118791287913879148791587916879178791887919879208792187922879238792487925879268792787928879298793087931879328793387934879358793687937879388793987940879418794287943879448794587946879478794887949879508795187952879538795487955879568795787958879598796087961879628796387964879658796687967879688796987970879718797287973879748797587976879778797887979879808798187982879838798487985879868798787988879898799087991879928799387994879958799687997879988799988000880018800288003880048800588006880078800888009880108801188012880138801488015880168801788018880198802088021880228802388024880258802688027880288802988030880318803288033880348803588036880378803888039880408804188042880438804488045880468804788048880498805088051880528805388054880558805688057880588805988060880618806288063880648806588066880678806888069880708807188072880738807488075880768807788078880798808088081880828808388084880858808688087880888808988090880918809288093880948809588096880978809888099881008810188102881038810488105881068810788108881098811088111881128811388114881158811688117881188811988120881218812288123881248812588126881278812888129881308813188132881338813488135881368813788138881398814088141881428814388144881458814688147881488814988150881518815288153881548815588156881578815888159881608816188162881638816488165881668816788168881698817088171881728817388174881758817688177881788817988180881818818288183881848818588186881878818888189881908819188192881938819488195881968819788198881998820088201882028820388204882058820688207882088820988210882118821288213882148821588216882178821888219882208822188222882238822488225882268822788228882298823088231882328823388234882358823688237882388823988240882418824288243882448824588246882478824888249882508825188252882538825488255882568825788258882598826088261882628826388264882658826688267882688826988270882718827288273882748827588276882778827888279882808828188282882838828488285882868828788288882898829088291882928829388294882958829688297882988829988300883018830288303883048830588306883078830888309883108831188312883138831488315883168831788318883198832088321883228832388324883258832688327883288832988330883318833288333883348833588336883378833888339883408834188342883438834488345883468834788348883498835088351883528835388354883558835688357883588835988360883618836288363883648836588366883678836888369883708837188372883738837488375883768837788378883798838088381883828838388384883858838688387883888838988390883918839288393883948839588396883978839888399884008840188402884038840488405884068840788408884098841088411884128841388414884158841688417884188841988420884218842288423884248842588426884278842888429884308843188432884338843488435884368843788438884398844088441884428844388444884458844688447884488844988450884518845288453884548845588456884578845888459884608846188462884638846488465884668846788468884698847088471884728847388474884758847688477884788847988480884818848288483884848848588486884878848888489884908849188492884938849488495884968849788498884998850088501885028850388504885058850688507885088850988510885118851288513885148851588516885178851888519885208852188522885238852488525885268852788528885298853088531885328853388534885358853688537885388853988540885418854288543885448854588546885478854888549885508855188552885538855488555885568855788558885598856088561885628856388564885658856688567885688856988570885718857288573885748857588576885778857888579885808858188582885838858488585885868858788588885898859088591885928859388594885958859688597885988859988600886018860288603886048860588606886078860888609886108861188612886138861488615886168861788618886198862088621886228862388624886258862688627886288862988630886318863288633886348863588636886378863888639886408864188642886438864488645886468864788648886498865088651886528865388654886558865688657886588865988660886618866288663886648866588666886678866888669886708867188672886738867488675886768867788678886798868088681886828868388684886858868688687886888868988690886918869288693886948869588696886978869888699887008870188702887038870488705887068870788708887098871088711887128871388714887158871688717887188871988720887218872288723887248872588726887278872888729887308873188732887338873488735887368873788738887398874088741887428874388744887458874688747887488874988750887518875288753887548875588756887578875888759887608876188762887638876488765887668876788768887698877088771887728877388774887758877688777887788877988780887818878288783887848878588786887878878888789887908879188792887938879488795887968879788798887998880088801888028880388804888058880688807888088880988810888118881288813888148881588816888178881888819888208882188822888238882488825888268882788828888298883088831888328883388834888358883688837888388883988840888418884288843888448884588846888478884888849888508885188852888538885488855888568885788858888598886088861888628886388864888658886688867888688886988870888718887288873888748887588876888778887888879888808888188882888838888488885888868888788888888898889088891888928889388894888958889688897888988889988900889018890288903889048890588906889078890888909889108891188912889138891488915889168891788918889198892088921889228892388924889258892688927889288892988930889318893288933889348893588936889378893888939889408894188942889438894488945889468894788948889498895088951889528895388954889558895688957889588895988960889618896288963889648896588966889678896888969889708897188972889738897488975889768897788978889798898088981889828898388984889858898688987889888898988990889918899288993889948899588996889978899888999890008900189002890038900489005890068900789008890098901089011890128901389014890158901689017890188901989020890218902289023890248902589026890278902889029890308903189032890338903489035890368903789038890398904089041890428904389044890458904689047890488904989050890518905289053890548905589056890578905889059890608906189062890638906489065890668906789068890698907089071890728907389074890758907689077890788907989080890818908289083890848908589086890878908889089890908909189092890938909489095890968909789098890998910089101891028910389104891058910689107891088910989110891118911289113891148911589116891178911889119891208912189122891238912489125891268912789128891298913089131891328913389134891358913689137891388913989140891418914289143891448914589146891478914889149891508915189152891538915489155891568915789158891598916089161891628916389164891658916689167891688916989170891718917289173891748917589176891778917889179891808918189182891838918489185891868918789188891898919089191891928919389194891958919689197891988919989200892018920289203892048920589206892078920889209892108921189212892138921489215892168921789218892198922089221892228922389224892258922689227892288922989230892318923289233892348923589236892378923889239892408924189242892438924489245892468924789248892498925089251892528925389254892558925689257892588925989260892618926289263892648926589266892678926889269892708927189272892738927489275892768927789278892798928089281892828928389284892858928689287892888928989290892918929289293892948929589296892978929889299893008930189302893038930489305893068930789308893098931089311893128931389314893158931689317893188931989320893218932289323893248932589326893278932889329893308933189332893338933489335893368933789338893398934089341893428934389344893458934689347893488934989350893518935289353893548935589356893578935889359893608936189362893638936489365893668936789368893698937089371893728937389374893758937689377893788937989380893818938289383893848938589386893878938889389893908939189392893938939489395893968939789398893998940089401894028940389404894058940689407894088940989410894118941289413894148941589416894178941889419894208942189422894238942489425894268942789428894298943089431894328943389434894358943689437894388943989440894418944289443894448944589446894478944889449894508945189452894538945489455894568945789458894598946089461894628946389464894658946689467894688946989470894718947289473894748947589476894778947889479894808948189482894838948489485894868948789488894898949089491894928949389494894958949689497894988949989500895018950289503895048950589506895078950889509895108951189512895138951489515895168951789518895198952089521895228952389524895258952689527895288952989530895318953289533895348953589536895378953889539895408954189542895438954489545895468954789548895498955089551895528955389554895558955689557895588955989560895618956289563895648956589566895678956889569895708957189572895738957489575895768957789578895798958089581895828958389584895858958689587895888958989590895918959289593895948959589596895978959889599896008960189602896038960489605896068960789608896098961089611896128961389614896158961689617896188961989620896218962289623896248962589626896278962889629896308963189632896338963489635896368963789638896398964089641896428964389644896458964689647896488964989650896518965289653896548965589656896578965889659896608966189662896638966489665896668966789668896698967089671896728967389674896758967689677896788967989680896818968289683896848968589686896878968889689896908969189692896938969489695896968969789698896998970089701897028970389704897058970689707897088970989710897118971289713897148971589716897178971889719897208972189722897238972489725897268972789728897298973089731897328973389734897358973689737897388973989740897418974289743897448974589746897478974889749897508975189752897538975489755897568975789758897598976089761897628976389764897658976689767897688976989770897718977289773897748977589776897778977889779897808978189782897838978489785897868978789788897898979089791897928979389794897958979689797897988979989800898018980289803898048980589806898078980889809898108981189812898138981489815898168981789818898198982089821898228982389824898258982689827898288982989830898318983289833898348983589836898378983889839898408984189842898438984489845898468984789848898498985089851898528985389854898558985689857898588985989860898618986289863898648986589866898678986889869898708987189872898738987489875898768987789878898798988089881898828988389884898858988689887898888988989890898918989289893898948989589896898978989889899899008990189902899038990489905899068990789908899098991089911899128991389914899158991689917899188991989920899218992289923899248992589926899278992889929899308993189932899338993489935899368993789938899398994089941899428994389944899458994689947899488994989950899518995289953899548995589956899578995889959899608996189962899638996489965899668996789968899698997089971899728997389974899758997689977899788997989980899818998289983899848998589986899878998889989899908999189992899938999489995899968999789998899999000090001900029000390004900059000690007900089000990010900119001290013900149001590016900179001890019900209002190022900239002490025900269002790028900299003090031900329003390034900359003690037900389003990040900419004290043900449004590046900479004890049900509005190052900539005490055900569005790058900599006090061900629006390064900659006690067900689006990070900719007290073900749007590076900779007890079900809008190082900839008490085900869008790088900899009090091900929009390094900959009690097900989009990100901019010290103901049010590106901079010890109901109011190112901139011490115901169011790118901199012090121901229012390124901259012690127901289012990130901319013290133901349013590136901379013890139901409014190142901439014490145901469014790148901499015090151901529015390154901559015690157901589015990160901619016290163901649016590166901679016890169901709017190172901739017490175901769017790178901799018090181901829018390184901859018690187901889018990190901919019290193901949019590196901979019890199902009020190202902039020490205902069020790208902099021090211902129021390214902159021690217902189021990220902219022290223902249022590226902279022890229902309023190232902339023490235902369023790238902399024090241902429024390244902459024690247902489024990250902519025290253902549025590256902579025890259902609026190262902639026490265902669026790268902699027090271902729027390274902759027690277902789027990280902819028290283902849028590286902879028890289902909029190292902939029490295902969029790298902999030090301903029030390304903059030690307903089030990310903119031290313903149031590316903179031890319903209032190322903239032490325903269032790328903299033090331903329033390334903359033690337903389033990340903419034290343903449034590346903479034890349903509035190352903539035490355903569035790358903599036090361903629036390364903659036690367903689036990370903719037290373903749037590376903779037890379903809038190382903839038490385903869038790388903899039090391903929039390394903959039690397903989039990400904019040290403904049040590406904079040890409904109041190412904139041490415904169041790418904199042090421904229042390424904259042690427904289042990430904319043290433904349043590436904379043890439904409044190442904439044490445904469044790448904499045090451904529045390454904559045690457904589045990460904619046290463904649046590466904679046890469904709047190472904739047490475904769047790478904799048090481904829048390484904859048690487904889048990490904919049290493904949049590496904979049890499905009050190502905039050490505905069050790508905099051090511905129051390514905159051690517905189051990520905219052290523905249052590526905279052890529905309053190532905339053490535905369053790538905399054090541905429054390544905459054690547905489054990550905519055290553905549055590556905579055890559905609056190562905639056490565905669056790568905699057090571905729057390574905759057690577905789057990580905819058290583905849058590586905879058890589905909059190592905939059490595905969059790598905999060090601906029060390604906059060690607906089060990610906119061290613906149061590616906179061890619906209062190622906239062490625906269062790628906299063090631906329063390634906359063690637906389063990640906419064290643906449064590646906479064890649906509065190652906539065490655906569065790658906599066090661906629066390664906659066690667906689066990670906719067290673906749067590676906779067890679906809068190682906839068490685906869068790688906899069090691906929069390694906959069690697906989069990700907019070290703907049070590706907079070890709907109071190712907139071490715907169071790718907199072090721907229072390724907259072690727907289072990730907319073290733907349073590736907379073890739907409074190742907439074490745907469074790748907499075090751907529075390754907559075690757907589075990760907619076290763907649076590766907679076890769907709077190772907739077490775907769077790778907799078090781907829078390784907859078690787907889078990790907919079290793907949079590796907979079890799908009080190802908039080490805908069080790808908099081090811908129081390814908159081690817908189081990820908219082290823908249082590826908279082890829908309083190832908339083490835908369083790838908399084090841908429084390844908459084690847908489084990850908519085290853908549085590856908579085890859908609086190862908639086490865908669086790868908699087090871908729087390874908759087690877908789087990880908819088290883908849088590886908879088890889908909089190892908939089490895908969089790898908999090090901909029090390904909059090690907909089090990910909119091290913909149091590916909179091890919909209092190922909239092490925909269092790928909299093090931909329093390934909359093690937909389093990940909419094290943909449094590946909479094890949909509095190952909539095490955909569095790958909599096090961909629096390964909659096690967909689096990970909719097290973909749097590976909779097890979909809098190982909839098490985909869098790988909899099090991909929099390994909959099690997909989099991000910019100291003910049100591006910079100891009910109101191012910139101491015910169101791018910199102091021910229102391024910259102691027910289102991030910319103291033910349103591036910379103891039910409104191042910439104491045910469104791048910499105091051910529105391054910559105691057910589105991060910619106291063910649106591066910679106891069910709107191072910739107491075910769107791078910799108091081910829108391084910859108691087910889108991090910919109291093910949109591096910979109891099911009110191102911039110491105911069110791108911099111091111911129111391114911159111691117911189111991120911219112291123911249112591126911279112891129911309113191132911339113491135911369113791138911399114091141911429114391144911459114691147911489114991150911519115291153911549115591156911579115891159911609116191162911639116491165911669116791168911699117091171911729117391174911759117691177911789117991180911819118291183911849118591186911879118891189911909119191192911939119491195911969119791198911999120091201912029120391204912059120691207912089120991210912119121291213912149121591216912179121891219912209122191222912239122491225912269122791228912299123091231912329123391234912359123691237912389123991240912419124291243912449124591246912479124891249912509125191252912539125491255912569125791258912599126091261912629126391264912659126691267912689126991270912719127291273912749127591276912779127891279912809128191282912839128491285912869128791288912899129091291912929129391294912959129691297912989129991300913019130291303913049130591306913079130891309913109131191312913139131491315913169131791318913199132091321913229132391324913259132691327913289132991330913319133291333913349133591336913379133891339913409134191342913439134491345913469134791348913499135091351913529135391354913559135691357913589135991360913619136291363913649136591366913679136891369913709137191372913739137491375913769137791378913799138091381913829138391384913859138691387913889138991390913919139291393913949139591396913979139891399914009140191402914039140491405914069140791408914099141091411914129141391414914159141691417914189141991420914219142291423914249142591426914279142891429914309143191432914339143491435914369143791438914399144091441914429144391444914459144691447914489144991450914519145291453914549145591456914579145891459914609146191462914639146491465914669146791468914699147091471914729147391474914759147691477914789147991480914819148291483914849148591486914879148891489914909149191492914939149491495914969149791498914999150091501915029150391504915059150691507915089150991510915119151291513915149151591516915179151891519915209152191522915239152491525915269152791528915299153091531915329153391534915359153691537915389153991540915419154291543915449154591546915479154891549915509155191552915539155491555915569155791558915599156091561915629156391564915659156691567915689156991570915719157291573915749157591576915779157891579915809158191582915839158491585915869158791588915899159091591915929159391594915959159691597915989159991600916019160291603916049160591606916079160891609916109161191612916139161491615916169161791618916199162091621916229162391624916259162691627916289162991630916319163291633916349163591636916379163891639916409164191642916439164491645916469164791648916499165091651916529165391654916559165691657916589165991660916619166291663916649166591666916679166891669916709167191672916739167491675916769167791678916799168091681916829168391684916859168691687916889168991690916919169291693916949169591696916979169891699917009170191702917039170491705917069170791708917099171091711917129171391714917159171691717917189171991720917219172291723917249172591726917279172891729917309173191732917339173491735917369173791738917399174091741917429174391744917459174691747917489174991750917519175291753917549175591756917579175891759917609176191762917639176491765917669176791768917699177091771917729177391774917759177691777917789177991780917819178291783917849178591786917879178891789917909179191792917939179491795917969179791798917999180091801918029180391804918059180691807918089180991810918119181291813918149181591816918179181891819918209182191822918239182491825918269182791828918299183091831918329183391834918359183691837918389183991840918419184291843918449184591846918479184891849918509185191852918539185491855918569185791858918599186091861918629186391864918659186691867918689186991870918719187291873918749187591876918779187891879918809188191882918839188491885918869188791888918899189091891918929189391894918959189691897918989189991900919019190291903919049190591906919079190891909919109191191912919139191491915919169191791918919199192091921919229192391924919259192691927919289192991930919319193291933919349193591936919379193891939919409194191942919439194491945919469194791948919499195091951919529195391954919559195691957919589195991960919619196291963919649196591966919679196891969919709197191972919739197491975919769197791978919799198091981919829198391984919859198691987919889198991990919919199291993919949199591996919979199891999920009200192002920039200492005920069200792008920099201092011920129201392014920159201692017920189201992020920219202292023920249202592026920279202892029920309203192032920339203492035920369203792038920399204092041920429204392044920459204692047920489204992050920519205292053920549205592056920579205892059920609206192062920639206492065920669206792068920699207092071920729207392074920759207692077920789207992080920819208292083920849208592086920879208892089920909209192092920939209492095920969209792098920999210092101921029210392104921059210692107921089210992110921119211292113921149211592116921179211892119921209212192122921239212492125921269212792128921299213092131921329213392134921359213692137921389213992140921419214292143921449214592146921479214892149921509215192152921539215492155921569215792158921599216092161921629216392164921659216692167921689216992170921719217292173921749217592176921779217892179921809218192182921839218492185921869218792188921899219092191921929219392194921959219692197921989219992200922019220292203922049220592206922079220892209922109221192212922139221492215922169221792218922199222092221922229222392224922259222692227922289222992230922319223292233922349223592236922379223892239922409224192242922439224492245922469224792248922499225092251922529225392254922559225692257922589225992260922619226292263922649226592266922679226892269922709227192272922739227492275922769227792278922799228092281922829228392284922859228692287922889228992290922919229292293922949229592296922979229892299923009230192302923039230492305923069230792308923099231092311923129231392314923159231692317923189231992320923219232292323923249232592326923279232892329923309233192332923339233492335923369233792338923399234092341923429234392344923459234692347923489234992350923519235292353923549235592356923579235892359923609236192362923639236492365923669236792368923699237092371923729237392374923759237692377923789237992380923819238292383923849238592386923879238892389923909239192392923939239492395923969239792398923999240092401924029240392404924059240692407924089240992410924119241292413924149241592416924179241892419924209242192422924239242492425924269242792428924299243092431924329243392434924359243692437924389243992440924419244292443924449244592446924479244892449924509245192452924539245492455924569245792458924599246092461924629246392464924659246692467924689246992470924719247292473924749247592476924779247892479924809248192482924839248492485924869248792488924899249092491924929249392494924959249692497924989249992500925019250292503925049250592506925079250892509925109251192512925139251492515925169251792518925199252092521925229252392524925259252692527925289252992530925319253292533925349253592536925379253892539925409254192542925439254492545925469254792548925499255092551925529255392554925559255692557925589255992560925619256292563925649256592566925679256892569925709257192572925739257492575925769257792578925799258092581925829258392584925859258692587925889258992590925919259292593925949259592596925979259892599926009260192602926039260492605926069260792608926099261092611926129261392614926159261692617926189261992620926219262292623926249262592626926279262892629926309263192632926339263492635926369263792638926399264092641926429264392644926459264692647926489264992650926519265292653926549265592656926579265892659926609266192662926639266492665926669266792668926699267092671926729267392674926759267692677926789267992680926819268292683926849268592686926879268892689926909269192692926939269492695926969269792698926999270092701927029270392704927059270692707927089270992710927119271292713927149271592716927179271892719927209272192722927239272492725927269272792728927299273092731927329273392734927359273692737927389273992740927419274292743927449274592746927479274892749927509275192752927539275492755927569275792758927599276092761927629276392764927659276692767927689276992770927719277292773927749277592776927779277892779927809278192782927839278492785927869278792788927899279092791927929279392794927959279692797927989279992800928019280292803928049280592806928079280892809928109281192812928139281492815928169281792818928199282092821928229282392824928259282692827928289282992830928319283292833928349283592836928379283892839928409284192842928439284492845928469284792848928499285092851928529285392854928559285692857928589285992860928619286292863928649286592866928679286892869928709287192872928739287492875928769287792878928799288092881928829288392884928859288692887928889288992890928919289292893928949289592896928979289892899929009290192902929039290492905929069290792908929099291092911929129291392914929159291692917929189291992920929219292292923929249292592926929279292892929929309293192932929339293492935929369293792938929399294092941929429294392944929459294692947929489294992950929519295292953929549295592956929579295892959929609296192962929639296492965929669296792968929699297092971929729297392974929759297692977929789297992980929819298292983929849298592986929879298892989929909299192992929939299492995929969299792998929999300093001930029300393004930059300693007930089300993010930119301293013930149301593016930179301893019930209302193022930239302493025930269302793028930299303093031930329303393034930359303693037930389303993040930419304293043930449304593046930479304893049930509305193052930539305493055930569305793058930599306093061930629306393064930659306693067930689306993070930719307293073930749307593076930779307893079930809308193082930839308493085930869308793088930899309093091930929309393094930959309693097930989309993100931019310293103931049310593106931079310893109931109311193112931139311493115931169311793118931199312093121931229312393124931259312693127931289312993130931319313293133931349313593136931379313893139931409314193142931439314493145931469314793148931499315093151931529315393154931559315693157931589315993160931619316293163931649316593166931679316893169931709317193172931739317493175931769317793178931799318093181931829318393184931859318693187931889318993190931919319293193931949319593196931979319893199932009320193202932039320493205932069320793208932099321093211932129321393214932159321693217932189321993220932219322293223932249322593226932279322893229932309323193232932339323493235932369323793238932399324093241932429324393244932459324693247932489324993250932519325293253932549325593256932579325893259932609326193262932639326493265932669326793268932699327093271932729327393274932759327693277932789327993280932819328293283932849328593286932879328893289932909329193292932939329493295932969329793298932999330093301933029330393304933059330693307933089330993310933119331293313933149331593316933179331893319933209332193322933239332493325933269332793328933299333093331933329333393334933359333693337933389333993340933419334293343933449334593346933479334893349933509335193352933539335493355933569335793358933599336093361933629336393364933659336693367933689336993370933719337293373933749337593376933779337893379933809338193382933839338493385933869338793388933899339093391933929339393394933959339693397933989339993400934019340293403934049340593406934079340893409934109341193412934139341493415934169341793418934199342093421934229342393424934259342693427934289342993430934319343293433934349343593436934379343893439934409344193442934439344493445934469344793448934499345093451934529345393454934559345693457934589345993460934619346293463934649346593466934679346893469934709347193472934739347493475934769347793478934799348093481934829348393484934859348693487934889348993490934919349293493934949349593496934979349893499935009350193502935039350493505935069350793508935099351093511935129351393514935159351693517935189351993520935219352293523935249352593526935279352893529935309353193532935339353493535935369353793538935399354093541935429354393544935459354693547935489354993550935519355293553935549355593556935579355893559935609356193562935639356493565935669356793568935699357093571935729357393574935759357693577935789357993580935819358293583935849358593586935879358893589935909359193592935939359493595935969359793598935999360093601936029360393604936059360693607936089360993610936119361293613936149361593616936179361893619936209362193622936239362493625936269362793628936299363093631936329363393634936359363693637936389363993640936419364293643936449364593646936479364893649936509365193652936539365493655936569365793658936599366093661936629366393664936659366693667936689366993670936719367293673936749367593676936779367893679936809368193682936839368493685936869368793688936899369093691936929369393694936959369693697936989369993700937019370293703937049370593706937079370893709937109371193712937139371493715937169371793718937199372093721937229372393724937259372693727937289372993730937319373293733937349373593736937379373893739937409374193742937439374493745937469374793748937499375093751937529375393754937559375693757937589375993760937619376293763937649376593766937679376893769937709377193772937739377493775937769377793778937799378093781937829378393784937859378693787937889378993790937919379293793937949379593796937979379893799938009380193802938039380493805938069380793808938099381093811938129381393814938159381693817938189381993820938219382293823938249382593826938279382893829938309383193832938339383493835938369383793838938399384093841938429384393844938459384693847938489384993850938519385293853938549385593856938579385893859938609386193862938639386493865938669386793868938699387093871938729387393874938759387693877938789387993880938819388293883938849388593886938879388893889938909389193892938939389493895938969389793898938999390093901939029390393904939059390693907939089390993910939119391293913939149391593916939179391893919939209392193922939239392493925939269392793928939299393093931939329393393934939359393693937939389393993940939419394293943939449394593946939479394893949939509395193952939539395493955939569395793958939599396093961939629396393964939659396693967939689396993970939719397293973939749397593976939779397893979939809398193982939839398493985939869398793988939899399093991939929399393994939959399693997939989399994000940019400294003940049400594006940079400894009940109401194012940139401494015940169401794018940199402094021940229402394024940259402694027940289402994030940319403294033940349403594036940379403894039940409404194042940439404494045940469404794048940499405094051940529405394054940559405694057940589405994060940619406294063940649406594066940679406894069940709407194072940739407494075940769407794078940799408094081940829408394084940859408694087940889408994090940919409294093940949409594096940979409894099941009410194102941039410494105941069410794108941099411094111941129411394114941159411694117941189411994120941219412294123941249412594126941279412894129941309413194132941339413494135941369413794138941399414094141941429414394144941459414694147941489414994150941519415294153941549415594156941579415894159941609416194162941639416494165941669416794168941699417094171941729417394174941759417694177941789417994180941819418294183941849418594186941879418894189941909419194192941939419494195941969419794198941999420094201942029420394204942059420694207942089420994210942119421294213942149421594216942179421894219942209422194222942239422494225942269422794228942299423094231942329423394234942359423694237942389423994240942419424294243942449424594246942479424894249942509425194252942539425494255942569425794258942599426094261942629426394264942659426694267942689426994270942719427294273942749427594276942779427894279942809428194282942839428494285942869428794288942899429094291942929429394294942959429694297942989429994300943019430294303943049430594306943079430894309943109431194312943139431494315943169431794318943199432094321943229432394324943259432694327943289432994330943319433294333943349433594336943379433894339943409434194342943439434494345943469434794348943499435094351943529435394354943559435694357943589435994360943619436294363943649436594366943679436894369943709437194372943739437494375943769437794378943799438094381943829438394384943859438694387943889438994390943919439294393943949439594396943979439894399944009440194402944039440494405944069440794408944099441094411944129441394414944159441694417944189441994420944219442294423944249442594426944279442894429944309443194432944339443494435944369443794438944399444094441944429444394444944459444694447944489444994450944519445294453944549445594456944579445894459944609446194462944639446494465944669446794468944699447094471944729447394474944759447694477944789447994480944819448294483944849448594486944879448894489944909449194492944939449494495944969449794498944999450094501945029450394504945059450694507945089450994510945119451294513945149451594516945179451894519945209452194522945239452494525945269452794528945299453094531945329453394534945359453694537945389453994540945419454294543945449454594546945479454894549945509455194552945539455494555945569455794558945599456094561945629456394564945659456694567945689456994570945719457294573945749457594576945779457894579945809458194582945839458494585945869458794588945899459094591945929459394594945959459694597945989459994600946019460294603946049460594606946079460894609946109461194612946139461494615946169461794618946199462094621946229462394624946259462694627946289462994630946319463294633946349463594636946379463894639946409464194642946439464494645946469464794648946499465094651946529465394654946559465694657946589465994660946619466294663946649466594666946679466894669946709467194672946739467494675946769467794678946799468094681946829468394684946859468694687946889468994690946919469294693946949469594696946979469894699947009470194702947039470494705947069470794708947099471094711947129471394714947159471694717947189471994720947219472294723947249472594726947279472894729947309473194732947339473494735947369473794738947399474094741947429474394744947459474694747947489474994750947519475294753947549475594756947579475894759947609476194762947639476494765947669476794768947699477094771947729477394774947759477694777947789477994780947819478294783947849478594786947879478894789947909479194792947939479494795947969479794798947999480094801948029480394804948059480694807948089480994810948119481294813948149481594816948179481894819948209482194822948239482494825948269482794828948299483094831948329483394834948359483694837948389483994840948419484294843948449484594846948479484894849948509485194852948539485494855948569485794858948599486094861948629486394864948659486694867948689486994870948719487294873948749487594876948779487894879948809488194882948839488494885948869488794888948899489094891948929489394894948959489694897948989489994900949019490294903949049490594906949079490894909949109491194912949139491494915949169491794918949199492094921949229492394924949259492694927949289492994930949319493294933949349493594936949379493894939949409494194942949439494494945949469494794948949499495094951949529495394954949559495694957949589495994960949619496294963949649496594966949679496894969949709497194972949739497494975949769497794978949799498094981949829498394984949859498694987949889498994990949919499294993949949499594996949979499894999950009500195002950039500495005950069500795008950099501095011950129501395014950159501695017950189501995020950219502295023950249502595026950279502895029950309503195032950339503495035950369503795038950399504095041950429504395044950459504695047950489504995050950519505295053950549505595056950579505895059950609506195062950639506495065950669506795068950699507095071950729507395074950759507695077950789507995080950819508295083950849508595086950879508895089950909509195092950939509495095950969509795098950999510095101951029510395104951059510695107951089510995110951119511295113951149511595116951179511895119951209512195122951239512495125951269512795128951299513095131951329513395134951359513695137951389513995140951419514295143951449514595146951479514895149951509515195152951539515495155951569515795158951599516095161951629516395164951659516695167951689516995170951719517295173951749517595176951779517895179951809518195182951839518495185951869518795188951899519095191951929519395194951959519695197951989519995200952019520295203952049520595206952079520895209952109521195212952139521495215952169521795218952199522095221952229522395224952259522695227952289522995230952319523295233952349523595236952379523895239952409524195242952439524495245952469524795248952499525095251952529525395254952559525695257952589525995260952619526295263952649526595266952679526895269952709527195272952739527495275952769527795278952799528095281952829528395284952859528695287952889528995290952919529295293952949529595296952979529895299953009530195302953039530495305953069530795308953099531095311953129531395314953159531695317953189531995320953219532295323953249532595326953279532895329953309533195332953339533495335953369533795338953399534095341953429534395344953459534695347953489534995350953519535295353953549535595356953579535895359953609536195362953639536495365953669536795368953699537095371953729537395374953759537695377953789537995380953819538295383953849538595386953879538895389953909539195392953939539495395953969539795398953999540095401954029540395404954059540695407954089540995410954119541295413954149541595416954179541895419954209542195422954239542495425954269542795428954299543095431954329543395434954359543695437954389543995440954419544295443954449544595446954479544895449954509545195452954539545495455954569545795458954599546095461954629546395464954659546695467954689546995470954719547295473954749547595476954779547895479954809548195482954839548495485954869548795488954899549095491954929549395494954959549695497954989549995500955019550295503955049550595506955079550895509955109551195512955139551495515955169551795518955199552095521955229552395524955259552695527955289552995530955319553295533955349553595536955379553895539955409554195542955439554495545955469554795548955499555095551955529555395554955559555695557955589555995560955619556295563955649556595566955679556895569955709557195572955739557495575955769557795578955799558095581955829558395584955859558695587955889558995590955919559295593955949559595596955979559895599956009560195602956039560495605956069560795608956099561095611956129561395614956159561695617956189561995620956219562295623956249562595626956279562895629956309563195632956339563495635956369563795638956399564095641956429564395644956459564695647956489564995650956519565295653956549565595656956579565895659956609566195662956639566495665956669566795668956699567095671956729567395674956759567695677956789567995680956819568295683956849568595686956879568895689956909569195692956939569495695956969569795698956999570095701957029570395704957059570695707957089570995710957119571295713957149571595716957179571895719957209572195722957239572495725957269572795728957299573095731957329573395734957359573695737957389573995740957419574295743957449574595746957479574895749957509575195752957539575495755957569575795758957599576095761957629576395764957659576695767957689576995770957719577295773957749577595776957779577895779957809578195782957839578495785957869578795788957899579095791957929579395794957959579695797957989579995800958019580295803958049580595806958079580895809958109581195812958139581495815958169581795818958199582095821958229582395824958259582695827958289582995830958319583295833958349583595836958379583895839958409584195842958439584495845958469584795848958499585095851958529585395854958559585695857958589585995860958619586295863958649586595866958679586895869958709587195872958739587495875958769587795878958799588095881958829588395884958859588695887958889588995890958919589295893958949589595896958979589895899959009590195902959039590495905959069590795908959099591095911959129591395914959159591695917959189591995920959219592295923959249592595926959279592895929959309593195932959339593495935959369593795938959399594095941959429594395944959459594695947959489594995950959519595295953959549595595956959579595895959959609596195962959639596495965959669596795968959699597095971959729597395974959759597695977959789597995980959819598295983959849598595986959879598895989959909599195992959939599495995959969599795998959999600096001960029600396004960059600696007960089600996010960119601296013960149601596016960179601896019960209602196022960239602496025960269602796028960299603096031960329603396034960359603696037960389603996040960419604296043960449604596046960479604896049960509605196052960539605496055960569605796058960599606096061960629606396064960659606696067960689606996070960719607296073960749607596076960779607896079960809608196082960839608496085960869608796088960899609096091960929609396094960959609696097960989609996100961019610296103961049610596106961079610896109961109611196112961139611496115961169611796118961199612096121961229612396124961259612696127961289612996130961319613296133961349613596136961379613896139961409614196142961439614496145961469614796148961499615096151961529615396154961559615696157961589615996160961619616296163961649616596166961679616896169961709617196172961739617496175961769617796178961799618096181961829618396184961859618696187961889618996190961919619296193961949619596196961979619896199962009620196202962039620496205962069620796208962099621096211962129621396214962159621696217962189621996220962219622296223962249622596226962279622896229962309623196232962339623496235962369623796238962399624096241962429624396244962459624696247962489624996250962519625296253962549625596256962579625896259962609626196262962639626496265962669626796268962699627096271962729627396274962759627696277962789627996280962819628296283962849628596286962879628896289962909629196292962939629496295962969629796298962999630096301963029630396304963059630696307963089630996310963119631296313963149631596316963179631896319963209632196322963239632496325963269632796328963299633096331963329633396334963359633696337963389633996340963419634296343963449634596346963479634896349963509635196352963539635496355963569635796358963599636096361963629636396364963659636696367963689636996370963719637296373963749637596376963779637896379963809638196382963839638496385963869638796388963899639096391963929639396394963959639696397963989639996400964019640296403964049640596406964079640896409964109641196412964139641496415964169641796418964199642096421964229642396424964259642696427964289642996430964319643296433964349643596436964379643896439964409644196442964439644496445964469644796448964499645096451964529645396454964559645696457964589645996460964619646296463964649646596466964679646896469964709647196472964739647496475964769647796478964799648096481964829648396484964859648696487964889648996490964919649296493964949649596496964979649896499965009650196502965039650496505965069650796508965099651096511965129651396514965159651696517965189651996520965219652296523965249652596526965279652896529965309653196532965339653496535965369653796538965399654096541965429654396544965459654696547965489654996550965519655296553965549655596556965579655896559965609656196562965639656496565965669656796568965699657096571965729657396574965759657696577965789657996580965819658296583965849658596586965879658896589965909659196592965939659496595965969659796598965999660096601966029660396604966059660696607966089660996610966119661296613966149661596616966179661896619966209662196622966239662496625966269662796628966299663096631966329663396634966359663696637966389663996640966419664296643966449664596646966479664896649966509665196652966539665496655966569665796658966599666096661966629666396664966659666696667966689666996670966719667296673966749667596676966779667896679966809668196682966839668496685966869668796688966899669096691966929669396694966959669696697966989669996700967019670296703967049670596706967079670896709967109671196712967139671496715967169671796718967199672096721967229672396724967259672696727967289672996730967319673296733967349673596736967379673896739967409674196742967439674496745967469674796748967499675096751967529675396754967559675696757967589675996760967619676296763967649676596766967679676896769967709677196772967739677496775967769677796778967799678096781967829678396784967859678696787967889678996790967919679296793967949679596796967979679896799968009680196802968039680496805968069680796808968099681096811968129681396814968159681696817968189681996820968219682296823968249682596826968279682896829968309683196832968339683496835968369683796838968399684096841968429684396844968459684696847968489684996850968519685296853968549685596856968579685896859968609686196862968639686496865968669686796868968699687096871968729687396874968759687696877968789687996880968819688296883968849688596886968879688896889968909689196892968939689496895968969689796898968999690096901969029690396904969059690696907969089690996910969119691296913969149691596916969179691896919969209692196922969239692496925969269692796928969299693096931969329693396934969359693696937969389693996940969419694296943969449694596946969479694896949969509695196952969539695496955969569695796958969599696096961969629696396964969659696696967969689696996970969719697296973969749697596976969779697896979969809698196982969839698496985969869698796988969899699096991969929699396994969959699696997969989699997000970019700297003970049700597006970079700897009970109701197012970139701497015970169701797018970199702097021970229702397024970259702697027970289702997030970319703297033970349703597036970379703897039970409704197042970439704497045970469704797048970499705097051970529705397054970559705697057970589705997060970619706297063970649706597066970679706897069970709707197072970739707497075970769707797078970799708097081970829708397084970859708697087970889708997090970919709297093970949709597096970979709897099971009710197102971039710497105971069710797108971099711097111971129711397114971159711697117971189711997120971219712297123971249712597126971279712897129971309713197132971339713497135971369713797138971399714097141971429714397144971459714697147971489714997150971519715297153971549715597156971579715897159971609716197162971639716497165971669716797168971699717097171971729717397174971759717697177971789717997180971819718297183971849718597186971879718897189971909719197192971939719497195971969719797198971999720097201972029720397204972059720697207972089720997210972119721297213972149721597216972179721897219972209722197222972239722497225972269722797228972299723097231972329723397234972359723697237972389723997240972419724297243972449724597246972479724897249972509725197252972539725497255972569725797258972599726097261972629726397264972659726697267972689726997270972719727297273972749727597276972779727897279972809728197282972839728497285972869728797288972899729097291972929729397294972959729697297972989729997300973019730297303973049730597306973079730897309973109731197312973139731497315973169731797318973199732097321973229732397324973259732697327973289732997330973319733297333973349733597336973379733897339973409734197342973439734497345973469734797348973499735097351973529735397354973559735697357973589735997360973619736297363973649736597366973679736897369973709737197372973739737497375973769737797378973799738097381973829738397384973859738697387973889738997390973919739297393973949739597396973979739897399974009740197402974039740497405974069740797408974099741097411974129741397414974159741697417974189741997420974219742297423974249742597426974279742897429974309743197432974339743497435974369743797438974399744097441974429744397444974459744697447974489744997450974519745297453974549745597456974579745897459974609746197462974639746497465974669746797468974699747097471974729747397474974759747697477974789747997480974819748297483974849748597486974879748897489974909749197492974939749497495974969749797498974999750097501975029750397504975059750697507975089750997510975119751297513975149751597516975179751897519975209752197522975239752497525975269752797528975299753097531975329753397534975359753697537975389753997540975419754297543975449754597546975479754897549975509755197552975539755497555975569755797558975599756097561975629756397564975659756697567975689756997570975719757297573975749757597576975779757897579975809758197582975839758497585975869758797588975899759097591975929759397594975959759697597975989759997600976019760297603976049760597606976079760897609976109761197612976139761497615976169761797618976199762097621976229762397624976259762697627976289762997630976319763297633976349763597636976379763897639976409764197642976439764497645976469764797648976499765097651976529765397654976559765697657976589765997660976619766297663976649766597666976679766897669976709767197672976739767497675976769767797678976799768097681976829768397684976859768697687976889768997690976919769297693976949769597696976979769897699977009770197702977039770497705977069770797708977099771097711977129771397714977159771697717977189771997720977219772297723977249772597726977279772897729977309773197732977339773497735977369773797738977399774097741977429774397744977459774697747977489774997750977519775297753977549775597756977579775897759977609776197762977639776497765977669776797768977699777097771977729777397774977759777697777977789777997780977819778297783977849778597786977879778897789977909779197792977939779497795977969779797798977999780097801978029780397804978059780697807978089780997810978119781297813978149781597816978179781897819978209782197822978239782497825978269782797828978299783097831978329783397834978359783697837978389783997840978419784297843978449784597846978479784897849978509785197852978539785497855978569785797858978599786097861978629786397864978659786697867978689786997870978719787297873978749787597876978779787897879978809788197882978839788497885978869788797888978899789097891978929789397894978959789697897978989789997900979019790297903979049790597906979079790897909979109791197912979139791497915979169791797918979199792097921979229792397924979259792697927979289792997930979319793297933979349793597936979379793897939979409794197942979439794497945979469794797948979499795097951979529795397954979559795697957979589795997960979619796297963979649796597966979679796897969979709797197972979739797497975979769797797978979799798097981979829798397984979859798697987979889798997990979919799297993979949799597996979979799897999980009800198002980039800498005980069800798008980099801098011980129801398014980159801698017980189801998020980219802298023980249802598026980279802898029980309803198032980339803498035980369803798038980399804098041980429804398044980459804698047980489804998050980519805298053980549805598056980579805898059980609806198062980639806498065980669806798068980699807098071980729807398074980759807698077980789807998080980819808298083980849808598086980879808898089980909809198092980939809498095980969809798098980999810098101981029810398104981059810698107981089810998110981119811298113981149811598116981179811898119981209812198122981239812498125981269812798128981299813098131981329813398134981359813698137981389813998140981419814298143981449814598146981479814898149981509815198152981539815498155981569815798158981599816098161981629816398164981659816698167981689816998170981719817298173981749817598176981779817898179981809818198182981839818498185981869818798188981899819098191981929819398194981959819698197981989819998200982019820298203982049820598206982079820898209982109821198212982139821498215982169821798218982199822098221982229822398224982259822698227982289822998230982319823298233982349823598236982379823898239982409824198242982439824498245982469824798248982499825098251982529825398254982559825698257982589825998260982619826298263982649826598266982679826898269982709827198272982739827498275982769827798278982799828098281982829828398284982859828698287982889828998290982919829298293982949829598296982979829898299983009830198302983039830498305983069830798308983099831098311983129831398314983159831698317983189831998320983219832298323983249832598326983279832898329983309833198332983339833498335983369833798338983399834098341983429834398344983459834698347983489834998350983519835298353983549835598356983579835898359983609836198362983639836498365983669836798368983699837098371983729837398374983759837698377983789837998380983819838298383983849838598386983879838898389983909839198392983939839498395983969839798398983999840098401984029840398404984059840698407984089840998410984119841298413984149841598416984179841898419984209842198422984239842498425984269842798428984299843098431984329843398434984359843698437984389843998440984419844298443984449844598446984479844898449984509845198452984539845498455984569845798458984599846098461984629846398464984659846698467984689846998470984719847298473984749847598476984779847898479984809848198482984839848498485984869848798488984899849098491984929849398494984959849698497984989849998500985019850298503985049850598506985079850898509985109851198512985139851498515985169851798518985199852098521985229852398524985259852698527985289852998530985319853298533985349853598536985379853898539985409854198542985439854498545985469854798548985499855098551985529855398554985559855698557985589855998560985619856298563985649856598566985679856898569985709857198572985739857498575985769857798578985799858098581985829858398584985859858698587985889858998590985919859298593985949859598596985979859898599986009860198602986039860498605986069860798608986099861098611986129861398614986159861698617986189861998620986219862298623986249862598626986279862898629986309863198632986339863498635986369863798638986399864098641986429864398644986459864698647986489864998650986519865298653986549865598656986579865898659986609866198662986639866498665986669866798668986699867098671986729867398674986759867698677986789867998680986819868298683986849868598686986879868898689986909869198692986939869498695986969869798698986999870098701987029870398704987059870698707987089870998710987119871298713987149871598716987179871898719987209872198722987239872498725987269872798728987299873098731987329873398734987359873698737987389873998740987419874298743987449874598746987479874898749987509875198752987539875498755987569875798758987599876098761987629876398764987659876698767987689876998770987719877298773987749877598776987779877898779987809878198782987839878498785987869878798788987899879098791987929879398794987959879698797987989879998800988019880298803988049880598806988079880898809988109881198812988139881498815988169881798818988199882098821988229882398824988259882698827988289882998830988319883298833988349883598836988379883898839988409884198842988439884498845988469884798848988499885098851988529885398854988559885698857988589885998860988619886298863988649886598866988679886898869988709887198872988739887498875988769887798878988799888098881988829888398884988859888698887988889888998890988919889298893988949889598896988979889898899989009890198902989039890498905989069890798908989099891098911989129891398914989159891698917989189891998920989219892298923989249892598926989279892898929989309893198932989339893498935989369893798938989399894098941989429894398944989459894698947989489894998950989519895298953989549895598956989579895898959989609896198962989639896498965989669896798968989699897098971989729897398974989759897698977989789897998980989819898298983989849898598986989879898898989989909899198992989939899498995989969899798998989999900099001990029900399004990059900699007990089900999010990119901299013990149901599016990179901899019990209902199022990239902499025990269902799028990299903099031990329903399034990359903699037990389903999040990419904299043990449904599046990479904899049990509905199052990539905499055990569905799058990599906099061990629906399064990659906699067990689906999070990719907299073990749907599076990779907899079990809908199082990839908499085990869908799088990899909099091990929909399094990959909699097990989909999100991019910299103991049910599106991079910899109991109911199112991139911499115991169911799118991199912099121991229912399124991259912699127991289912999130991319913299133991349913599136991379913899139991409914199142991439914499145991469914799148991499915099151991529915399154991559915699157991589915999160991619916299163991649916599166991679916899169991709917199172991739917499175991769917799178991799918099181991829918399184991859918699187991889918999190991919919299193991949919599196991979919899199992009920199202992039920499205992069920799208992099921099211992129921399214992159921699217992189921999220992219922299223992249922599226992279922899229992309923199232992339923499235992369923799238992399924099241992429924399244992459924699247992489924999250992519925299253992549925599256992579925899259992609926199262992639926499265992669926799268992699927099271992729927399274992759927699277992789927999280992819928299283992849928599286992879928899289992909929199292992939929499295992969929799298992999930099301993029930399304993059930699307993089930999310993119931299313993149931599316993179931899319993209932199322993239932499325993269932799328993299933099331993329933399334993359933699337993389933999340993419934299343993449934599346993479934899349993509935199352993539935499355993569935799358993599936099361993629936399364993659936699367993689936999370993719937299373993749937599376993779937899379993809938199382993839938499385993869938799388993899939099391993929939399394993959939699397993989939999400994019940299403994049940599406994079940899409994109941199412994139941499415994169941799418994199942099421994229942399424994259942699427994289942999430994319943299433994349943599436994379943899439994409944199442994439944499445994469944799448994499945099451994529945399454994559945699457994589945999460994619946299463994649946599466994679946899469994709947199472994739947499475994769947799478994799948099481994829948399484994859948699487994889948999490994919949299493994949949599496994979949899499995009950199502995039950499505995069950799508995099951099511995129951399514995159951699517995189951999520995219952299523995249952599526995279952899529995309953199532995339953499535995369953799538995399954099541995429954399544995459954699547995489954999550995519955299553995549955599556995579955899559
  1. var __decorate=this&&this.__decorate||function(e,t,r,c){var o,f=arguments.length,n=f<3?t:null===c?c=Object.getOwnPropertyDescriptor(t,r):c;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)n=Reflect.decorate(e,t,r,c);else for(var l=e.length-1;l>=0;l--)(o=e[l])&&(n=(f<3?o(n):f>3?o(t,r,n):o(t,r))||n);return f>3&&n&&Object.defineProperty(t,r,n),n};
  2. var __extends=this&&this.__extends||function(){var t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,o){t.__proto__=o}||function(t,o){for(var n in o)o.hasOwnProperty(n)&&(t[n]=o[n])};return function(o,n){function r(){this.constructor=o}t(o,n),o.prototype=null===n?Object.create(n):(r.prototype=n.prototype,new r)}}();
  3. var BABYLON;
  4. (function (BABYLON) {
  5. /**
  6. * EffectFallbacks can be used to add fallbacks (properties to disable) to certain properties when desired to improve performance.
  7. * (Eg. Start at high quality with reflection and fog, if fps is low, remove reflection, if still low remove fog)
  8. */
  9. var EffectFallbacks = /** @class */ (function () {
  10. function EffectFallbacks() {
  11. this._defines = {};
  12. this._currentRank = 32;
  13. this._maxRank = -1;
  14. }
  15. /**
  16. * Removes the fallback from the bound mesh.
  17. */
  18. EffectFallbacks.prototype.unBindMesh = function () {
  19. this._mesh = null;
  20. };
  21. /**
  22. * Adds a fallback on the specified property.
  23. * @param rank The rank of the fallback (Lower ranks will be fallbacked to first)
  24. * @param define The name of the define in the shader
  25. */
  26. EffectFallbacks.prototype.addFallback = function (rank, define) {
  27. if (!this._defines[rank]) {
  28. if (rank < this._currentRank) {
  29. this._currentRank = rank;
  30. }
  31. if (rank > this._maxRank) {
  32. this._maxRank = rank;
  33. }
  34. this._defines[rank] = new Array();
  35. }
  36. this._defines[rank].push(define);
  37. };
  38. /**
  39. * Sets the mesh to use CPU skinning when needing to fallback.
  40. * @param rank The rank of the fallback (Lower ranks will be fallbacked to first)
  41. * @param mesh The mesh to use the fallbacks.
  42. */
  43. EffectFallbacks.prototype.addCPUSkinningFallback = function (rank, mesh) {
  44. this._mesh = mesh;
  45. if (rank < this._currentRank) {
  46. this._currentRank = rank;
  47. }
  48. if (rank > this._maxRank) {
  49. this._maxRank = rank;
  50. }
  51. };
  52. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  53. /**
  54. * Checks to see if more fallbacks are still availible.
  55. */
  56. get: function () {
  57. return this._currentRank <= this._maxRank;
  58. },
  59. enumerable: true,
  60. configurable: true
  61. });
  62. /**
  63. * Removes the defines that shoould be removed when falling back.
  64. * @param currentDefines defines the current define statements for the shader.
  65. * @param effect defines the current effect we try to compile
  66. * @returns The resulting defines with defines of the current rank removed.
  67. */
  68. EffectFallbacks.prototype.reduce = function (currentDefines, effect) {
  69. // First we try to switch to CPU skinning
  70. if (this._mesh && this._mesh.computeBonesUsingShaders && this._mesh.numBoneInfluencers > 0 && this._mesh.material) {
  71. this._mesh.computeBonesUsingShaders = false;
  72. currentDefines = currentDefines.replace("#define NUM_BONE_INFLUENCERS " + this._mesh.numBoneInfluencers, "#define NUM_BONE_INFLUENCERS 0");
  73. effect._bonesComputationForcedToCPU = true;
  74. var scene = this._mesh.getScene();
  75. for (var index = 0; index < scene.meshes.length; index++) {
  76. var otherMesh = scene.meshes[index];
  77. if (!otherMesh.material) {
  78. continue;
  79. }
  80. if (!otherMesh.computeBonesUsingShaders || otherMesh.numBoneInfluencers === 0) {
  81. continue;
  82. }
  83. if (otherMesh.material.getEffect() === effect) {
  84. otherMesh.computeBonesUsingShaders = false;
  85. }
  86. else if (otherMesh.subMeshes) {
  87. for (var _i = 0, _a = otherMesh.subMeshes; _i < _a.length; _i++) {
  88. var subMesh = _a[_i];
  89. var subMeshEffect = subMesh.effect;
  90. if (subMeshEffect === effect) {
  91. otherMesh.computeBonesUsingShaders = false;
  92. break;
  93. }
  94. }
  95. }
  96. }
  97. }
  98. else {
  99. var currentFallbacks = this._defines[this._currentRank];
  100. if (currentFallbacks) {
  101. for (var index = 0; index < currentFallbacks.length; index++) {
  102. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  103. }
  104. }
  105. this._currentRank++;
  106. }
  107. return currentDefines;
  108. };
  109. return EffectFallbacks;
  110. }());
  111. BABYLON.EffectFallbacks = EffectFallbacks;
  112. /**
  113. * Options to be used when creating an effect.
  114. */
  115. var EffectCreationOptions = /** @class */ (function () {
  116. function EffectCreationOptions() {
  117. }
  118. return EffectCreationOptions;
  119. }());
  120. BABYLON.EffectCreationOptions = EffectCreationOptions;
  121. /**
  122. * Effect containing vertex and fragment shader that can be executed on an object.
  123. */
  124. var Effect = /** @class */ (function () {
  125. /**
  126. * Instantiates an effect.
  127. * An effect can be used to create/manage/execute vertex and fragment shaders.
  128. * @param baseName Name of the effect.
  129. * @param attributesNamesOrOptions List of attribute names that will be passed to the shader or set of all options to create the effect.
  130. * @param uniformsNamesOrEngine List of uniform variable names that will be passed to the shader or the engine that will be used to render effect.
  131. * @param samplers List of sampler variables that will be passed to the shader.
  132. * @param engine Engine to be used to render the effect
  133. * @param defines Define statements to be added to the shader.
  134. * @param fallbacks Possible fallbacks for this effect to improve performance when needed.
  135. * @param onCompiled Callback that will be called when the shader is compiled.
  136. * @param onError Callback that will be called if an error occurs during shader compilation.
  137. * @param indexParameters Parameters to be used with Babylons include syntax to iterate over an array (eg. {lights: 10})
  138. */
  139. function Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, engine, defines, fallbacks, onCompiled, onError, indexParameters) {
  140. if (samplers === void 0) { samplers = null; }
  141. if (defines === void 0) { defines = null; }
  142. if (fallbacks === void 0) { fallbacks = null; }
  143. if (onCompiled === void 0) { onCompiled = null; }
  144. if (onError === void 0) { onError = null; }
  145. var _this = this;
  146. /**
  147. * Unique ID of the effect.
  148. */
  149. this.uniqueId = 0;
  150. /**
  151. * Observable that will be called when the shader is compiled.
  152. */
  153. this.onCompileObservable = new BABYLON.Observable();
  154. /**
  155. * Observable that will be called if an error occurs during shader compilation.
  156. */
  157. this.onErrorObservable = new BABYLON.Observable();
  158. /**
  159. * Observable that will be called when effect is bound.
  160. */
  161. this.onBindObservable = new BABYLON.Observable();
  162. /** @hidden */
  163. this._bonesComputationForcedToCPU = false;
  164. this._uniformBuffersNames = {};
  165. this._isReady = false;
  166. this._compilationError = "";
  167. this.name = baseName;
  168. if (attributesNamesOrOptions.attributes) {
  169. var options = attributesNamesOrOptions;
  170. this._engine = uniformsNamesOrEngine;
  171. this._attributesNames = options.attributes;
  172. this._uniformsNames = options.uniformsNames.concat(options.samplers);
  173. this._samplers = options.samplers.slice();
  174. this.defines = options.defines;
  175. this.onError = options.onError;
  176. this.onCompiled = options.onCompiled;
  177. this._fallbacks = options.fallbacks;
  178. this._indexParameters = options.indexParameters;
  179. this._transformFeedbackVaryings = options.transformFeedbackVaryings;
  180. if (options.uniformBuffersNames) {
  181. for (var i = 0; i < options.uniformBuffersNames.length; i++) {
  182. this._uniformBuffersNames[options.uniformBuffersNames[i]] = i;
  183. }
  184. }
  185. }
  186. else {
  187. this._engine = engine;
  188. this.defines = defines;
  189. this._uniformsNames = uniformsNamesOrEngine.concat(samplers);
  190. this._samplers = samplers ? samplers.slice() : [];
  191. this._attributesNames = attributesNamesOrOptions;
  192. this.onError = onError;
  193. this.onCompiled = onCompiled;
  194. this._indexParameters = indexParameters;
  195. this._fallbacks = fallbacks;
  196. }
  197. this.uniqueId = Effect._uniqueIdSeed++;
  198. var vertexSource;
  199. var fragmentSource;
  200. if (baseName.vertexElement) {
  201. vertexSource = document.getElementById(baseName.vertexElement);
  202. if (!vertexSource) {
  203. vertexSource = baseName.vertexElement;
  204. }
  205. }
  206. else {
  207. vertexSource = baseName.vertex || baseName;
  208. }
  209. if (baseName.fragmentElement) {
  210. fragmentSource = document.getElementById(baseName.fragmentElement);
  211. if (!fragmentSource) {
  212. fragmentSource = baseName.fragmentElement;
  213. }
  214. }
  215. else {
  216. fragmentSource = baseName.fragment || baseName;
  217. }
  218. this._loadVertexShader(vertexSource, function (vertexCode) {
  219. _this._processIncludes(vertexCode, function (vertexCodeWithIncludes) {
  220. _this._processShaderConversion(vertexCodeWithIncludes, false, function (migratedVertexCode) {
  221. _this._loadFragmentShader(fragmentSource, function (fragmentCode) {
  222. _this._processIncludes(fragmentCode, function (fragmentCodeWithIncludes) {
  223. _this._processShaderConversion(fragmentCodeWithIncludes, true, function (migratedFragmentCode) {
  224. if (baseName) {
  225. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  226. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  227. _this._vertexSourceCode = "#define SHADER_NAME vertex:" + vertex + "\n" + migratedVertexCode;
  228. _this._fragmentSourceCode = "#define SHADER_NAME fragment:" + fragment + "\n" + migratedFragmentCode;
  229. }
  230. else {
  231. _this._vertexSourceCode = migratedVertexCode;
  232. _this._fragmentSourceCode = migratedFragmentCode;
  233. }
  234. _this._prepareEffect();
  235. });
  236. });
  237. });
  238. });
  239. });
  240. });
  241. }
  242. Object.defineProperty(Effect.prototype, "key", {
  243. /**
  244. * Unique key for this effect
  245. */
  246. get: function () {
  247. return this._key;
  248. },
  249. enumerable: true,
  250. configurable: true
  251. });
  252. /**
  253. * If the effect has been compiled and prepared.
  254. * @returns if the effect is compiled and prepared.
  255. */
  256. Effect.prototype.isReady = function () {
  257. return this._isReady;
  258. };
  259. /**
  260. * The engine the effect was initialized with.
  261. * @returns the engine.
  262. */
  263. Effect.prototype.getEngine = function () {
  264. return this._engine;
  265. };
  266. /**
  267. * The compiled webGL program for the effect
  268. * @returns the webGL program.
  269. */
  270. Effect.prototype.getProgram = function () {
  271. return this._program;
  272. };
  273. /**
  274. * The set of names of attribute variables for the shader.
  275. * @returns An array of attribute names.
  276. */
  277. Effect.prototype.getAttributesNames = function () {
  278. return this._attributesNames;
  279. };
  280. /**
  281. * Returns the attribute at the given index.
  282. * @param index The index of the attribute.
  283. * @returns The location of the attribute.
  284. */
  285. Effect.prototype.getAttributeLocation = function (index) {
  286. return this._attributes[index];
  287. };
  288. /**
  289. * Returns the attribute based on the name of the variable.
  290. * @param name of the attribute to look up.
  291. * @returns the attribute location.
  292. */
  293. Effect.prototype.getAttributeLocationByName = function (name) {
  294. var index = this._attributesNames.indexOf(name);
  295. return this._attributes[index];
  296. };
  297. /**
  298. * The number of attributes.
  299. * @returns the numnber of attributes.
  300. */
  301. Effect.prototype.getAttributesCount = function () {
  302. return this._attributes.length;
  303. };
  304. /**
  305. * Gets the index of a uniform variable.
  306. * @param uniformName of the uniform to look up.
  307. * @returns the index.
  308. */
  309. Effect.prototype.getUniformIndex = function (uniformName) {
  310. return this._uniformsNames.indexOf(uniformName);
  311. };
  312. /**
  313. * Returns the attribute based on the name of the variable.
  314. * @param uniformName of the uniform to look up.
  315. * @returns the location of the uniform.
  316. */
  317. Effect.prototype.getUniform = function (uniformName) {
  318. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  319. };
  320. /**
  321. * Returns an array of sampler variable names
  322. * @returns The array of sampler variable neames.
  323. */
  324. Effect.prototype.getSamplers = function () {
  325. return this._samplers;
  326. };
  327. /**
  328. * The error from the last compilation.
  329. * @returns the error string.
  330. */
  331. Effect.prototype.getCompilationError = function () {
  332. return this._compilationError;
  333. };
  334. /**
  335. * Adds a callback to the onCompiled observable and call the callback imediatly if already ready.
  336. * @param func The callback to be used.
  337. */
  338. Effect.prototype.executeWhenCompiled = function (func) {
  339. if (this.isReady()) {
  340. func(this);
  341. return;
  342. }
  343. this.onCompileObservable.add(function (effect) {
  344. func(effect);
  345. });
  346. };
  347. /** @hidden */
  348. Effect.prototype._loadVertexShader = function (vertex, callback) {
  349. if (BABYLON.Tools.IsWindowObjectExist()) {
  350. // DOM element ?
  351. if (vertex instanceof HTMLElement) {
  352. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  353. callback(vertexCode);
  354. return;
  355. }
  356. }
  357. // Base64 encoded ?
  358. if (vertex.substr(0, 7) === "base64:") {
  359. var vertexBinary = window.atob(vertex.substr(7));
  360. callback(vertexBinary);
  361. return;
  362. }
  363. // Is in local store ?
  364. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  365. callback(Effect.ShadersStore[vertex + "VertexShader"]);
  366. return;
  367. }
  368. var vertexShaderUrl;
  369. if (vertex[0] === "." || vertex[0] === "/" || vertex.indexOf("http") > -1) {
  370. vertexShaderUrl = vertex;
  371. }
  372. else {
  373. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  374. }
  375. // Vertex shader
  376. this._engine._loadFile(vertexShaderUrl + ".vertex.fx", callback);
  377. };
  378. /** @hidden */
  379. Effect.prototype._loadFragmentShader = function (fragment, callback) {
  380. if (BABYLON.Tools.IsWindowObjectExist()) {
  381. // DOM element ?
  382. if (fragment instanceof HTMLElement) {
  383. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  384. callback(fragmentCode);
  385. return;
  386. }
  387. }
  388. // Base64 encoded ?
  389. if (fragment.substr(0, 7) === "base64:") {
  390. var fragmentBinary = window.atob(fragment.substr(7));
  391. callback(fragmentBinary);
  392. return;
  393. }
  394. // Is in local store ?
  395. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  396. callback(Effect.ShadersStore[fragment + "PixelShader"]);
  397. return;
  398. }
  399. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  400. callback(Effect.ShadersStore[fragment + "FragmentShader"]);
  401. return;
  402. }
  403. var fragmentShaderUrl;
  404. if (fragment[0] === "." || fragment[0] === "/" || fragment.indexOf("http") > -1) {
  405. fragmentShaderUrl = fragment;
  406. }
  407. else {
  408. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  409. }
  410. // Fragment shader
  411. this._engine._loadFile(fragmentShaderUrl + ".fragment.fx", callback);
  412. };
  413. Effect.prototype._dumpShadersSource = function (vertexCode, fragmentCode, defines) {
  414. // Rebuild shaders source code
  415. var shaderVersion = (this._engine.webGLVersion > 1) ? "#version 300 es\n#define WEBGL2 \n" : "";
  416. var prefix = shaderVersion + (defines ? defines + "\n" : "");
  417. vertexCode = prefix + vertexCode;
  418. fragmentCode = prefix + fragmentCode;
  419. // Number lines of shaders source code
  420. var i = 2;
  421. var regex = /\n/gm;
  422. var formattedVertexCode = "\n1\t" + vertexCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  423. i = 2;
  424. var formattedFragmentCode = "\n1\t" + fragmentCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  425. // Dump shaders name and formatted source code
  426. if (this.name.vertexElement) {
  427. BABYLON.Tools.Error("Vertex shader: " + this.name.vertexElement + formattedVertexCode);
  428. BABYLON.Tools.Error("Fragment shader: " + this.name.fragmentElement + formattedFragmentCode);
  429. }
  430. else if (this.name.vertex) {
  431. BABYLON.Tools.Error("Vertex shader: " + this.name.vertex + formattedVertexCode);
  432. BABYLON.Tools.Error("Fragment shader: " + this.name.fragment + formattedFragmentCode);
  433. }
  434. else {
  435. BABYLON.Tools.Error("Vertex shader: " + this.name + formattedVertexCode);
  436. BABYLON.Tools.Error("Fragment shader: " + this.name + formattedFragmentCode);
  437. }
  438. };
  439. ;
  440. Effect.prototype._processShaderConversion = function (sourceCode, isFragment, callback) {
  441. var preparedSourceCode = this._processPrecision(sourceCode);
  442. if (this._engine.webGLVersion == 1) {
  443. callback(preparedSourceCode);
  444. return;
  445. }
  446. // Already converted
  447. if (preparedSourceCode.indexOf("#version 3") !== -1) {
  448. callback(preparedSourceCode.replace("#version 300 es", ""));
  449. return;
  450. }
  451. var hasDrawBuffersExtension = preparedSourceCode.search(/#extension.+GL_EXT_draw_buffers.+require/) !== -1;
  452. // Remove extensions
  453. // #extension GL_OES_standard_derivatives : enable
  454. // #extension GL_EXT_shader_texture_lod : enable
  455. // #extension GL_EXT_frag_depth : enable
  456. // #extension GL_EXT_draw_buffers : require
  457. var regex = /#extension.+(GL_OES_standard_derivatives|GL_EXT_shader_texture_lod|GL_EXT_frag_depth|GL_EXT_draw_buffers).+(enable|require)/g;
  458. var result = preparedSourceCode.replace(regex, "");
  459. // Migrate to GLSL v300
  460. result = result.replace(/varying(?![\n\r])\s/g, isFragment ? "in " : "out ");
  461. result = result.replace(/attribute[ \t]/g, "in ");
  462. result = result.replace(/[ \t]attribute/g, " in");
  463. if (isFragment) {
  464. result = result.replace(/texture2DLodEXT\s*\(/g, "textureLod(");
  465. result = result.replace(/textureCubeLodEXT\s*\(/g, "textureLod(");
  466. result = result.replace(/texture2D\s*\(/g, "texture(");
  467. result = result.replace(/textureCube\s*\(/g, "texture(");
  468. result = result.replace(/gl_FragDepthEXT/g, "gl_FragDepth");
  469. result = result.replace(/gl_FragColor/g, "glFragColor");
  470. result = result.replace(/gl_FragData/g, "glFragData");
  471. result = result.replace(/void\s+?main\s*\(/g, (hasDrawBuffersExtension ? "" : "out vec4 glFragColor;\n") + "void main(");
  472. }
  473. callback(result);
  474. };
  475. Effect.prototype._processIncludes = function (sourceCode, callback) {
  476. var _this = this;
  477. var regex = /#include<(.+)>(\((.*)\))*(\[(.*)\])*/g;
  478. var match = regex.exec(sourceCode);
  479. var returnValue = new String(sourceCode);
  480. while (match != null) {
  481. var includeFile = match[1];
  482. // Uniform declaration
  483. if (includeFile.indexOf("__decl__") !== -1) {
  484. includeFile = includeFile.replace(/__decl__/, "");
  485. if (this._engine.supportsUniformBuffers) {
  486. includeFile = includeFile.replace(/Vertex/, "Ubo");
  487. includeFile = includeFile.replace(/Fragment/, "Ubo");
  488. }
  489. includeFile = includeFile + "Declaration";
  490. }
  491. if (Effect.IncludesShadersStore[includeFile]) {
  492. // Substitution
  493. var includeContent = Effect.IncludesShadersStore[includeFile];
  494. if (match[2]) {
  495. var splits = match[3].split(",");
  496. for (var index = 0; index < splits.length; index += 2) {
  497. var source = new RegExp(splits[index], "g");
  498. var dest = splits[index + 1];
  499. includeContent = includeContent.replace(source, dest);
  500. }
  501. }
  502. if (match[4]) {
  503. var indexString = match[5];
  504. if (indexString.indexOf("..") !== -1) {
  505. var indexSplits = indexString.split("..");
  506. var minIndex = parseInt(indexSplits[0]);
  507. var maxIndex = parseInt(indexSplits[1]);
  508. var sourceIncludeContent = includeContent.slice(0);
  509. includeContent = "";
  510. if (isNaN(maxIndex)) {
  511. maxIndex = this._indexParameters[indexSplits[1]];
  512. }
  513. for (var i = minIndex; i < maxIndex; i++) {
  514. if (!this._engine.supportsUniformBuffers) {
  515. // Ubo replacement
  516. sourceIncludeContent = sourceIncludeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  517. return p1 + "{X}";
  518. });
  519. }
  520. includeContent += sourceIncludeContent.replace(/\{X\}/g, i.toString()) + "\n";
  521. }
  522. }
  523. else {
  524. if (!this._engine.supportsUniformBuffers) {
  525. // Ubo replacement
  526. includeContent = includeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  527. return p1 + "{X}";
  528. });
  529. }
  530. includeContent = includeContent.replace(/\{X\}/g, indexString);
  531. }
  532. }
  533. // Replace
  534. returnValue = returnValue.replace(match[0], includeContent);
  535. }
  536. else {
  537. var includeShaderUrl = BABYLON.Engine.ShadersRepository + "ShadersInclude/" + includeFile + ".fx";
  538. this._engine._loadFile(includeShaderUrl, function (fileContent) {
  539. Effect.IncludesShadersStore[includeFile] = fileContent;
  540. _this._processIncludes(returnValue, callback);
  541. });
  542. return;
  543. }
  544. match = regex.exec(sourceCode);
  545. }
  546. callback(returnValue);
  547. };
  548. Effect.prototype._processPrecision = function (source) {
  549. if (source.indexOf("precision highp float") === -1) {
  550. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  551. source = "precision mediump float;\n" + source;
  552. }
  553. else {
  554. source = "precision highp float;\n" + source;
  555. }
  556. }
  557. else {
  558. if (!this._engine.getCaps().highPrecisionShaderSupported) { // Moving highp to mediump
  559. source = source.replace("precision highp float", "precision mediump float");
  560. }
  561. }
  562. return source;
  563. };
  564. /**
  565. * Recompiles the webGL program
  566. * @param vertexSourceCode The source code for the vertex shader.
  567. * @param fragmentSourceCode The source code for the fragment shader.
  568. * @param onCompiled Callback called when completed.
  569. * @param onError Callback called on error.
  570. */
  571. Effect.prototype._rebuildProgram = function (vertexSourceCode, fragmentSourceCode, onCompiled, onError) {
  572. var _this = this;
  573. this._isReady = false;
  574. this._vertexSourceCodeOverride = vertexSourceCode;
  575. this._fragmentSourceCodeOverride = fragmentSourceCode;
  576. this.onError = function (effect, error) {
  577. if (onError) {
  578. onError(error);
  579. }
  580. };
  581. this.onCompiled = function () {
  582. var scenes = _this.getEngine().scenes;
  583. for (var i = 0; i < scenes.length; i++) {
  584. scenes[i].markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  585. }
  586. if (onCompiled) {
  587. onCompiled(_this._program);
  588. }
  589. };
  590. this._fallbacks = null;
  591. this._prepareEffect();
  592. };
  593. /**
  594. * Gets the uniform locations of the the specified variable names
  595. * @param names THe names of the variables to lookup.
  596. * @returns Array of locations in the same order as variable names.
  597. */
  598. Effect.prototype.getSpecificUniformLocations = function (names) {
  599. var engine = this._engine;
  600. return engine.getUniforms(this._program, names);
  601. };
  602. /**
  603. * Prepares the effect
  604. */
  605. Effect.prototype._prepareEffect = function () {
  606. var attributesNames = this._attributesNames;
  607. var defines = this.defines;
  608. var fallbacks = this._fallbacks;
  609. this._valueCache = {};
  610. var previousProgram = this._program;
  611. try {
  612. var engine = this._engine;
  613. if (this._vertexSourceCodeOverride && this._fragmentSourceCodeOverride) {
  614. this._program = engine.createRawShaderProgram(this._vertexSourceCodeOverride, this._fragmentSourceCodeOverride, undefined, this._transformFeedbackVaryings);
  615. }
  616. else {
  617. this._program = engine.createShaderProgram(this._vertexSourceCode, this._fragmentSourceCode, defines, undefined, this._transformFeedbackVaryings);
  618. }
  619. this._program.__SPECTOR_rebuildProgram = this._rebuildProgram.bind(this);
  620. if (engine.supportsUniformBuffers) {
  621. for (var name in this._uniformBuffersNames) {
  622. this.bindUniformBlock(name, this._uniformBuffersNames[name]);
  623. }
  624. }
  625. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  626. this._attributes = engine.getAttributes(this._program, attributesNames);
  627. var index;
  628. for (index = 0; index < this._samplers.length; index++) {
  629. var sampler = this.getUniform(this._samplers[index]);
  630. if (sampler == null) {
  631. this._samplers.splice(index, 1);
  632. index--;
  633. }
  634. }
  635. engine.bindSamplers(this);
  636. this._compilationError = "";
  637. this._isReady = true;
  638. if (this.onCompiled) {
  639. this.onCompiled(this);
  640. }
  641. this.onCompileObservable.notifyObservers(this);
  642. this.onCompileObservable.clear();
  643. // Unbind mesh reference in fallbacks
  644. if (this._fallbacks) {
  645. this._fallbacks.unBindMesh();
  646. }
  647. if (previousProgram) {
  648. this.getEngine()._deleteProgram(previousProgram);
  649. }
  650. }
  651. catch (e) {
  652. this._compilationError = e.message;
  653. // Let's go through fallbacks then
  654. BABYLON.Tools.Error("Unable to compile effect:");
  655. BABYLON.Tools.Error("Uniforms: " + this._uniformsNames.map(function (uniform) {
  656. return " " + uniform;
  657. }));
  658. BABYLON.Tools.Error("Attributes: " + attributesNames.map(function (attribute) {
  659. return " " + attribute;
  660. }));
  661. this._dumpShadersSource(this._vertexSourceCode, this._fragmentSourceCode, defines);
  662. BABYLON.Tools.Error("Error: " + this._compilationError);
  663. if (previousProgram) {
  664. this._program = previousProgram;
  665. this._isReady = true;
  666. if (this.onError) {
  667. this.onError(this, this._compilationError);
  668. }
  669. this.onErrorObservable.notifyObservers(this);
  670. }
  671. if (fallbacks && fallbacks.isMoreFallbacks) {
  672. BABYLON.Tools.Error("Trying next fallback.");
  673. this.defines = fallbacks.reduce(this.defines, this);
  674. this._prepareEffect();
  675. }
  676. else { // Sorry we did everything we can
  677. if (this.onError) {
  678. this.onError(this, this._compilationError);
  679. }
  680. this.onErrorObservable.notifyObservers(this);
  681. this.onErrorObservable.clear();
  682. // Unbind mesh reference in fallbacks
  683. if (this._fallbacks) {
  684. this._fallbacks.unBindMesh();
  685. }
  686. }
  687. }
  688. };
  689. Object.defineProperty(Effect.prototype, "isSupported", {
  690. /**
  691. * Checks if the effect is supported. (Must be called after compilation)
  692. */
  693. get: function () {
  694. return this._compilationError === "";
  695. },
  696. enumerable: true,
  697. configurable: true
  698. });
  699. /**
  700. * Binds a texture to the engine to be used as output of the shader.
  701. * @param channel Name of the output variable.
  702. * @param texture Texture to bind.
  703. */
  704. Effect.prototype._bindTexture = function (channel, texture) {
  705. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  706. };
  707. /**
  708. * Sets a texture on the engine to be used in the shader.
  709. * @param channel Name of the sampler variable.
  710. * @param texture Texture to set.
  711. */
  712. Effect.prototype.setTexture = function (channel, texture) {
  713. this._engine.setTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  714. };
  715. /**
  716. * Sets a depth stencil texture from a render target on the engine to be used in the shader.
  717. * @param channel Name of the sampler variable.
  718. * @param texture Texture to set.
  719. */
  720. Effect.prototype.setDepthStencilTexture = function (channel, texture) {
  721. this._engine.setDepthStencilTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  722. };
  723. /**
  724. * Sets an array of textures on the engine to be used in the shader.
  725. * @param channel Name of the variable.
  726. * @param textures Textures to set.
  727. */
  728. Effect.prototype.setTextureArray = function (channel, textures) {
  729. if (this._samplers.indexOf(channel + "Ex") === -1) {
  730. var initialPos = this._samplers.indexOf(channel);
  731. for (var index = 1; index < textures.length; index++) {
  732. this._samplers.splice(initialPos + index, 0, channel + "Ex");
  733. }
  734. }
  735. this._engine.setTextureArray(this._samplers.indexOf(channel), this.getUniform(channel), textures);
  736. };
  737. /**
  738. * Sets a texture to be the input of the specified post process. (To use the output, pass in the next post process in the pipeline)
  739. * @param channel Name of the sampler variable.
  740. * @param postProcess Post process to get the input texture from.
  741. */
  742. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  743. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  744. };
  745. /**
  746. * (Warning! setTextureFromPostProcessOutput may be desired instead)
  747. * Sets the input texture of the passed in post process to be input of this effect. (To use the output of the passed in post process use setTextureFromPostProcessOutput)
  748. * @param channel Name of the sampler variable.
  749. * @param postProcess Post process to get the output texture from.
  750. */
  751. Effect.prototype.setTextureFromPostProcessOutput = function (channel, postProcess) {
  752. this._engine.setTextureFromPostProcessOutput(this._samplers.indexOf(channel), postProcess);
  753. };
  754. /** @hidden */
  755. Effect.prototype._cacheMatrix = function (uniformName, matrix) {
  756. var cache = this._valueCache[uniformName];
  757. var flag = matrix.updateFlag;
  758. if (cache !== undefined && cache === flag) {
  759. return false;
  760. }
  761. this._valueCache[uniformName] = flag;
  762. return true;
  763. };
  764. /** @hidden */
  765. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  766. var cache = this._valueCache[uniformName];
  767. if (!cache) {
  768. cache = [x, y];
  769. this._valueCache[uniformName] = cache;
  770. return true;
  771. }
  772. var changed = false;
  773. if (cache[0] !== x) {
  774. cache[0] = x;
  775. changed = true;
  776. }
  777. if (cache[1] !== y) {
  778. cache[1] = y;
  779. changed = true;
  780. }
  781. return changed;
  782. };
  783. /** @hidden */
  784. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  785. var cache = this._valueCache[uniformName];
  786. if (!cache) {
  787. cache = [x, y, z];
  788. this._valueCache[uniformName] = cache;
  789. return true;
  790. }
  791. var changed = false;
  792. if (cache[0] !== x) {
  793. cache[0] = x;
  794. changed = true;
  795. }
  796. if (cache[1] !== y) {
  797. cache[1] = y;
  798. changed = true;
  799. }
  800. if (cache[2] !== z) {
  801. cache[2] = z;
  802. changed = true;
  803. }
  804. return changed;
  805. };
  806. /** @hidden */
  807. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  808. var cache = this._valueCache[uniformName];
  809. if (!cache) {
  810. cache = [x, y, z, w];
  811. this._valueCache[uniformName] = cache;
  812. return true;
  813. }
  814. var changed = false;
  815. if (cache[0] !== x) {
  816. cache[0] = x;
  817. changed = true;
  818. }
  819. if (cache[1] !== y) {
  820. cache[1] = y;
  821. changed = true;
  822. }
  823. if (cache[2] !== z) {
  824. cache[2] = z;
  825. changed = true;
  826. }
  827. if (cache[3] !== w) {
  828. cache[3] = w;
  829. changed = true;
  830. }
  831. return changed;
  832. };
  833. /**
  834. * Binds a buffer to a uniform.
  835. * @param buffer Buffer to bind.
  836. * @param name Name of the uniform variable to bind to.
  837. */
  838. Effect.prototype.bindUniformBuffer = function (buffer, name) {
  839. var bufferName = this._uniformBuffersNames[name];
  840. if (bufferName === undefined || Effect._baseCache[bufferName] === buffer) {
  841. return;
  842. }
  843. Effect._baseCache[bufferName] = buffer;
  844. this._engine.bindUniformBufferBase(buffer, bufferName);
  845. };
  846. /**
  847. * Binds block to a uniform.
  848. * @param blockName Name of the block to bind.
  849. * @param index Index to bind.
  850. */
  851. Effect.prototype.bindUniformBlock = function (blockName, index) {
  852. this._engine.bindUniformBlock(this._program, blockName, index);
  853. };
  854. /**
  855. * Sets an interger value on a uniform variable.
  856. * @param uniformName Name of the variable.
  857. * @param value Value to be set.
  858. * @returns this effect.
  859. */
  860. Effect.prototype.setInt = function (uniformName, value) {
  861. var cache = this._valueCache[uniformName];
  862. if (cache !== undefined && cache === value)
  863. return this;
  864. this._valueCache[uniformName] = value;
  865. this._engine.setInt(this.getUniform(uniformName), value);
  866. return this;
  867. };
  868. /**
  869. * Sets an int array on a uniform variable.
  870. * @param uniformName Name of the variable.
  871. * @param array array to be set.
  872. * @returns this effect.
  873. */
  874. Effect.prototype.setIntArray = function (uniformName, array) {
  875. this._valueCache[uniformName] = null;
  876. this._engine.setIntArray(this.getUniform(uniformName), array);
  877. return this;
  878. };
  879. /**
  880. * Sets an int array 2 on a uniform variable. (Array is specified as single array eg. [1,2,3,4] will result in [[1,2],[3,4]] in the shader)
  881. * @param uniformName Name of the variable.
  882. * @param array array to be set.
  883. * @returns this effect.
  884. */
  885. Effect.prototype.setIntArray2 = function (uniformName, array) {
  886. this._valueCache[uniformName] = null;
  887. this._engine.setIntArray2(this.getUniform(uniformName), array);
  888. return this;
  889. };
  890. /**
  891. * Sets an int array 3 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6] will result in [[1,2,3],[4,5,6]] in the shader)
  892. * @param uniformName Name of the variable.
  893. * @param array array to be set.
  894. * @returns this effect.
  895. */
  896. Effect.prototype.setIntArray3 = function (uniformName, array) {
  897. this._valueCache[uniformName] = null;
  898. this._engine.setIntArray3(this.getUniform(uniformName), array);
  899. return this;
  900. };
  901. /**
  902. * Sets an int array 4 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6,7,8] will result in [[1,2,3,4],[5,6,7,8]] in the shader)
  903. * @param uniformName Name of the variable.
  904. * @param array array to be set.
  905. * @returns this effect.
  906. */
  907. Effect.prototype.setIntArray4 = function (uniformName, array) {
  908. this._valueCache[uniformName] = null;
  909. this._engine.setIntArray4(this.getUniform(uniformName), array);
  910. return this;
  911. };
  912. /**
  913. * Sets an float array on a uniform variable.
  914. * @param uniformName Name of the variable.
  915. * @param array array to be set.
  916. * @returns this effect.
  917. */
  918. Effect.prototype.setFloatArray = function (uniformName, array) {
  919. this._valueCache[uniformName] = null;
  920. this._engine.setFloatArray(this.getUniform(uniformName), array);
  921. return this;
  922. };
  923. /**
  924. * Sets an float array 2 on a uniform variable. (Array is specified as single array eg. [1,2,3,4] will result in [[1,2],[3,4]] in the shader)
  925. * @param uniformName Name of the variable.
  926. * @param array array to be set.
  927. * @returns this effect.
  928. */
  929. Effect.prototype.setFloatArray2 = function (uniformName, array) {
  930. this._valueCache[uniformName] = null;
  931. this._engine.setFloatArray2(this.getUniform(uniformName), array);
  932. return this;
  933. };
  934. /**
  935. * Sets an float array 3 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6] will result in [[1,2,3],[4,5,6]] in the shader)
  936. * @param uniformName Name of the variable.
  937. * @param array array to be set.
  938. * @returns this effect.
  939. */
  940. Effect.prototype.setFloatArray3 = function (uniformName, array) {
  941. this._valueCache[uniformName] = null;
  942. this._engine.setFloatArray3(this.getUniform(uniformName), array);
  943. return this;
  944. };
  945. /**
  946. * Sets an float array 4 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6,7,8] will result in [[1,2,3,4],[5,6,7,8]] in the shader)
  947. * @param uniformName Name of the variable.
  948. * @param array array to be set.
  949. * @returns this effect.
  950. */
  951. Effect.prototype.setFloatArray4 = function (uniformName, array) {
  952. this._valueCache[uniformName] = null;
  953. this._engine.setFloatArray4(this.getUniform(uniformName), array);
  954. return this;
  955. };
  956. /**
  957. * Sets an array on a uniform variable.
  958. * @param uniformName Name of the variable.
  959. * @param array array to be set.
  960. * @returns this effect.
  961. */
  962. Effect.prototype.setArray = function (uniformName, array) {
  963. this._valueCache[uniformName] = null;
  964. this._engine.setArray(this.getUniform(uniformName), array);
  965. return this;
  966. };
  967. /**
  968. * Sets an array 2 on a uniform variable. (Array is specified as single array eg. [1,2,3,4] will result in [[1,2],[3,4]] in the shader)
  969. * @param uniformName Name of the variable.
  970. * @param array array to be set.
  971. * @returns this effect.
  972. */
  973. Effect.prototype.setArray2 = function (uniformName, array) {
  974. this._valueCache[uniformName] = null;
  975. this._engine.setArray2(this.getUniform(uniformName), array);
  976. return this;
  977. };
  978. /**
  979. * Sets an array 3 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6] will result in [[1,2,3],[4,5,6]] in the shader)
  980. * @param uniformName Name of the variable.
  981. * @param array array to be set.
  982. * @returns this effect.
  983. */
  984. Effect.prototype.setArray3 = function (uniformName, array) {
  985. this._valueCache[uniformName] = null;
  986. this._engine.setArray3(this.getUniform(uniformName), array);
  987. return this;
  988. };
  989. /**
  990. * Sets an array 4 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6,7,8] will result in [[1,2,3,4],[5,6,7,8]] in the shader)
  991. * @param uniformName Name of the variable.
  992. * @param array array to be set.
  993. * @returns this effect.
  994. */
  995. Effect.prototype.setArray4 = function (uniformName, array) {
  996. this._valueCache[uniformName] = null;
  997. this._engine.setArray4(this.getUniform(uniformName), array);
  998. return this;
  999. };
  1000. /**
  1001. * Sets matrices on a uniform variable.
  1002. * @param uniformName Name of the variable.
  1003. * @param matrices matrices to be set.
  1004. * @returns this effect.
  1005. */
  1006. Effect.prototype.setMatrices = function (uniformName, matrices) {
  1007. if (!matrices) {
  1008. return this;
  1009. }
  1010. this._valueCache[uniformName] = null;
  1011. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  1012. return this;
  1013. };
  1014. /**
  1015. * Sets matrix on a uniform variable.
  1016. * @param uniformName Name of the variable.
  1017. * @param matrix matrix to be set.
  1018. * @returns this effect.
  1019. */
  1020. Effect.prototype.setMatrix = function (uniformName, matrix) {
  1021. if (this._cacheMatrix(uniformName, matrix)) {
  1022. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  1023. }
  1024. return this;
  1025. };
  1026. /**
  1027. * Sets a 3x3 matrix on a uniform variable. (Speicified as [1,2,3,4,5,6,7,8,9] will result in [1,2,3][4,5,6][7,8,9] matrix)
  1028. * @param uniformName Name of the variable.
  1029. * @param matrix matrix to be set.
  1030. * @returns this effect.
  1031. */
  1032. Effect.prototype.setMatrix3x3 = function (uniformName, matrix) {
  1033. this._valueCache[uniformName] = null;
  1034. this._engine.setMatrix3x3(this.getUniform(uniformName), matrix);
  1035. return this;
  1036. };
  1037. /**
  1038. * Sets a 2x2 matrix on a uniform variable. (Speicified as [1,2,3,4] will result in [1,2][3,4] matrix)
  1039. * @param uniformName Name of the variable.
  1040. * @param matrix matrix to be set.
  1041. * @returns this effect.
  1042. */
  1043. Effect.prototype.setMatrix2x2 = function (uniformName, matrix) {
  1044. this._valueCache[uniformName] = null;
  1045. this._engine.setMatrix2x2(this.getUniform(uniformName), matrix);
  1046. return this;
  1047. };
  1048. /**
  1049. * Sets a float on a uniform variable.
  1050. * @param uniformName Name of the variable.
  1051. * @param value value to be set.
  1052. * @returns this effect.
  1053. */
  1054. Effect.prototype.setFloat = function (uniformName, value) {
  1055. var cache = this._valueCache[uniformName];
  1056. if (cache !== undefined && cache === value)
  1057. return this;
  1058. this._valueCache[uniformName] = value;
  1059. this._engine.setFloat(this.getUniform(uniformName), value);
  1060. return this;
  1061. };
  1062. /**
  1063. * Sets a boolean on a uniform variable.
  1064. * @param uniformName Name of the variable.
  1065. * @param bool value to be set.
  1066. * @returns this effect.
  1067. */
  1068. Effect.prototype.setBool = function (uniformName, bool) {
  1069. var cache = this._valueCache[uniformName];
  1070. if (cache !== undefined && cache === bool)
  1071. return this;
  1072. this._valueCache[uniformName] = bool;
  1073. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  1074. return this;
  1075. };
  1076. /**
  1077. * Sets a Vector2 on a uniform variable.
  1078. * @param uniformName Name of the variable.
  1079. * @param vector2 vector2 to be set.
  1080. * @returns this effect.
  1081. */
  1082. Effect.prototype.setVector2 = function (uniformName, vector2) {
  1083. if (this._cacheFloat2(uniformName, vector2.x, vector2.y)) {
  1084. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  1085. }
  1086. return this;
  1087. };
  1088. /**
  1089. * Sets a float2 on a uniform variable.
  1090. * @param uniformName Name of the variable.
  1091. * @param x First float in float2.
  1092. * @param y Second float in float2.
  1093. * @returns this effect.
  1094. */
  1095. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  1096. if (this._cacheFloat2(uniformName, x, y)) {
  1097. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  1098. }
  1099. return this;
  1100. };
  1101. /**
  1102. * Sets a Vector3 on a uniform variable.
  1103. * @param uniformName Name of the variable.
  1104. * @param vector3 Value to be set.
  1105. * @returns this effect.
  1106. */
  1107. Effect.prototype.setVector3 = function (uniformName, vector3) {
  1108. if (this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z)) {
  1109. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  1110. }
  1111. return this;
  1112. };
  1113. /**
  1114. * Sets a float3 on a uniform variable.
  1115. * @param uniformName Name of the variable.
  1116. * @param x First float in float3.
  1117. * @param y Second float in float3.
  1118. * @param z Third float in float3.
  1119. * @returns this effect.
  1120. */
  1121. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  1122. if (this._cacheFloat3(uniformName, x, y, z)) {
  1123. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  1124. }
  1125. return this;
  1126. };
  1127. /**
  1128. * Sets a Vector4 on a uniform variable.
  1129. * @param uniformName Name of the variable.
  1130. * @param vector4 Value to be set.
  1131. * @returns this effect.
  1132. */
  1133. Effect.prototype.setVector4 = function (uniformName, vector4) {
  1134. if (this._cacheFloat4(uniformName, vector4.x, vector4.y, vector4.z, vector4.w)) {
  1135. this._engine.setFloat4(this.getUniform(uniformName), vector4.x, vector4.y, vector4.z, vector4.w);
  1136. }
  1137. return this;
  1138. };
  1139. /**
  1140. * Sets a float4 on a uniform variable.
  1141. * @param uniformName Name of the variable.
  1142. * @param x First float in float4.
  1143. * @param y Second float in float4.
  1144. * @param z Third float in float4.
  1145. * @param w Fourth float in float4.
  1146. * @returns this effect.
  1147. */
  1148. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  1149. if (this._cacheFloat4(uniformName, x, y, z, w)) {
  1150. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  1151. }
  1152. return this;
  1153. };
  1154. /**
  1155. * Sets a Color3 on a uniform variable.
  1156. * @param uniformName Name of the variable.
  1157. * @param color3 Value to be set.
  1158. * @returns this effect.
  1159. */
  1160. Effect.prototype.setColor3 = function (uniformName, color3) {
  1161. if (this._cacheFloat3(uniformName, color3.r, color3.g, color3.b)) {
  1162. this._engine.setColor3(this.getUniform(uniformName), color3);
  1163. }
  1164. return this;
  1165. };
  1166. /**
  1167. * Sets a Color4 on a uniform variable.
  1168. * @param uniformName Name of the variable.
  1169. * @param color3 Value to be set.
  1170. * @param alpha Alpha value to be set.
  1171. * @returns this effect.
  1172. */
  1173. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  1174. if (this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha)) {
  1175. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  1176. }
  1177. return this;
  1178. };
  1179. /**
  1180. * Sets a Color4 on a uniform variable
  1181. * @param uniformName defines the name of the variable
  1182. * @param color4 defines the value to be set
  1183. * @returns this effect.
  1184. */
  1185. Effect.prototype.setDirectColor4 = function (uniformName, color4) {
  1186. if (this._cacheFloat4(uniformName, color4.r, color4.g, color4.b, color4.a)) {
  1187. this._engine.setDirectColor4(this.getUniform(uniformName), color4);
  1188. }
  1189. return this;
  1190. };
  1191. /**
  1192. * Resets the cache of effects.
  1193. */
  1194. Effect.ResetCache = function () {
  1195. Effect._baseCache = {};
  1196. };
  1197. Effect._uniqueIdSeed = 0;
  1198. Effect._baseCache = {};
  1199. /**
  1200. * Store of each shader (The can be looked up using effect.key)
  1201. */
  1202. Effect.ShadersStore = {};
  1203. /**
  1204. * Store of each included file for a shader (The can be looked up using effect.key)
  1205. */
  1206. Effect.IncludesShadersStore = {};
  1207. return Effect;
  1208. }());
  1209. BABYLON.Effect = Effect;
  1210. })(BABYLON || (BABYLON = {}));
  1211. //# sourceMappingURL=babylon.effect.js.map
  1212. //# sourceMappingURL=babylon.types.js.map
  1213. var BABYLON;
  1214. (function (BABYLON) {
  1215. var KeyboardEventTypes = /** @class */ (function () {
  1216. function KeyboardEventTypes() {
  1217. }
  1218. Object.defineProperty(KeyboardEventTypes, "KEYDOWN", {
  1219. get: function () {
  1220. return KeyboardEventTypes._KEYDOWN;
  1221. },
  1222. enumerable: true,
  1223. configurable: true
  1224. });
  1225. Object.defineProperty(KeyboardEventTypes, "KEYUP", {
  1226. get: function () {
  1227. return KeyboardEventTypes._KEYUP;
  1228. },
  1229. enumerable: true,
  1230. configurable: true
  1231. });
  1232. KeyboardEventTypes._KEYDOWN = 0x01;
  1233. KeyboardEventTypes._KEYUP = 0x02;
  1234. return KeyboardEventTypes;
  1235. }());
  1236. BABYLON.KeyboardEventTypes = KeyboardEventTypes;
  1237. var KeyboardInfo = /** @class */ (function () {
  1238. function KeyboardInfo(type, event) {
  1239. this.type = type;
  1240. this.event = event;
  1241. }
  1242. return KeyboardInfo;
  1243. }());
  1244. BABYLON.KeyboardInfo = KeyboardInfo;
  1245. /**
  1246. * This class is used to store keyboard related info for the onPreKeyboardObservable event.
  1247. * Set the skipOnKeyboardObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onKeyboardObservable
  1248. */
  1249. var KeyboardInfoPre = /** @class */ (function (_super) {
  1250. __extends(KeyboardInfoPre, _super);
  1251. function KeyboardInfoPre(type, event) {
  1252. var _this = _super.call(this, type, event) || this;
  1253. _this.skipOnPointerObservable = false;
  1254. return _this;
  1255. }
  1256. return KeyboardInfoPre;
  1257. }(KeyboardInfo));
  1258. BABYLON.KeyboardInfoPre = KeyboardInfoPre;
  1259. })(BABYLON || (BABYLON = {}));
  1260. //# sourceMappingURL=babylon.keyboardEvents.js.map
  1261. var BABYLON;
  1262. (function (BABYLON) {
  1263. var PointerEventTypes = /** @class */ (function () {
  1264. function PointerEventTypes() {
  1265. }
  1266. Object.defineProperty(PointerEventTypes, "POINTERDOWN", {
  1267. get: function () {
  1268. return PointerEventTypes._POINTERDOWN;
  1269. },
  1270. enumerable: true,
  1271. configurable: true
  1272. });
  1273. Object.defineProperty(PointerEventTypes, "POINTERUP", {
  1274. get: function () {
  1275. return PointerEventTypes._POINTERUP;
  1276. },
  1277. enumerable: true,
  1278. configurable: true
  1279. });
  1280. Object.defineProperty(PointerEventTypes, "POINTERMOVE", {
  1281. get: function () {
  1282. return PointerEventTypes._POINTERMOVE;
  1283. },
  1284. enumerable: true,
  1285. configurable: true
  1286. });
  1287. Object.defineProperty(PointerEventTypes, "POINTERWHEEL", {
  1288. get: function () {
  1289. return PointerEventTypes._POINTERWHEEL;
  1290. },
  1291. enumerable: true,
  1292. configurable: true
  1293. });
  1294. Object.defineProperty(PointerEventTypes, "POINTERPICK", {
  1295. get: function () {
  1296. return PointerEventTypes._POINTERPICK;
  1297. },
  1298. enumerable: true,
  1299. configurable: true
  1300. });
  1301. Object.defineProperty(PointerEventTypes, "POINTERTAP", {
  1302. get: function () {
  1303. return PointerEventTypes._POINTERTAP;
  1304. },
  1305. enumerable: true,
  1306. configurable: true
  1307. });
  1308. Object.defineProperty(PointerEventTypes, "POINTERDOUBLETAP", {
  1309. get: function () {
  1310. return PointerEventTypes._POINTERDOUBLETAP;
  1311. },
  1312. enumerable: true,
  1313. configurable: true
  1314. });
  1315. PointerEventTypes._POINTERDOWN = 0x01;
  1316. PointerEventTypes._POINTERUP = 0x02;
  1317. PointerEventTypes._POINTERMOVE = 0x04;
  1318. PointerEventTypes._POINTERWHEEL = 0x08;
  1319. PointerEventTypes._POINTERPICK = 0x10;
  1320. PointerEventTypes._POINTERTAP = 0x20;
  1321. PointerEventTypes._POINTERDOUBLETAP = 0x40;
  1322. return PointerEventTypes;
  1323. }());
  1324. BABYLON.PointerEventTypes = PointerEventTypes;
  1325. var PointerInfoBase = /** @class */ (function () {
  1326. function PointerInfoBase(type, event) {
  1327. this.type = type;
  1328. this.event = event;
  1329. }
  1330. return PointerInfoBase;
  1331. }());
  1332. BABYLON.PointerInfoBase = PointerInfoBase;
  1333. /**
  1334. * This class is used to store pointer related info for the onPrePointerObservable event.
  1335. * Set the skipOnPointerObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onPointerObservable
  1336. */
  1337. var PointerInfoPre = /** @class */ (function (_super) {
  1338. __extends(PointerInfoPre, _super);
  1339. function PointerInfoPre(type, event, localX, localY) {
  1340. var _this = _super.call(this, type, event) || this;
  1341. /**
  1342. * Ray from a pointer if availible (eg. 6dof controller)
  1343. */
  1344. _this.ray = null;
  1345. _this.skipOnPointerObservable = false;
  1346. _this.localPosition = new BABYLON.Vector2(localX, localY);
  1347. return _this;
  1348. }
  1349. return PointerInfoPre;
  1350. }(PointerInfoBase));
  1351. BABYLON.PointerInfoPre = PointerInfoPre;
  1352. /**
  1353. * This type contains all the data related to a pointer event in Babylon.js.
  1354. * The event member is an instance of PointerEvent for all types except PointerWheel and is of type MouseWheelEvent when type equals PointerWheel. The different event types can be found in the PointerEventTypes class.
  1355. */
  1356. var PointerInfo = /** @class */ (function (_super) {
  1357. __extends(PointerInfo, _super);
  1358. function PointerInfo(type, event, pickInfo) {
  1359. var _this = _super.call(this, type, event) || this;
  1360. _this.pickInfo = pickInfo;
  1361. return _this;
  1362. }
  1363. return PointerInfo;
  1364. }(PointerInfoBase));
  1365. BABYLON.PointerInfo = PointerInfo;
  1366. })(BABYLON || (BABYLON = {}));
  1367. //# sourceMappingURL=babylon.pointerEvents.js.map
  1368. var BABYLON;
  1369. (function (BABYLON) {
  1370. BABYLON.ToGammaSpace = 1 / 2.2;
  1371. BABYLON.ToLinearSpace = 2.2;
  1372. BABYLON.Epsilon = 0.001;
  1373. /**
  1374. * Class used to hold a RBG color
  1375. */
  1376. var Color3 = /** @class */ (function () {
  1377. /**
  1378. * Creates a new Color3 object from red, green, blue values, all between 0 and 1
  1379. * @param r defines the red component (between 0 and 1, default is 0)
  1380. * @param g defines the green component (between 0 and 1, default is 0)
  1381. * @param b defines the blue component (between 0 and 1, default is 0)
  1382. */
  1383. function Color3(
  1384. /**
  1385. * Defines the red component (between 0 and 1, default is 0)
  1386. */
  1387. r,
  1388. /**
  1389. * Defines the green component (between 0 and 1, default is 0)
  1390. */
  1391. g,
  1392. /**
  1393. * Defines the blue component (between 0 and 1, default is 0)
  1394. */
  1395. b) {
  1396. if (r === void 0) { r = 0; }
  1397. if (g === void 0) { g = 0; }
  1398. if (b === void 0) { b = 0; }
  1399. this.r = r;
  1400. this.g = g;
  1401. this.b = b;
  1402. }
  1403. /**
  1404. * Creates a string with the Color3 current values
  1405. * @returns the string representation of the Color3 object
  1406. */
  1407. Color3.prototype.toString = function () {
  1408. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + "}";
  1409. };
  1410. /**
  1411. * Returns the string "Color3"
  1412. * @returns "Color3"
  1413. */
  1414. Color3.prototype.getClassName = function () {
  1415. return "Color3";
  1416. };
  1417. /**
  1418. * Compute the Color3 hash code
  1419. * @returns an unique number that can be used to hash Color3 objects
  1420. */
  1421. Color3.prototype.getHashCode = function () {
  1422. var hash = this.r || 0;
  1423. hash = (hash * 397) ^ (this.g || 0);
  1424. hash = (hash * 397) ^ (this.b || 0);
  1425. return hash;
  1426. };
  1427. // Operators
  1428. /**
  1429. * Stores in the given array from the given starting index the red, green, blue values as successive elements
  1430. * @param array defines the array where to store the r,g,b components
  1431. * @param index defines an optional index in the target array to define where to start storing values
  1432. * @returns the current Color3 object
  1433. */
  1434. Color3.prototype.toArray = function (array, index) {
  1435. if (index === undefined) {
  1436. index = 0;
  1437. }
  1438. array[index] = this.r;
  1439. array[index + 1] = this.g;
  1440. array[index + 2] = this.b;
  1441. return this;
  1442. };
  1443. /**
  1444. * Returns a new {BABYLON.Color4} object from the current Color3 and the given alpha
  1445. * @param alpha defines the alpha component on the new {BABYLON.Color4} object (default is 1)
  1446. * @returns a new {BABYLON.Color4} object
  1447. */
  1448. Color3.prototype.toColor4 = function (alpha) {
  1449. if (alpha === void 0) { alpha = 1; }
  1450. return new Color4(this.r, this.g, this.b, alpha);
  1451. };
  1452. /**
  1453. * Returns a new array populated with 3 numeric elements : red, green and blue values
  1454. * @returns the new array
  1455. */
  1456. Color3.prototype.asArray = function () {
  1457. var result = new Array();
  1458. this.toArray(result, 0);
  1459. return result;
  1460. };
  1461. /**
  1462. * Returns the luminance value
  1463. * @returns a float value
  1464. */
  1465. Color3.prototype.toLuminance = function () {
  1466. return this.r * 0.3 + this.g * 0.59 + this.b * 0.11;
  1467. };
  1468. /**
  1469. * Multiply each Color3 rgb values by the given Color3 rgb values in a new Color3 object
  1470. * @param otherColor defines the second operand
  1471. * @returns the new Color3 object
  1472. */
  1473. Color3.prototype.multiply = function (otherColor) {
  1474. return new Color3(this.r * otherColor.r, this.g * otherColor.g, this.b * otherColor.b);
  1475. };
  1476. /**
  1477. * Multiply the rgb values of the Color3 and the given Color3 and stores the result in the object "result"
  1478. * @param otherColor defines the second operand
  1479. * @param result defines the Color3 object where to store the result
  1480. * @returns the current Color3
  1481. */
  1482. Color3.prototype.multiplyToRef = function (otherColor, result) {
  1483. result.r = this.r * otherColor.r;
  1484. result.g = this.g * otherColor.g;
  1485. result.b = this.b * otherColor.b;
  1486. return this;
  1487. };
  1488. /**
  1489. * Determines equality between Color3 objects
  1490. * @param otherColor defines the second operand
  1491. * @returns true if the rgb values are equal to the given ones
  1492. */
  1493. Color3.prototype.equals = function (otherColor) {
  1494. return otherColor && this.r === otherColor.r && this.g === otherColor.g && this.b === otherColor.b;
  1495. };
  1496. /**
  1497. * Determines equality between the current Color3 object and a set of r,b,g values
  1498. * @param r defines the red component to check
  1499. * @param g defines the green component to check
  1500. * @param b defines the blue component to check
  1501. * @returns true if the rgb values are equal to the given ones
  1502. */
  1503. Color3.prototype.equalsFloats = function (r, g, b) {
  1504. return this.r === r && this.g === g && this.b === b;
  1505. };
  1506. /**
  1507. * Multiplies in place each rgb value by scale
  1508. * @param scale defines the scaling factor
  1509. * @returns the updated Color3
  1510. */
  1511. Color3.prototype.scale = function (scale) {
  1512. return new Color3(this.r * scale, this.g * scale, this.b * scale);
  1513. };
  1514. /**
  1515. * Multiplies the rgb values by scale and stores the result into "result"
  1516. * @param scale defines the scaling factor
  1517. * @param result defines the Color3 object where to store the result
  1518. * @returns the unmodified current Color3
  1519. */
  1520. Color3.prototype.scaleToRef = function (scale, result) {
  1521. result.r = this.r * scale;
  1522. result.g = this.g * scale;
  1523. result.b = this.b * scale;
  1524. return this;
  1525. };
  1526. /**
  1527. * Scale the current Color3 values by a factor and add the result to a given Color3
  1528. * @param scale defines the scale factor
  1529. * @param result defines color to store the result into
  1530. * @returns the unmodified current Color3
  1531. */
  1532. Color3.prototype.scaleAndAddToRef = function (scale, result) {
  1533. result.r += this.r * scale;
  1534. result.g += this.g * scale;
  1535. result.b += this.b * scale;
  1536. return this;
  1537. };
  1538. /**
  1539. * Clamps the rgb values by the min and max values and stores the result into "result"
  1540. * @param min defines minimum clamping value (default is 0)
  1541. * @param max defines maximum clamping value (default is 1)
  1542. * @param result defines color to store the result into
  1543. * @returns the original Color3
  1544. */
  1545. Color3.prototype.clampToRef = function (min, max, result) {
  1546. if (min === void 0) { min = 0; }
  1547. if (max === void 0) { max = 1; }
  1548. result.r = BABYLON.Scalar.Clamp(this.r, min, max);
  1549. result.g = BABYLON.Scalar.Clamp(this.g, min, max);
  1550. result.b = BABYLON.Scalar.Clamp(this.b, min, max);
  1551. return this;
  1552. };
  1553. /**
  1554. * Creates a new Color3 set with the added values of the current Color3 and of the given one
  1555. * @param otherColor defines the second operand
  1556. * @returns the new Color3
  1557. */
  1558. Color3.prototype.add = function (otherColor) {
  1559. return new Color3(this.r + otherColor.r, this.g + otherColor.g, this.b + otherColor.b);
  1560. };
  1561. /**
  1562. * Stores the result of the addition of the current Color3 and given one rgb values into "result"
  1563. * @param otherColor defines the second operand
  1564. * @param result defines Color3 object to store the result into
  1565. * @returns the unmodified current Color3
  1566. */
  1567. Color3.prototype.addToRef = function (otherColor, result) {
  1568. result.r = this.r + otherColor.r;
  1569. result.g = this.g + otherColor.g;
  1570. result.b = this.b + otherColor.b;
  1571. return this;
  1572. };
  1573. /**
  1574. * Returns a new Color3 set with the subtracted values of the given one from the current Color3
  1575. * @param otherColor defines the second operand
  1576. * @returns the new Color3
  1577. */
  1578. Color3.prototype.subtract = function (otherColor) {
  1579. return new Color3(this.r - otherColor.r, this.g - otherColor.g, this.b - otherColor.b);
  1580. };
  1581. /**
  1582. * Stores the result of the subtraction of given one from the current Color3 rgb values into "result"
  1583. * @param otherColor defines the second operand
  1584. * @param result defines Color3 object to store the result into
  1585. * @returns the unmodified current Color3
  1586. */
  1587. Color3.prototype.subtractToRef = function (otherColor, result) {
  1588. result.r = this.r - otherColor.r;
  1589. result.g = this.g - otherColor.g;
  1590. result.b = this.b - otherColor.b;
  1591. return this;
  1592. };
  1593. /**
  1594. * Copy the current object
  1595. * @returns a new Color3 copied the current one
  1596. */
  1597. Color3.prototype.clone = function () {
  1598. return new Color3(this.r, this.g, this.b);
  1599. };
  1600. /**
  1601. * Copies the rgb values from the source in the current Color3
  1602. * @param source defines the source Color3 object
  1603. * @returns the updated Color3 object
  1604. */
  1605. Color3.prototype.copyFrom = function (source) {
  1606. this.r = source.r;
  1607. this.g = source.g;
  1608. this.b = source.b;
  1609. return this;
  1610. };
  1611. /**
  1612. * Updates the Color3 rgb values from the given floats
  1613. * @param r defines the red component to read from
  1614. * @param g defines the green component to read from
  1615. * @param b defines the blue component to read from
  1616. * @returns the current Color3 object
  1617. */
  1618. Color3.prototype.copyFromFloats = function (r, g, b) {
  1619. this.r = r;
  1620. this.g = g;
  1621. this.b = b;
  1622. return this;
  1623. };
  1624. /**
  1625. * Updates the Color3 rgb values from the given floats
  1626. * @param r defines the red component to read from
  1627. * @param g defines the green component to read from
  1628. * @param b defines the blue component to read from
  1629. * @returns the current Color3 object
  1630. */
  1631. Color3.prototype.set = function (r, g, b) {
  1632. return this.copyFromFloats(r, g, b);
  1633. };
  1634. /**
  1635. * Compute the Color3 hexadecimal code as a string
  1636. * @returns a string containing the hexadecimal representation of the Color3 object
  1637. */
  1638. Color3.prototype.toHexString = function () {
  1639. var intR = (this.r * 255) | 0;
  1640. var intG = (this.g * 255) | 0;
  1641. var intB = (this.b * 255) | 0;
  1642. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB);
  1643. };
  1644. /**
  1645. * Computes a new Color3 converted from the current one to linear space
  1646. * @returns a new Color3 object
  1647. */
  1648. Color3.prototype.toLinearSpace = function () {
  1649. var convertedColor = new Color3();
  1650. this.toLinearSpaceToRef(convertedColor);
  1651. return convertedColor;
  1652. };
  1653. /**
  1654. * Converts the Color3 values to linear space and stores the result in "convertedColor"
  1655. * @param convertedColor defines the Color3 object where to store the linear space version
  1656. * @returns the unmodified Color3
  1657. */
  1658. Color3.prototype.toLinearSpaceToRef = function (convertedColor) {
  1659. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  1660. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  1661. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  1662. return this;
  1663. };
  1664. /**
  1665. * Computes a new Color3 converted from the current one to gamma space
  1666. * @returns a new Color3 object
  1667. */
  1668. Color3.prototype.toGammaSpace = function () {
  1669. var convertedColor = new Color3();
  1670. this.toGammaSpaceToRef(convertedColor);
  1671. return convertedColor;
  1672. };
  1673. /**
  1674. * Converts the Color3 values to gamma space and stores the result in "convertedColor"
  1675. * @param convertedColor defines the Color3 object where to store the gamma space version
  1676. * @returns the unmodified Color3
  1677. */
  1678. Color3.prototype.toGammaSpaceToRef = function (convertedColor) {
  1679. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  1680. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  1681. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  1682. return this;
  1683. };
  1684. // Statics
  1685. /**
  1686. * Creates a new Color3 from the string containing valid hexadecimal values
  1687. * @param hex defines a string containing valid hexadecimal values
  1688. * @returns a new Color3 object
  1689. */
  1690. Color3.FromHexString = function (hex) {
  1691. if (hex.substring(0, 1) !== "#" || hex.length !== 7) {
  1692. return new Color3(0, 0, 0);
  1693. }
  1694. var r = parseInt(hex.substring(1, 3), 16);
  1695. var g = parseInt(hex.substring(3, 5), 16);
  1696. var b = parseInt(hex.substring(5, 7), 16);
  1697. return Color3.FromInts(r, g, b);
  1698. };
  1699. /**
  1700. * Creates a new Vector3 from the starting index of the given array
  1701. * @param array defines the source array
  1702. * @param offset defines an offset in the source array
  1703. * @returns a new Color3 object
  1704. */
  1705. Color3.FromArray = function (array, offset) {
  1706. if (offset === void 0) { offset = 0; }
  1707. return new Color3(array[offset], array[offset + 1], array[offset + 2]);
  1708. };
  1709. /**
  1710. * Creates a new Color3 from integer values (< 256)
  1711. * @param r defines the red component to read from (value between 0 and 255)
  1712. * @param g defines the green component to read from (value between 0 and 255)
  1713. * @param b defines the blue component to read from (value between 0 and 255)
  1714. * @returns a new Color3 object
  1715. */
  1716. Color3.FromInts = function (r, g, b) {
  1717. return new Color3(r / 255.0, g / 255.0, b / 255.0);
  1718. };
  1719. /**
  1720. * Creates a new Color3 with values linearly interpolated of "amount" between the start Color3 and the end Color3
  1721. * @param start defines the start Color3 value
  1722. * @param end defines the end Color3 value
  1723. * @param amount defines the gradient value between start and end
  1724. * @returns a new Color3 object
  1725. */
  1726. Color3.Lerp = function (start, end, amount) {
  1727. var r = start.r + ((end.r - start.r) * amount);
  1728. var g = start.g + ((end.g - start.g) * amount);
  1729. var b = start.b + ((end.b - start.b) * amount);
  1730. return new Color3(r, g, b);
  1731. };
  1732. /**
  1733. * Returns a Color3 value containing a red color
  1734. * @returns a new Color3 object
  1735. */
  1736. Color3.Red = function () { return new Color3(1, 0, 0); };
  1737. /**
  1738. * Returns a Color3 value containing a green color
  1739. * @returns a new Color3 object
  1740. */
  1741. Color3.Green = function () { return new Color3(0, 1, 0); };
  1742. /**
  1743. * Returns a Color3 value containing a blue color
  1744. * @returns a new Color3 object
  1745. */
  1746. Color3.Blue = function () { return new Color3(0, 0, 1); };
  1747. /**
  1748. * Returns a Color3 value containing a black color
  1749. * @returns a new Color3 object
  1750. */
  1751. Color3.Black = function () { return new Color3(0, 0, 0); };
  1752. /**
  1753. * Returns a Color3 value containing a white color
  1754. * @returns a new Color3 object
  1755. */
  1756. Color3.White = function () { return new Color3(1, 1, 1); };
  1757. /**
  1758. * Returns a Color3 value containing a purple color
  1759. * @returns a new Color3 object
  1760. */
  1761. Color3.Purple = function () { return new Color3(0.5, 0, 0.5); };
  1762. /**
  1763. * Returns a Color3 value containing a magenta color
  1764. * @returns a new Color3 object
  1765. */
  1766. Color3.Magenta = function () { return new Color3(1, 0, 1); };
  1767. /**
  1768. * Returns a Color3 value containing a yellow color
  1769. * @returns a new Color3 object
  1770. */
  1771. Color3.Yellow = function () { return new Color3(1, 1, 0); };
  1772. /**
  1773. * Returns a Color3 value containing a gray color
  1774. * @returns a new Color3 object
  1775. */
  1776. Color3.Gray = function () { return new Color3(0.5, 0.5, 0.5); };
  1777. /**
  1778. * Returns a Color3 value containing a teal color
  1779. * @returns a new Color3 object
  1780. */
  1781. Color3.Teal = function () { return new Color3(0, 1.0, 1.0); };
  1782. /**
  1783. * Returns a Color3 value containing a random color
  1784. * @returns a new Color3 object
  1785. */
  1786. Color3.Random = function () { return new Color3(Math.random(), Math.random(), Math.random()); };
  1787. return Color3;
  1788. }());
  1789. BABYLON.Color3 = Color3;
  1790. /**
  1791. * Class used to hold a RBGA color
  1792. */
  1793. var Color4 = /** @class */ (function () {
  1794. /**
  1795. * Creates a new Color4 object from red, green, blue values, all between 0 and 1
  1796. * @param r defines the red component (between 0 and 1, default is 0)
  1797. * @param g defines the green component (between 0 and 1, default is 0)
  1798. * @param b defines the blue component (between 0 and 1, default is 0)
  1799. * @param a defines the alpha component (between 0 and 1, default is 1)
  1800. */
  1801. function Color4(
  1802. /**
  1803. * Defines the red component (between 0 and 1, default is 0)
  1804. */
  1805. r,
  1806. /**
  1807. * Defines the green component (between 0 and 1, default is 0)
  1808. */
  1809. g,
  1810. /**
  1811. * Defines the blue component (between 0 and 1, default is 0)
  1812. */
  1813. b,
  1814. /**
  1815. * Defines the alpha component (between 0 and 1, default is 1)
  1816. */
  1817. a) {
  1818. if (r === void 0) { r = 0; }
  1819. if (g === void 0) { g = 0; }
  1820. if (b === void 0) { b = 0; }
  1821. if (a === void 0) { a = 1; }
  1822. this.r = r;
  1823. this.g = g;
  1824. this.b = b;
  1825. this.a = a;
  1826. }
  1827. // Operators
  1828. /**
  1829. * Adds in place the given Color4 values to the current Color4 object
  1830. * @param right defines the second operand
  1831. * @returns the current updated Color4 object
  1832. */
  1833. Color4.prototype.addInPlace = function (right) {
  1834. this.r += right.r;
  1835. this.g += right.g;
  1836. this.b += right.b;
  1837. this.a += right.a;
  1838. return this;
  1839. };
  1840. /**
  1841. * Creates a new array populated with 4 numeric elements : red, green, blue, alpha values
  1842. * @returns the new array
  1843. */
  1844. Color4.prototype.asArray = function () {
  1845. var result = new Array();
  1846. this.toArray(result, 0);
  1847. return result;
  1848. };
  1849. /**
  1850. * Stores from the starting index in the given array the Color4 successive values
  1851. * @param array defines the array where to store the r,g,b components
  1852. * @param index defines an optional index in the target array to define where to start storing values
  1853. * @returns the current Color4 object
  1854. */
  1855. Color4.prototype.toArray = function (array, index) {
  1856. if (index === undefined) {
  1857. index = 0;
  1858. }
  1859. array[index] = this.r;
  1860. array[index + 1] = this.g;
  1861. array[index + 2] = this.b;
  1862. array[index + 3] = this.a;
  1863. return this;
  1864. };
  1865. /**
  1866. * Creates a new Color4 set with the added values of the current Color4 and of the given one
  1867. * @param right defines the second operand
  1868. * @returns a new Color4 object
  1869. */
  1870. Color4.prototype.add = function (right) {
  1871. return new Color4(this.r + right.r, this.g + right.g, this.b + right.b, this.a + right.a);
  1872. };
  1873. /**
  1874. * Creates a new Color4 set with the subtracted values of the given one from the current Color4
  1875. * @param right defines the second operand
  1876. * @returns a new Color4 object
  1877. */
  1878. Color4.prototype.subtract = function (right) {
  1879. return new Color4(this.r - right.r, this.g - right.g, this.b - right.b, this.a - right.a);
  1880. };
  1881. /**
  1882. * Subtracts the given ones from the current Color4 values and stores the results in "result"
  1883. * @param right defines the second operand
  1884. * @param result defines the Color4 object where to store the result
  1885. * @returns the current Color4 object
  1886. */
  1887. Color4.prototype.subtractToRef = function (right, result) {
  1888. result.r = this.r - right.r;
  1889. result.g = this.g - right.g;
  1890. result.b = this.b - right.b;
  1891. result.a = this.a - right.a;
  1892. return this;
  1893. };
  1894. /**
  1895. * Creates a new Color4 with the current Color4 values multiplied by scale
  1896. * @param scale defines the scaling factor to apply
  1897. * @returns a new Color4 object
  1898. */
  1899. Color4.prototype.scale = function (scale) {
  1900. return new Color4(this.r * scale, this.g * scale, this.b * scale, this.a * scale);
  1901. };
  1902. /**
  1903. * Multiplies the current Color4 values by scale and stores the result in "result"
  1904. * @param scale defines the scaling factor to apply
  1905. * @param result defines the Color4 object where to store the result
  1906. * @returns the current unmodified Color4
  1907. */
  1908. Color4.prototype.scaleToRef = function (scale, result) {
  1909. result.r = this.r * scale;
  1910. result.g = this.g * scale;
  1911. result.b = this.b * scale;
  1912. result.a = this.a * scale;
  1913. return this;
  1914. };
  1915. /**
  1916. * Scale the current Color4 values by a factor and add the result to a given Color4
  1917. * @param scale defines the scale factor
  1918. * @param result defines the Color4 object where to store the result
  1919. * @returns the unmodified current Color4
  1920. */
  1921. Color4.prototype.scaleAndAddToRef = function (scale, result) {
  1922. result.r += this.r * scale;
  1923. result.g += this.g * scale;
  1924. result.b += this.b * scale;
  1925. result.a += this.a * scale;
  1926. return this;
  1927. };
  1928. /**
  1929. * Clamps the rgb values by the min and max values and stores the result into "result"
  1930. * @param min defines minimum clamping value (default is 0)
  1931. * @param max defines maximum clamping value (default is 1)
  1932. * @param result defines color to store the result into.
  1933. * @returns the cuurent Color4
  1934. */
  1935. Color4.prototype.clampToRef = function (min, max, result) {
  1936. if (min === void 0) { min = 0; }
  1937. if (max === void 0) { max = 1; }
  1938. result.r = BABYLON.Scalar.Clamp(this.r, min, max);
  1939. result.g = BABYLON.Scalar.Clamp(this.g, min, max);
  1940. result.b = BABYLON.Scalar.Clamp(this.b, min, max);
  1941. result.a = BABYLON.Scalar.Clamp(this.a, min, max);
  1942. return this;
  1943. };
  1944. /**
  1945. * Multipy an Color4 value by another and return a new Color4 object
  1946. * @param color defines the Color4 value to multiply by
  1947. * @returns a new Color4 object
  1948. */
  1949. Color4.prototype.multiply = function (color) {
  1950. return new Color4(this.r * color.r, this.g * color.g, this.b * color.b, this.a * color.a);
  1951. };
  1952. /**
  1953. * Multipy a Color4 value by another and push the result in a reference value
  1954. * @param color defines the Color4 value to multiply by
  1955. * @param result defines the Color4 to fill the result in
  1956. * @returns the result Color4
  1957. */
  1958. Color4.prototype.multiplyToRef = function (color, result) {
  1959. result.r = this.r * color.r;
  1960. result.g = this.g * color.g;
  1961. result.b = this.b * color.b;
  1962. result.a = this.a * color.a;
  1963. return result;
  1964. };
  1965. /**
  1966. * Creates a string with the Color4 current values
  1967. * @returns the string representation of the Color4 object
  1968. */
  1969. Color4.prototype.toString = function () {
  1970. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + " A:" + this.a + "}";
  1971. };
  1972. /**
  1973. * Returns the string "Color4"
  1974. * @returns "Color4"
  1975. */
  1976. Color4.prototype.getClassName = function () {
  1977. return "Color4";
  1978. };
  1979. /**
  1980. * Compute the Color4 hash code
  1981. * @returns an unique number that can be used to hash Color4 objects
  1982. */
  1983. Color4.prototype.getHashCode = function () {
  1984. var hash = this.r || 0;
  1985. hash = (hash * 397) ^ (this.g || 0);
  1986. hash = (hash * 397) ^ (this.b || 0);
  1987. hash = (hash * 397) ^ (this.a || 0);
  1988. return hash;
  1989. };
  1990. /**
  1991. * Creates a new Color4 copied from the current one
  1992. * @returns a new Color4 object
  1993. */
  1994. Color4.prototype.clone = function () {
  1995. return new Color4(this.r, this.g, this.b, this.a);
  1996. };
  1997. /**
  1998. * Copies the given Color4 values into the current one
  1999. * @param source defines the source Color4 object
  2000. * @returns the current updated Color4 object
  2001. */
  2002. Color4.prototype.copyFrom = function (source) {
  2003. this.r = source.r;
  2004. this.g = source.g;
  2005. this.b = source.b;
  2006. this.a = source.a;
  2007. return this;
  2008. };
  2009. /**
  2010. * Copies the given float values into the current one
  2011. * @param r defines the red component to read from
  2012. * @param g defines the green component to read from
  2013. * @param b defines the blue component to read from
  2014. * @param a defines the alpha component to read from
  2015. * @returns the current updated Color4 object
  2016. */
  2017. Color4.prototype.copyFromFloats = function (r, g, b, a) {
  2018. this.r = r;
  2019. this.g = g;
  2020. this.b = b;
  2021. this.a = a;
  2022. return this;
  2023. };
  2024. /**
  2025. * Copies the given float values into the current one
  2026. * @param r defines the red component to read from
  2027. * @param g defines the green component to read from
  2028. * @param b defines the blue component to read from
  2029. * @param a defines the alpha component to read from
  2030. * @returns the current updated Color4 object
  2031. */
  2032. Color4.prototype.set = function (r, g, b, a) {
  2033. return this.copyFromFloats(r, g, b, a);
  2034. };
  2035. /**
  2036. * Compute the Color4 hexadecimal code as a string
  2037. * @returns a string containing the hexadecimal representation of the Color4 object
  2038. */
  2039. Color4.prototype.toHexString = function () {
  2040. var intR = (this.r * 255) | 0;
  2041. var intG = (this.g * 255) | 0;
  2042. var intB = (this.b * 255) | 0;
  2043. var intA = (this.a * 255) | 0;
  2044. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB) + BABYLON.Scalar.ToHex(intA);
  2045. };
  2046. /**
  2047. * Computes a new Color4 converted from the current one to linear space
  2048. * @returns a new Color4 object
  2049. */
  2050. Color4.prototype.toLinearSpace = function () {
  2051. var convertedColor = new Color4();
  2052. this.toLinearSpaceToRef(convertedColor);
  2053. return convertedColor;
  2054. };
  2055. /**
  2056. * Converts the Color4 values to linear space and stores the result in "convertedColor"
  2057. * @param convertedColor defines the Color4 object where to store the linear space version
  2058. * @returns the unmodified Color4
  2059. */
  2060. Color4.prototype.toLinearSpaceToRef = function (convertedColor) {
  2061. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  2062. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  2063. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  2064. convertedColor.a = this.a;
  2065. return this;
  2066. };
  2067. /**
  2068. * Computes a new Color4 converted from the current one to gamma space
  2069. * @returns a new Color4 object
  2070. */
  2071. Color4.prototype.toGammaSpace = function () {
  2072. var convertedColor = new Color4();
  2073. this.toGammaSpaceToRef(convertedColor);
  2074. return convertedColor;
  2075. };
  2076. /**
  2077. * Converts the Color4 values to gamma space and stores the result in "convertedColor"
  2078. * @param convertedColor defines the Color4 object where to store the gamma space version
  2079. * @returns the unmodified Color4
  2080. */
  2081. Color4.prototype.toGammaSpaceToRef = function (convertedColor) {
  2082. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  2083. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  2084. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  2085. convertedColor.a = this.a;
  2086. return this;
  2087. };
  2088. // Statics
  2089. /**
  2090. * Creates a new Color4 from the string containing valid hexadecimal values
  2091. * @param hex defines a string containing valid hexadecimal values
  2092. * @returns a new Color4 object
  2093. */
  2094. Color4.FromHexString = function (hex) {
  2095. if (hex.substring(0, 1) !== "#" || hex.length !== 9) {
  2096. return new Color4(0.0, 0.0, 0.0, 0.0);
  2097. }
  2098. var r = parseInt(hex.substring(1, 3), 16);
  2099. var g = parseInt(hex.substring(3, 5), 16);
  2100. var b = parseInt(hex.substring(5, 7), 16);
  2101. var a = parseInt(hex.substring(7, 9), 16);
  2102. return Color4.FromInts(r, g, b, a);
  2103. };
  2104. /**
  2105. * Creates a new Color4 object set with the linearly interpolated values of "amount" between the left Color4 object and the right Color4 object
  2106. * @param left defines the start value
  2107. * @param right defines the end value
  2108. * @param amount defines the gradient factor
  2109. * @returns a new Color4 object
  2110. */
  2111. Color4.Lerp = function (left, right, amount) {
  2112. var result = new Color4(0.0, 0.0, 0.0, 0.0);
  2113. Color4.LerpToRef(left, right, amount, result);
  2114. return result;
  2115. };
  2116. /**
  2117. * Set the given "result" with the linearly interpolated values of "amount" between the left Color4 object and the right Color4 object
  2118. * @param left defines the start value
  2119. * @param right defines the end value
  2120. * @param amount defines the gradient factor
  2121. * @param result defines the Color4 object where to store data
  2122. */
  2123. Color4.LerpToRef = function (left, right, amount, result) {
  2124. result.r = left.r + (right.r - left.r) * amount;
  2125. result.g = left.g + (right.g - left.g) * amount;
  2126. result.b = left.b + (right.b - left.b) * amount;
  2127. result.a = left.a + (right.a - left.a) * amount;
  2128. };
  2129. /**
  2130. * Creates a new Color4 from the starting index element of the given array
  2131. * @param array defines the source array to read from
  2132. * @param offset defines the offset in the source array
  2133. * @returns a new Color4 object
  2134. */
  2135. Color4.FromArray = function (array, offset) {
  2136. if (offset === void 0) { offset = 0; }
  2137. return new Color4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  2138. };
  2139. /**
  2140. * Creates a new Color3 from integer values (< 256)
  2141. * @param r defines the red component to read from (value between 0 and 255)
  2142. * @param g defines the green component to read from (value between 0 and 255)
  2143. * @param b defines the blue component to read from (value between 0 and 255)
  2144. * @param a defines the alpha component to read from (value between 0 and 255)
  2145. * @returns a new Color3 object
  2146. */
  2147. Color4.FromInts = function (r, g, b, a) {
  2148. return new Color4(r / 255.0, g / 255.0, b / 255.0, a / 255.0);
  2149. };
  2150. /**
  2151. * Check the content of a given array and convert it to an array containing RGBA data
  2152. * If the original array was already containing count * 4 values then it is returned directly
  2153. * @param colors defines the array to check
  2154. * @param count defines the number of RGBA data to expect
  2155. * @returns an array containing count * 4 values (RGBA)
  2156. */
  2157. Color4.CheckColors4 = function (colors, count) {
  2158. // Check if color3 was used
  2159. if (colors.length === count * 3) {
  2160. var colors4 = [];
  2161. for (var index = 0; index < colors.length; index += 3) {
  2162. var newIndex = (index / 3) * 4;
  2163. colors4[newIndex] = colors[index];
  2164. colors4[newIndex + 1] = colors[index + 1];
  2165. colors4[newIndex + 2] = colors[index + 2];
  2166. colors4[newIndex + 3] = 1.0;
  2167. }
  2168. return colors4;
  2169. }
  2170. return colors;
  2171. };
  2172. return Color4;
  2173. }());
  2174. BABYLON.Color4 = Color4;
  2175. /**
  2176. * Class representing a vector containing 2 coordinates
  2177. */
  2178. var Vector2 = /** @class */ (function () {
  2179. /**
  2180. * Creates a new Vector2 from the given x and y coordinates
  2181. * @param x defines the first coordinate
  2182. * @param y defines the second coordinate
  2183. */
  2184. function Vector2(
  2185. /** defines the first coordinate */
  2186. x,
  2187. /** defines the second coordinate */
  2188. y) {
  2189. this.x = x;
  2190. this.y = y;
  2191. }
  2192. /**
  2193. * Gets a string with the Vector2 coordinates
  2194. * @returns a string with the Vector2 coordinates
  2195. */
  2196. Vector2.prototype.toString = function () {
  2197. return "{X: " + this.x + " Y:" + this.y + "}";
  2198. };
  2199. /**
  2200. * Gets class name
  2201. * @returns the string "Vector2"
  2202. */
  2203. Vector2.prototype.getClassName = function () {
  2204. return "Vector2";
  2205. };
  2206. /**
  2207. * Gets current vector hash code
  2208. * @returns the Vector2 hash code as a number
  2209. */
  2210. Vector2.prototype.getHashCode = function () {
  2211. var hash = this.x || 0;
  2212. hash = (hash * 397) ^ (this.y || 0);
  2213. return hash;
  2214. };
  2215. // Operators
  2216. /**
  2217. * Sets the Vector2 coordinates in the given array or Float32Array from the given index.
  2218. * @param array defines the source array
  2219. * @param index defines the offset in source array
  2220. * @returns the current Vector2
  2221. */
  2222. Vector2.prototype.toArray = function (array, index) {
  2223. if (index === void 0) { index = 0; }
  2224. array[index] = this.x;
  2225. array[index + 1] = this.y;
  2226. return this;
  2227. };
  2228. /**
  2229. * Copy the current vector to an array
  2230. * @returns a new array with 2 elements: the Vector2 coordinates.
  2231. */
  2232. Vector2.prototype.asArray = function () {
  2233. var result = new Array();
  2234. this.toArray(result, 0);
  2235. return result;
  2236. };
  2237. /**
  2238. * Sets the Vector2 coordinates with the given Vector2 coordinates
  2239. * @param source defines the source Vector2
  2240. * @returns the current updated Vector2
  2241. */
  2242. Vector2.prototype.copyFrom = function (source) {
  2243. this.x = source.x;
  2244. this.y = source.y;
  2245. return this;
  2246. };
  2247. /**
  2248. * Sets the Vector2 coordinates with the given floats
  2249. * @param x defines the first coordinate
  2250. * @param y defines the second coordinate
  2251. * @returns the current updated Vector2
  2252. */
  2253. Vector2.prototype.copyFromFloats = function (x, y) {
  2254. this.x = x;
  2255. this.y = y;
  2256. return this;
  2257. };
  2258. /**
  2259. * Sets the Vector2 coordinates with the given floats
  2260. * @param x defines the first coordinate
  2261. * @param y defines the second coordinate
  2262. * @returns the current updated Vector2
  2263. */
  2264. Vector2.prototype.set = function (x, y) {
  2265. return this.copyFromFloats(x, y);
  2266. };
  2267. /**
  2268. * Add another vector with the current one
  2269. * @param otherVector defines the other vector
  2270. * @returns a new Vector2 set with the addition of the current Vector2 and the given one coordinates
  2271. */
  2272. Vector2.prototype.add = function (otherVector) {
  2273. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  2274. };
  2275. /**
  2276. * Sets the "result" coordinates with the addition of the current Vector2 and the given one coordinates
  2277. * @param otherVector defines the other vector
  2278. * @param result defines the target vector
  2279. * @returns the unmodified current Vector2
  2280. */
  2281. Vector2.prototype.addToRef = function (otherVector, result) {
  2282. result.x = this.x + otherVector.x;
  2283. result.y = this.y + otherVector.y;
  2284. return this;
  2285. };
  2286. /**
  2287. * Set the Vector2 coordinates by adding the given Vector2 coordinates
  2288. * @param otherVector defines the other vector
  2289. * @returns the current updated Vector2
  2290. */
  2291. Vector2.prototype.addInPlace = function (otherVector) {
  2292. this.x += otherVector.x;
  2293. this.y += otherVector.y;
  2294. return this;
  2295. };
  2296. /**
  2297. * Gets a new Vector2 by adding the current Vector2 coordinates to the given Vector3 x, y coordinates
  2298. * @param otherVector defines the other vector
  2299. * @returns a new Vector2
  2300. */
  2301. Vector2.prototype.addVector3 = function (otherVector) {
  2302. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  2303. };
  2304. /**
  2305. * Gets a new Vector2 set with the subtracted coordinates of the given one from the current Vector2
  2306. * @param otherVector defines the other vector
  2307. * @returns a new Vector2
  2308. */
  2309. Vector2.prototype.subtract = function (otherVector) {
  2310. return new Vector2(this.x - otherVector.x, this.y - otherVector.y);
  2311. };
  2312. /**
  2313. * Sets the "result" coordinates with the subtraction of the given one from the current Vector2 coordinates.
  2314. * @param otherVector defines the other vector
  2315. * @param result defines the target vector
  2316. * @returns the unmodified current Vector2
  2317. */
  2318. Vector2.prototype.subtractToRef = function (otherVector, result) {
  2319. result.x = this.x - otherVector.x;
  2320. result.y = this.y - otherVector.y;
  2321. return this;
  2322. };
  2323. /**
  2324. * Sets the current Vector2 coordinates by subtracting from it the given one coordinates
  2325. * @param otherVector defines the other vector
  2326. * @returns the current updated Vector2
  2327. */
  2328. Vector2.prototype.subtractInPlace = function (otherVector) {
  2329. this.x -= otherVector.x;
  2330. this.y -= otherVector.y;
  2331. return this;
  2332. };
  2333. /**
  2334. * Multiplies in place the current Vector2 coordinates by the given ones
  2335. * @param otherVector defines the other vector
  2336. * @returns the current updated Vector2
  2337. */
  2338. Vector2.prototype.multiplyInPlace = function (otherVector) {
  2339. this.x *= otherVector.x;
  2340. this.y *= otherVector.y;
  2341. return this;
  2342. };
  2343. /**
  2344. * Returns a new Vector2 set with the multiplication of the current Vector2 and the given one coordinates
  2345. * @param otherVector defines the other vector
  2346. * @returns a new Vector2
  2347. */
  2348. Vector2.prototype.multiply = function (otherVector) {
  2349. return new Vector2(this.x * otherVector.x, this.y * otherVector.y);
  2350. };
  2351. /**
  2352. * Sets "result" coordinates with the multiplication of the current Vector2 and the given one coordinates
  2353. * @param otherVector defines the other vector
  2354. * @param result defines the target vector
  2355. * @returns the unmodified current Vector2
  2356. */
  2357. Vector2.prototype.multiplyToRef = function (otherVector, result) {
  2358. result.x = this.x * otherVector.x;
  2359. result.y = this.y * otherVector.y;
  2360. return this;
  2361. };
  2362. /**
  2363. * Gets a new Vector2 set with the Vector2 coordinates multiplied by the given floats
  2364. * @param x defines the first coordinate
  2365. * @param y defines the second coordinate
  2366. * @returns a new Vector2
  2367. */
  2368. Vector2.prototype.multiplyByFloats = function (x, y) {
  2369. return new Vector2(this.x * x, this.y * y);
  2370. };
  2371. /**
  2372. * Returns a new Vector2 set with the Vector2 coordinates divided by the given one coordinates
  2373. * @param otherVector defines the other vector
  2374. * @returns a new Vector2
  2375. */
  2376. Vector2.prototype.divide = function (otherVector) {
  2377. return new Vector2(this.x / otherVector.x, this.y / otherVector.y);
  2378. };
  2379. /**
  2380. * Sets the "result" coordinates with the Vector2 divided by the given one coordinates
  2381. * @param otherVector defines the other vector
  2382. * @param result defines the target vector
  2383. * @returns the unmodified current Vector2
  2384. */
  2385. Vector2.prototype.divideToRef = function (otherVector, result) {
  2386. result.x = this.x / otherVector.x;
  2387. result.y = this.y / otherVector.y;
  2388. return this;
  2389. };
  2390. /**
  2391. * Divides the current Vector3 coordinates by the given ones
  2392. * @param otherVector defines the other vector
  2393. * @returns the current updated Vector2
  2394. */
  2395. Vector2.prototype.divideInPlace = function (otherVector) {
  2396. return this.divideToRef(otherVector, this);
  2397. };
  2398. /**
  2399. * Gets a new Vector2 with current Vector2 negated coordinates
  2400. * @returns a new Vector2
  2401. */
  2402. Vector2.prototype.negate = function () {
  2403. return new Vector2(-this.x, -this.y);
  2404. };
  2405. /**
  2406. * Multiply the Vector2 coordinates by scale
  2407. * @param scale defines the scaling factor
  2408. * @returns the current updated Vector2
  2409. */
  2410. Vector2.prototype.scaleInPlace = function (scale) {
  2411. this.x *= scale;
  2412. this.y *= scale;
  2413. return this;
  2414. };
  2415. /**
  2416. * Returns a new Vector2 scaled by "scale" from the current Vector2
  2417. * @param scale defines the scaling factor
  2418. * @returns a new Vector2
  2419. */
  2420. Vector2.prototype.scale = function (scale) {
  2421. var result = new Vector2(0, 0);
  2422. this.scaleToRef(scale, result);
  2423. return result;
  2424. };
  2425. /**
  2426. * Scale the current Vector2 values by a factor to a given Vector2
  2427. * @param scale defines the scale factor
  2428. * @param result defines the Vector2 object where to store the result
  2429. * @returns the unmodified current Vector2
  2430. */
  2431. Vector2.prototype.scaleToRef = function (scale, result) {
  2432. result.x = this.x * scale;
  2433. result.y = this.y * scale;
  2434. return this;
  2435. };
  2436. /**
  2437. * Scale the current Vector2 values by a factor and add the result to a given Vector2
  2438. * @param scale defines the scale factor
  2439. * @param result defines the Vector2 object where to store the result
  2440. * @returns the unmodified current Vector2
  2441. */
  2442. Vector2.prototype.scaleAndAddToRef = function (scale, result) {
  2443. result.x += this.x * scale;
  2444. result.y += this.y * scale;
  2445. return this;
  2446. };
  2447. /**
  2448. * Gets a boolean if two vectors are equals
  2449. * @param otherVector defines the other vector
  2450. * @returns true if the given vector coordinates strictly equal the current Vector2 ones
  2451. */
  2452. Vector2.prototype.equals = function (otherVector) {
  2453. return otherVector && this.x === otherVector.x && this.y === otherVector.y;
  2454. };
  2455. /**
  2456. * Gets a boolean if two vectors are equals (using an epsilon value)
  2457. * @param otherVector defines the other vector
  2458. * @param epsilon defines the minimal distance to consider equality
  2459. * @returns true if the given vector coordinates are close to the current ones by a distance of epsilon.
  2460. */
  2461. Vector2.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  2462. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  2463. return otherVector && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon) && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon);
  2464. };
  2465. // Properties
  2466. /**
  2467. * Gets the length of the vector
  2468. * @returns the vector length (float)
  2469. */
  2470. Vector2.prototype.length = function () {
  2471. return Math.sqrt(this.x * this.x + this.y * this.y);
  2472. };
  2473. /**
  2474. * Gets the vector squared length
  2475. * @returns the vector squared length (float)
  2476. */
  2477. Vector2.prototype.lengthSquared = function () {
  2478. return (this.x * this.x + this.y * this.y);
  2479. };
  2480. // Methods
  2481. /**
  2482. * Normalize the vector
  2483. * @returns the current updated Vector2
  2484. */
  2485. Vector2.prototype.normalize = function () {
  2486. var len = this.length();
  2487. if (len === 0)
  2488. return this;
  2489. var num = 1.0 / len;
  2490. this.x *= num;
  2491. this.y *= num;
  2492. return this;
  2493. };
  2494. /**
  2495. * Gets a new Vector2 copied from the Vector2
  2496. * @returns a new Vector2
  2497. */
  2498. Vector2.prototype.clone = function () {
  2499. return new Vector2(this.x, this.y);
  2500. };
  2501. // Statics
  2502. /**
  2503. * Gets a new Vector2(0, 0)
  2504. * @returns a new Vector2
  2505. */
  2506. Vector2.Zero = function () {
  2507. return new Vector2(0, 0);
  2508. };
  2509. /**
  2510. * Gets a new Vector2(1, 1)
  2511. * @returns a new Vector2
  2512. */
  2513. Vector2.One = function () {
  2514. return new Vector2(1, 1);
  2515. };
  2516. /**
  2517. * Gets a new Vector2 set from the given index element of the given array
  2518. * @param array defines the data source
  2519. * @param offset defines the offset in the data source
  2520. * @returns a new Vector2
  2521. */
  2522. Vector2.FromArray = function (array, offset) {
  2523. if (offset === void 0) { offset = 0; }
  2524. return new Vector2(array[offset], array[offset + 1]);
  2525. };
  2526. /**
  2527. * Sets "result" from the given index element of the given array
  2528. * @param array defines the data source
  2529. * @param offset defines the offset in the data source
  2530. * @param result defines the target vector
  2531. */
  2532. Vector2.FromArrayToRef = function (array, offset, result) {
  2533. result.x = array[offset];
  2534. result.y = array[offset + 1];
  2535. };
  2536. /**
  2537. * Gets a new Vector2 located for "amount" (float) on the CatmullRom spline defined by the given four Vector2
  2538. * @param value1 defines 1st point of control
  2539. * @param value2 defines 2nd point of control
  2540. * @param value3 defines 3rd point of control
  2541. * @param value4 defines 4th point of control
  2542. * @param amount defines the interpolation factor
  2543. * @returns a new Vector2
  2544. */
  2545. Vector2.CatmullRom = function (value1, value2, value3, value4, amount) {
  2546. var squared = amount * amount;
  2547. var cubed = amount * squared;
  2548. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  2549. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  2550. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  2551. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  2552. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  2553. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  2554. return new Vector2(x, y);
  2555. };
  2556. /**
  2557. * 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".
  2558. * If a coordinate of "value" is lower than "min" coordinates, the returned Vector2 is given this "min" coordinate.
  2559. * If a coordinate of "value" is greater than "max" coordinates, the returned Vector2 is given this "max" coordinate
  2560. * @param value defines the value to clamp
  2561. * @param min defines the lower limit
  2562. * @param max defines the upper limit
  2563. * @returns a new Vector2
  2564. */
  2565. Vector2.Clamp = function (value, min, max) {
  2566. var x = value.x;
  2567. x = (x > max.x) ? max.x : x;
  2568. x = (x < min.x) ? min.x : x;
  2569. var y = value.y;
  2570. y = (y > max.y) ? max.y : y;
  2571. y = (y < min.y) ? min.y : y;
  2572. return new Vector2(x, y);
  2573. };
  2574. /**
  2575. * Returns a new Vector2 located for "amount" (float) on the Hermite spline defined by the vectors "value1", "value3", "tangent1", "tangent2"
  2576. * @param value1 defines the 1st control point
  2577. * @param tangent1 defines the outgoing tangent
  2578. * @param value2 defines the 2nd control point
  2579. * @param tangent2 defines the incoming tangent
  2580. * @param amount defines the interpolation factor
  2581. * @returns a new Vector2
  2582. */
  2583. Vector2.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  2584. var squared = amount * amount;
  2585. var cubed = amount * squared;
  2586. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  2587. var part2 = (-2.0 * cubed) + (3.0 * squared);
  2588. var part3 = (cubed - (2.0 * squared)) + amount;
  2589. var part4 = cubed - squared;
  2590. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  2591. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  2592. return new Vector2(x, y);
  2593. };
  2594. /**
  2595. * Returns a new Vector2 located for "amount" (float) on the linear interpolation between the vector "start" adn the vector "end".
  2596. * @param start defines the start vector
  2597. * @param end defines the end vector
  2598. * @param amount defines the interpolation factor
  2599. * @returns a new Vector2
  2600. */
  2601. Vector2.Lerp = function (start, end, amount) {
  2602. var x = start.x + ((end.x - start.x) * amount);
  2603. var y = start.y + ((end.y - start.y) * amount);
  2604. return new Vector2(x, y);
  2605. };
  2606. /**
  2607. * Gets the dot product of the vector "left" and the vector "right"
  2608. * @param left defines first vector
  2609. * @param right defines second vector
  2610. * @returns the dot product (float)
  2611. */
  2612. Vector2.Dot = function (left, right) {
  2613. return left.x * right.x + left.y * right.y;
  2614. };
  2615. /**
  2616. * Returns a new Vector2 equal to the normalized given vector
  2617. * @param vector defines the vector to normalize
  2618. * @returns a new Vector2
  2619. */
  2620. Vector2.Normalize = function (vector) {
  2621. var newVector = vector.clone();
  2622. newVector.normalize();
  2623. return newVector;
  2624. };
  2625. /**
  2626. * Gets a new Vector2 set with the minimal coordinate values from the "left" and "right" vectors
  2627. * @param left defines 1st vector
  2628. * @param right defines 2nd vector
  2629. * @returns a new Vector2
  2630. */
  2631. Vector2.Minimize = function (left, right) {
  2632. var x = (left.x < right.x) ? left.x : right.x;
  2633. var y = (left.y < right.y) ? left.y : right.y;
  2634. return new Vector2(x, y);
  2635. };
  2636. /**
  2637. * Gets a new Vecto2 set with the maximal coordinate values from the "left" and "right" vectors
  2638. * @param left defines 1st vector
  2639. * @param right defines 2nd vector
  2640. * @returns a new Vector2
  2641. */
  2642. Vector2.Maximize = function (left, right) {
  2643. var x = (left.x > right.x) ? left.x : right.x;
  2644. var y = (left.y > right.y) ? left.y : right.y;
  2645. return new Vector2(x, y);
  2646. };
  2647. /**
  2648. * Gets a new Vector2 set with the transformed coordinates of the given vector by the given transformation matrix
  2649. * @param vector defines the vector to transform
  2650. * @param transformation defines the matrix to apply
  2651. * @returns a new Vector2
  2652. */
  2653. Vector2.Transform = function (vector, transformation) {
  2654. var r = Vector2.Zero();
  2655. Vector2.TransformToRef(vector, transformation, r);
  2656. return r;
  2657. };
  2658. /**
  2659. * Transforms the given vector coordinates by the given transformation matrix and stores the result in the vector "result" coordinates
  2660. * @param vector defines the vector to transform
  2661. * @param transformation defines the matrix to apply
  2662. * @param result defines the target vector
  2663. */
  2664. Vector2.TransformToRef = function (vector, transformation, result) {
  2665. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + transformation.m[12];
  2666. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + transformation.m[13];
  2667. result.x = x;
  2668. result.y = y;
  2669. };
  2670. /**
  2671. * Determines if a given vector is included in a triangle
  2672. * @param p defines the vector to test
  2673. * @param p0 defines 1st triangle point
  2674. * @param p1 defines 2nd triangle point
  2675. * @param p2 defines 3rd triangle point
  2676. * @returns true if the point "p" is in the triangle defined by the vertors "p0", "p1", "p2"
  2677. */
  2678. Vector2.PointInTriangle = function (p, p0, p1, p2) {
  2679. var a = 1 / 2 * (-p1.y * p2.x + p0.y * (-p1.x + p2.x) + p0.x * (p1.y - p2.y) + p1.x * p2.y);
  2680. var sign = a < 0 ? -1 : 1;
  2681. var s = (p0.y * p2.x - p0.x * p2.y + (p2.y - p0.y) * p.x + (p0.x - p2.x) * p.y) * sign;
  2682. var t = (p0.x * p1.y - p0.y * p1.x + (p0.y - p1.y) * p.x + (p1.x - p0.x) * p.y) * sign;
  2683. return s > 0 && t > 0 && (s + t) < 2 * a * sign;
  2684. };
  2685. /**
  2686. * Gets the distance between the vectors "value1" and "value2"
  2687. * @param value1 defines first vector
  2688. * @param value2 defines second vector
  2689. * @returns the distance between vectors
  2690. */
  2691. Vector2.Distance = function (value1, value2) {
  2692. return Math.sqrt(Vector2.DistanceSquared(value1, value2));
  2693. };
  2694. /**
  2695. * Returns the squared distance between the vectors "value1" and "value2"
  2696. * @param value1 defines first vector
  2697. * @param value2 defines second vector
  2698. * @returns the squared distance between vectors
  2699. */
  2700. Vector2.DistanceSquared = function (value1, value2) {
  2701. var x = value1.x - value2.x;
  2702. var y = value1.y - value2.y;
  2703. return (x * x) + (y * y);
  2704. };
  2705. /**
  2706. * Gets a new Vector2 located at the center of the vectors "value1" and "value2"
  2707. * @param value1 defines first vector
  2708. * @param value2 defines second vector
  2709. * @returns a new Vector2
  2710. */
  2711. Vector2.Center = function (value1, value2) {
  2712. var center = value1.add(value2);
  2713. center.scaleInPlace(0.5);
  2714. return center;
  2715. };
  2716. /**
  2717. * Gets the shortest distance (float) between the point "p" and the segment defined by the two points "segA" and "segB".
  2718. * @param p defines the middle point
  2719. * @param segA defines one point of the segment
  2720. * @param segB defines the other point of the segment
  2721. * @returns the shortest distance
  2722. */
  2723. Vector2.DistanceOfPointFromSegment = function (p, segA, segB) {
  2724. var l2 = Vector2.DistanceSquared(segA, segB);
  2725. if (l2 === 0.0) {
  2726. return Vector2.Distance(p, segA);
  2727. }
  2728. var v = segB.subtract(segA);
  2729. var t = Math.max(0, Math.min(1, Vector2.Dot(p.subtract(segA), v) / l2));
  2730. var proj = segA.add(v.multiplyByFloats(t, t));
  2731. return Vector2.Distance(p, proj);
  2732. };
  2733. return Vector2;
  2734. }());
  2735. BABYLON.Vector2 = Vector2;
  2736. /**
  2737. * Classed used to store (x,y,z) vector representation
  2738. * A Vector3 is the main object used in 3D geometry
  2739. * It can represent etiher the coordinates of a point the space, either a direction
  2740. * Reminder: Babylon.js uses a left handed forward facing system
  2741. */
  2742. var Vector3 = /** @class */ (function () {
  2743. /**
  2744. * Creates a new Vector3 object from the given x, y, z (floats) coordinates.
  2745. * @param x defines the first coordinates (on X axis)
  2746. * @param y defines the second coordinates (on Y axis)
  2747. * @param z defines the third coordinates (on Z axis)
  2748. */
  2749. function Vector3(
  2750. /**
  2751. * Defines the first coordinates (on X axis)
  2752. */
  2753. x,
  2754. /**
  2755. * Defines the second coordinates (on Y axis)
  2756. */
  2757. y,
  2758. /**
  2759. * Defines the third coordinates (on Z axis)
  2760. */
  2761. z) {
  2762. this.x = x;
  2763. this.y = y;
  2764. this.z = z;
  2765. }
  2766. /**
  2767. * Creates a string representation of the Vector3
  2768. * @returns a string with the Vector3 coordinates.
  2769. */
  2770. Vector3.prototype.toString = function () {
  2771. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "}";
  2772. };
  2773. /**
  2774. * Gets the class name
  2775. * @returns the string "Vector3"
  2776. */
  2777. Vector3.prototype.getClassName = function () {
  2778. return "Vector3";
  2779. };
  2780. /**
  2781. * Creates the Vector3 hash code
  2782. * @returns a number which tends to be unique between Vector3 instances
  2783. */
  2784. Vector3.prototype.getHashCode = function () {
  2785. var hash = this.x || 0;
  2786. hash = (hash * 397) ^ (this.y || 0);
  2787. hash = (hash * 397) ^ (this.z || 0);
  2788. return hash;
  2789. };
  2790. // Operators
  2791. /**
  2792. * Creates an array containing three elements : the coordinates of the Vector3
  2793. * @returns a new array of numbers
  2794. */
  2795. Vector3.prototype.asArray = function () {
  2796. var result = [];
  2797. this.toArray(result, 0);
  2798. return result;
  2799. };
  2800. /**
  2801. * Populates the given array or Float32Array from the given index with the successive coordinates of the Vector3
  2802. * @param array defines the destination array
  2803. * @param index defines the offset in the destination array
  2804. * @returns the current Vector3
  2805. */
  2806. Vector3.prototype.toArray = function (array, index) {
  2807. if (index === void 0) { index = 0; }
  2808. array[index] = this.x;
  2809. array[index + 1] = this.y;
  2810. array[index + 2] = this.z;
  2811. return this;
  2812. };
  2813. /**
  2814. * Converts the current Vector3 into a quaternion (considering that the Vector3 contains Euler angles representation of a rotation)
  2815. * @returns a new Quaternion object, computed from the Vector3 coordinates
  2816. */
  2817. Vector3.prototype.toQuaternion = function () {
  2818. return BABYLON.Quaternion.RotationYawPitchRoll(this.x, this.y, this.z);
  2819. };
  2820. /**
  2821. * Adds the given vector to the current Vector3
  2822. * @param otherVector defines the second operand
  2823. * @returns the current updated Vector3
  2824. */
  2825. Vector3.prototype.addInPlace = function (otherVector) {
  2826. this.x += otherVector.x;
  2827. this.y += otherVector.y;
  2828. this.z += otherVector.z;
  2829. return this;
  2830. };
  2831. /**
  2832. * Gets a new Vector3, result of the addition the current Vector3 and the given vector
  2833. * @param otherVector defines the second operand
  2834. * @returns the resulting Vector3
  2835. */
  2836. Vector3.prototype.add = function (otherVector) {
  2837. return new Vector3(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);
  2838. };
  2839. /**
  2840. * Adds the current Vector3 to the given one and stores the result in the vector "result"
  2841. * @param otherVector defines the second operand
  2842. * @param result defines the Vector3 object where to store the result
  2843. * @returns the current Vector3
  2844. */
  2845. Vector3.prototype.addToRef = function (otherVector, result) {
  2846. result.x = this.x + otherVector.x;
  2847. result.y = this.y + otherVector.y;
  2848. result.z = this.z + otherVector.z;
  2849. return this;
  2850. };
  2851. /**
  2852. * Subtract the given vector from the current Vector3
  2853. * @param otherVector defines the second operand
  2854. * @returns the current updated Vector3
  2855. */
  2856. Vector3.prototype.subtractInPlace = function (otherVector) {
  2857. this.x -= otherVector.x;
  2858. this.y -= otherVector.y;
  2859. this.z -= otherVector.z;
  2860. return this;
  2861. };
  2862. /**
  2863. * Returns a new Vector3, result of the subtraction of the given vector from the current Vector3
  2864. * @param otherVector defines the second operand
  2865. * @returns the resulting Vector3
  2866. */
  2867. Vector3.prototype.subtract = function (otherVector) {
  2868. return new Vector3(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z);
  2869. };
  2870. /**
  2871. * Subtracts the given vector from the current Vector3 and stores the result in the vector "result".
  2872. * @param otherVector defines the second operand
  2873. * @param result defines the Vector3 object where to store the result
  2874. * @returns the current Vector3
  2875. */
  2876. Vector3.prototype.subtractToRef = function (otherVector, result) {
  2877. result.x = this.x - otherVector.x;
  2878. result.y = this.y - otherVector.y;
  2879. result.z = this.z - otherVector.z;
  2880. return this;
  2881. };
  2882. /**
  2883. * Returns a new Vector3 set with the subtraction of the given floats from the current Vector3 coordinates
  2884. * @param x defines the x coordinate of the operand
  2885. * @param y defines the y coordinate of the operand
  2886. * @param z defines the z coordinate of the operand
  2887. * @returns the resulting Vector3
  2888. */
  2889. Vector3.prototype.subtractFromFloats = function (x, y, z) {
  2890. return new Vector3(this.x - x, this.y - y, this.z - z);
  2891. };
  2892. /**
  2893. * Subtracts the given floats from the current Vector3 coordinates and set the given vector "result" with this result
  2894. * @param x defines the x coordinate of the operand
  2895. * @param y defines the y coordinate of the operand
  2896. * @param z defines the z coordinate of the operand
  2897. * @param result defines the Vector3 object where to store the result
  2898. * @returns the current Vector3
  2899. */
  2900. Vector3.prototype.subtractFromFloatsToRef = function (x, y, z, result) {
  2901. result.x = this.x - x;
  2902. result.y = this.y - y;
  2903. result.z = this.z - z;
  2904. return this;
  2905. };
  2906. /**
  2907. * Gets a new Vector3 set with the current Vector3 negated coordinates
  2908. * @returns a new Vector3
  2909. */
  2910. Vector3.prototype.negate = function () {
  2911. return new Vector3(-this.x, -this.y, -this.z);
  2912. };
  2913. /**
  2914. * Multiplies the Vector3 coordinates by the float "scale"
  2915. * @param scale defines the multiplier factor
  2916. * @returns the current updated Vector3
  2917. */
  2918. Vector3.prototype.scaleInPlace = function (scale) {
  2919. this.x *= scale;
  2920. this.y *= scale;
  2921. this.z *= scale;
  2922. return this;
  2923. };
  2924. /**
  2925. * Returns a new Vector3 set with the current Vector3 coordinates multiplied by the float "scale"
  2926. * @param scale defines the multiplier factor
  2927. * @returns a new Vector3
  2928. */
  2929. Vector3.prototype.scale = function (scale) {
  2930. return new Vector3(this.x * scale, this.y * scale, this.z * scale);
  2931. };
  2932. /**
  2933. * Multiplies the current Vector3 coordinates by the float "scale" and stores the result in the given vector "result" coordinates
  2934. * @param scale defines the multiplier factor
  2935. * @param result defines the Vector3 object where to store the result
  2936. * @returns the current Vector3
  2937. */
  2938. Vector3.prototype.scaleToRef = function (scale, result) {
  2939. result.x = this.x * scale;
  2940. result.y = this.y * scale;
  2941. result.z = this.z * scale;
  2942. return this;
  2943. };
  2944. /**
  2945. * Scale the current Vector3 values by a factor and add the result to a given Vector3
  2946. * @param scale defines the scale factor
  2947. * @param result defines the Vector3 object where to store the result
  2948. * @returns the unmodified current Vector3
  2949. */
  2950. Vector3.prototype.scaleAndAddToRef = function (scale, result) {
  2951. result.x += this.x * scale;
  2952. result.y += this.y * scale;
  2953. result.z += this.z * scale;
  2954. return this;
  2955. };
  2956. /**
  2957. * Returns true if the current Vector3 and the given vector coordinates are strictly equal
  2958. * @param otherVector defines the second operand
  2959. * @returns true if both vectors are equals
  2960. */
  2961. Vector3.prototype.equals = function (otherVector) {
  2962. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z;
  2963. };
  2964. /**
  2965. * Returns true if the current Vector3 and the given vector coordinates are distant less than epsilon
  2966. * @param otherVector defines the second operand
  2967. * @param epsilon defines the minimal distance to define values as equals
  2968. * @returns true if both vectors are distant less than epsilon
  2969. */
  2970. Vector3.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  2971. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  2972. 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);
  2973. };
  2974. /**
  2975. * Returns true if the current Vector3 coordinates equals the given floats
  2976. * @param x defines the x coordinate of the operand
  2977. * @param y defines the y coordinate of the operand
  2978. * @param z defines the z coordinate of the operand
  2979. * @returns true if both vectors are equals
  2980. */
  2981. Vector3.prototype.equalsToFloats = function (x, y, z) {
  2982. return this.x === x && this.y === y && this.z === z;
  2983. };
  2984. /**
  2985. * Multiplies the current Vector3 coordinates by the given ones
  2986. * @param otherVector defines the second operand
  2987. * @returns the current updated Vector3
  2988. */
  2989. Vector3.prototype.multiplyInPlace = function (otherVector) {
  2990. this.x *= otherVector.x;
  2991. this.y *= otherVector.y;
  2992. this.z *= otherVector.z;
  2993. return this;
  2994. };
  2995. /**
  2996. * Returns a new Vector3, result of the multiplication of the current Vector3 by the given vector
  2997. * @param otherVector defines the second operand
  2998. * @returns the new Vector3
  2999. */
  3000. Vector3.prototype.multiply = function (otherVector) {
  3001. return new Vector3(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z);
  3002. };
  3003. /**
  3004. * Multiplies the current Vector3 by the given one and stores the result in the given vector "result"
  3005. * @param otherVector defines the second operand
  3006. * @param result defines the Vector3 object where to store the result
  3007. * @returns the current Vector3
  3008. */
  3009. Vector3.prototype.multiplyToRef = function (otherVector, result) {
  3010. result.x = this.x * otherVector.x;
  3011. result.y = this.y * otherVector.y;
  3012. result.z = this.z * otherVector.z;
  3013. return this;
  3014. };
  3015. /**
  3016. * Returns a new Vector3 set with the result of the mulliplication of the current Vector3 coordinates by the given floats
  3017. * @param x defines the x coordinate of the operand
  3018. * @param y defines the y coordinate of the operand
  3019. * @param z defines the z coordinate of the operand
  3020. * @returns the new Vector3
  3021. */
  3022. Vector3.prototype.multiplyByFloats = function (x, y, z) {
  3023. return new Vector3(this.x * x, this.y * y, this.z * z);
  3024. };
  3025. /**
  3026. * Returns a new Vector3 set with the result of the division of the current Vector3 coordinates by the given ones
  3027. * @param otherVector defines the second operand
  3028. * @returns the new Vector3
  3029. */
  3030. Vector3.prototype.divide = function (otherVector) {
  3031. return new Vector3(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);
  3032. };
  3033. /**
  3034. * Divides the current Vector3 coordinates by the given ones and stores the result in the given vector "result"
  3035. * @param otherVector defines the second operand
  3036. * @param result defines the Vector3 object where to store the result
  3037. * @returns the current Vector3
  3038. */
  3039. Vector3.prototype.divideToRef = function (otherVector, result) {
  3040. result.x = this.x / otherVector.x;
  3041. result.y = this.y / otherVector.y;
  3042. result.z = this.z / otherVector.z;
  3043. return this;
  3044. };
  3045. /**
  3046. * Divides the current Vector3 coordinates by the given ones.
  3047. * @param otherVector defines the second operand
  3048. * @returns the current updated Vector3
  3049. */
  3050. Vector3.prototype.divideInPlace = function (otherVector) {
  3051. return this.divideToRef(otherVector, this);
  3052. };
  3053. /**
  3054. * Updates the current Vector3 with the minimal coordinate values between its and the given vector ones
  3055. * @param other defines the second operand
  3056. * @returns the current updated Vector3
  3057. */
  3058. Vector3.prototype.minimizeInPlace = function (other) {
  3059. if (other.x < this.x)
  3060. this.x = other.x;
  3061. if (other.y < this.y)
  3062. this.y = other.y;
  3063. if (other.z < this.z)
  3064. this.z = other.z;
  3065. return this;
  3066. };
  3067. /**
  3068. * Updates the current Vector3 with the maximal coordinate values between its and the given vector ones.
  3069. * @param other defines the second operand
  3070. * @returns the current updated Vector3
  3071. */
  3072. Vector3.prototype.maximizeInPlace = function (other) {
  3073. if (other.x > this.x)
  3074. this.x = other.x;
  3075. if (other.y > this.y)
  3076. this.y = other.y;
  3077. if (other.z > this.z)
  3078. this.z = other.z;
  3079. return this;
  3080. };
  3081. Object.defineProperty(Vector3.prototype, "isNonUniform", {
  3082. /**
  3083. * Gets a boolean indicating that the vector is non uniform meaning x, y or z are not all the same
  3084. */
  3085. get: function () {
  3086. var absX = Math.abs(this.x);
  3087. var absY = Math.abs(this.y);
  3088. if (absX !== absY) {
  3089. return true;
  3090. }
  3091. var absZ = Math.abs(this.z);
  3092. if (absX !== absZ) {
  3093. return true;
  3094. }
  3095. if (absY !== absZ) {
  3096. return true;
  3097. }
  3098. return false;
  3099. },
  3100. enumerable: true,
  3101. configurable: true
  3102. });
  3103. // Properties
  3104. /**
  3105. * Gets the length of the Vector3
  3106. * @returns the length of the Vecto3
  3107. */
  3108. Vector3.prototype.length = function () {
  3109. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  3110. };
  3111. /**
  3112. * Gets the squared length of the Vector3
  3113. * @returns squared length of the Vector3
  3114. */
  3115. Vector3.prototype.lengthSquared = function () {
  3116. return (this.x * this.x + this.y * this.y + this.z * this.z);
  3117. };
  3118. /**
  3119. * Normalize the current Vector3.
  3120. * Please note that this is an in place operation.
  3121. * @returns the current updated Vector3
  3122. */
  3123. Vector3.prototype.normalize = function () {
  3124. var len = this.length();
  3125. if (len === 0 || len === 1.0)
  3126. return this;
  3127. var num = 1.0 / len;
  3128. this.x *= num;
  3129. this.y *= num;
  3130. this.z *= num;
  3131. return this;
  3132. };
  3133. /**
  3134. * Normalize the current Vector3 to a new vector
  3135. * @returns the new Vector3
  3136. */
  3137. Vector3.prototype.normalizeToNew = function () {
  3138. var normalized = new Vector3(0, 0, 0);
  3139. this.normalizeToRef(normalized);
  3140. return normalized;
  3141. };
  3142. /**
  3143. * Normalize the current Vector3 to the reference
  3144. * @param reference define the Vector3 to update
  3145. * @returns the updated Vector3
  3146. */
  3147. Vector3.prototype.normalizeToRef = function (reference) {
  3148. var len = this.length();
  3149. if (len === 0 || len === 1.0) {
  3150. reference.set(this.x, this.y, this.z);
  3151. return reference;
  3152. }
  3153. var scale = 1.0 / len;
  3154. this.scaleToRef(scale, reference);
  3155. return reference;
  3156. };
  3157. /**
  3158. * Creates a new Vector3 copied from the current Vector3
  3159. * @returns the new Vector3
  3160. */
  3161. Vector3.prototype.clone = function () {
  3162. return new Vector3(this.x, this.y, this.z);
  3163. };
  3164. /**
  3165. * Copies the given vector coordinates to the current Vector3 ones
  3166. * @param source defines the source Vector3
  3167. * @returns the current updated Vector3
  3168. */
  3169. Vector3.prototype.copyFrom = function (source) {
  3170. this.x = source.x;
  3171. this.y = source.y;
  3172. this.z = source.z;
  3173. return this;
  3174. };
  3175. /**
  3176. * Copies the given floats to the current Vector3 coordinates
  3177. * @param x defines the x coordinate of the operand
  3178. * @param y defines the y coordinate of the operand
  3179. * @param z defines the z coordinate of the operand
  3180. * @returns the current updated Vector3
  3181. */
  3182. Vector3.prototype.copyFromFloats = function (x, y, z) {
  3183. this.x = x;
  3184. this.y = y;
  3185. this.z = z;
  3186. return this;
  3187. };
  3188. /**
  3189. * Copies the given floats to the current Vector3 coordinates
  3190. * @param x defines the x coordinate of the operand
  3191. * @param y defines the y coordinate of the operand
  3192. * @param z defines the z coordinate of the operand
  3193. * @returns the current updated Vector3
  3194. */
  3195. Vector3.prototype.set = function (x, y, z) {
  3196. return this.copyFromFloats(x, y, z);
  3197. };
  3198. // Statics
  3199. /**
  3200. * Get the clip factor between two vectors
  3201. * @param vector0 defines the first operand
  3202. * @param vector1 defines the second operand
  3203. * @param axis defines the axis to use
  3204. * @param size defines the size along the axis
  3205. * @returns the clip factor
  3206. */
  3207. Vector3.GetClipFactor = function (vector0, vector1, axis, size) {
  3208. var d0 = Vector3.Dot(vector0, axis) - size;
  3209. var d1 = Vector3.Dot(vector1, axis) - size;
  3210. var s = d0 / (d0 - d1);
  3211. return s;
  3212. };
  3213. /**
  3214. * Get angle between two vectors
  3215. * @param vector0 angle between vector0 and vector1
  3216. * @param vector1 angle between vector0 and vector1
  3217. * @param normal direction of the normal
  3218. * @return the angle between vector0 and vector1
  3219. */
  3220. Vector3.GetAngleBetweenVectors = function (vector0, vector1, normal) {
  3221. var v0 = vector0.clone().normalize();
  3222. var v1 = vector1.clone().normalize();
  3223. var dot = Vector3.Dot(v0, v1);
  3224. var n = Vector3.Cross(v0, v1);
  3225. if (Vector3.Dot(n, normal) > 0) {
  3226. return Math.acos(dot);
  3227. }
  3228. return -Math.acos(dot);
  3229. };
  3230. /**
  3231. * Returns a new Vector3 set from the index "offset" of the given array
  3232. * @param array defines the source array
  3233. * @param offset defines the offset in the source array
  3234. * @returns the new Vector3
  3235. */
  3236. Vector3.FromArray = function (array, offset) {
  3237. if (!offset) {
  3238. offset = 0;
  3239. }
  3240. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  3241. };
  3242. /**
  3243. * Returns a new Vector3 set from the index "offset" of the given Float32Array
  3244. * This function is deprecated. Use FromArray instead
  3245. * @param array defines the source array
  3246. * @param offset defines the offset in the source array
  3247. * @returns the new Vector3
  3248. */
  3249. Vector3.FromFloatArray = function (array, offset) {
  3250. return Vector3.FromArray(array, offset);
  3251. };
  3252. /**
  3253. * Sets the given vector "result" with the element values from the index "offset" of the given array
  3254. * @param array defines the source array
  3255. * @param offset defines the offset in the source array
  3256. * @param result defines the Vector3 where to store the result
  3257. */
  3258. Vector3.FromArrayToRef = function (array, offset, result) {
  3259. result.x = array[offset];
  3260. result.y = array[offset + 1];
  3261. result.z = array[offset + 2];
  3262. };
  3263. /**
  3264. * Sets the given vector "result" with the element values from the index "offset" of the given Float32Array
  3265. * This function is deprecated. Use FromArrayToRef instead.
  3266. * @param array defines the source array
  3267. * @param offset defines the offset in the source array
  3268. * @param result defines the Vector3 where to store the result
  3269. */
  3270. Vector3.FromFloatArrayToRef = function (array, offset, result) {
  3271. return Vector3.FromArrayToRef(array, offset, result);
  3272. };
  3273. /**
  3274. * Sets the given vector "result" with the given floats.
  3275. * @param x defines the x coordinate of the source
  3276. * @param y defines the y coordinate of the source
  3277. * @param z defines the z coordinate of the source
  3278. * @param result defines the Vector3 where to store the result
  3279. */
  3280. Vector3.FromFloatsToRef = function (x, y, z, result) {
  3281. result.x = x;
  3282. result.y = y;
  3283. result.z = z;
  3284. };
  3285. /**
  3286. * Returns a new Vector3 set to (0.0, 0.0, 0.0)
  3287. * @returns a new empty Vector3
  3288. */
  3289. Vector3.Zero = function () {
  3290. return new Vector3(0.0, 0.0, 0.0);
  3291. };
  3292. /**
  3293. * Returns a new Vector3 set to (1.0, 1.0, 1.0)
  3294. * @returns a new unit Vector3
  3295. */
  3296. Vector3.One = function () {
  3297. return new Vector3(1.0, 1.0, 1.0);
  3298. };
  3299. /**
  3300. * Returns a new Vector3 set to (0.0, 1.0, 0.0)
  3301. * @returns a new up Vector3
  3302. */
  3303. Vector3.Up = function () {
  3304. return new Vector3(0.0, 1.0, 0.0);
  3305. };
  3306. /**
  3307. * Returns a new Vector3 set to (0.0, 0.0, 1.0)
  3308. * @returns a new forward Vector3
  3309. */
  3310. Vector3.Forward = function () {
  3311. return new Vector3(0.0, 0.0, 1.0);
  3312. };
  3313. /**
  3314. * Returns a new Vector3 set to (1.0, 0.0, 0.0)
  3315. * @returns a new right Vector3
  3316. */
  3317. Vector3.Right = function () {
  3318. return new Vector3(1.0, 0.0, 0.0);
  3319. };
  3320. /**
  3321. * Returns a new Vector3 set to (-1.0, 0.0, 0.0)
  3322. * @returns a new left Vector3
  3323. */
  3324. Vector3.Left = function () {
  3325. return new Vector3(-1.0, 0.0, 0.0);
  3326. };
  3327. /**
  3328. * Returns a new Vector3 set with the result of the transformation by the given matrix of the given vector.
  3329. * This method computes tranformed coordinates only, not transformed direction vectors (ie. it takes translation in account)
  3330. * @param vector defines the Vector3 to transform
  3331. * @param transformation defines the transformation matrix
  3332. * @returns the transformed Vector3
  3333. */
  3334. Vector3.TransformCoordinates = function (vector, transformation) {
  3335. var result = Vector3.Zero();
  3336. Vector3.TransformCoordinatesToRef(vector, transformation, result);
  3337. return result;
  3338. };
  3339. /**
  3340. * Sets the given vector "result" coordinates with the result of the transformation by the given matrix of the given vector
  3341. * This method computes tranformed coordinates only, not transformed direction vectors (ie. it takes translation in account)
  3342. * @param vector defines the Vector3 to transform
  3343. * @param transformation defines the transformation matrix
  3344. * @param result defines the Vector3 where to store the result
  3345. */
  3346. Vector3.TransformCoordinatesToRef = function (vector, transformation, result) {
  3347. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]) + transformation.m[12];
  3348. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]) + transformation.m[13];
  3349. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]) + transformation.m[14];
  3350. var w = (vector.x * transformation.m[3]) + (vector.y * transformation.m[7]) + (vector.z * transformation.m[11]) + transformation.m[15];
  3351. result.x = x / w;
  3352. result.y = y / w;
  3353. result.z = z / w;
  3354. };
  3355. /**
  3356. * Sets the given vector "result" coordinates with the result of the transformation by the given matrix of the given floats (x, y, z)
  3357. * This method computes tranformed coordinates only, not transformed direction vectors
  3358. * @param x define the x coordinate of the source vector
  3359. * @param y define the y coordinate of the source vector
  3360. * @param z define the z coordinate of the source vector
  3361. * @param transformation defines the transformation matrix
  3362. * @param result defines the Vector3 where to store the result
  3363. */
  3364. Vector3.TransformCoordinatesFromFloatsToRef = function (x, y, z, transformation, result) {
  3365. var rx = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]) + transformation.m[12];
  3366. var ry = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]) + transformation.m[13];
  3367. var rz = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]) + transformation.m[14];
  3368. var rw = (x * transformation.m[3]) + (y * transformation.m[7]) + (z * transformation.m[11]) + transformation.m[15];
  3369. result.x = rx / rw;
  3370. result.y = ry / rw;
  3371. result.z = rz / rw;
  3372. };
  3373. /**
  3374. * Returns a new Vector3 set with the result of the normal transformation by the given matrix of the given vector
  3375. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3376. * @param vector defines the Vector3 to transform
  3377. * @param transformation defines the transformation matrix
  3378. * @returns the new Vector3
  3379. */
  3380. Vector3.TransformNormal = function (vector, transformation) {
  3381. var result = Vector3.Zero();
  3382. Vector3.TransformNormalToRef(vector, transformation, result);
  3383. return result;
  3384. };
  3385. /**
  3386. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given vector
  3387. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3388. * @param vector defines the Vector3 to transform
  3389. * @param transformation defines the transformation matrix
  3390. * @param result defines the Vector3 where to store the result
  3391. */
  3392. Vector3.TransformNormalToRef = function (vector, transformation, result) {
  3393. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  3394. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  3395. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  3396. result.x = x;
  3397. result.y = y;
  3398. result.z = z;
  3399. };
  3400. /**
  3401. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given floats (x, y, z)
  3402. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3403. * @param x define the x coordinate of the source vector
  3404. * @param y define the y coordinate of the source vector
  3405. * @param z define the z coordinate of the source vector
  3406. * @param transformation defines the transformation matrix
  3407. * @param result defines the Vector3 where to store the result
  3408. */
  3409. Vector3.TransformNormalFromFloatsToRef = function (x, y, z, transformation, result) {
  3410. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  3411. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  3412. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  3413. };
  3414. /**
  3415. * Returns a new Vector3 located for "amount" on the CatmullRom interpolation spline defined by the vectors "value1", "value2", "value3", "value4"
  3416. * @param value1 defines the first control point
  3417. * @param value2 defines the second control point
  3418. * @param value3 defines the third control point
  3419. * @param value4 defines the fourth control point
  3420. * @param amount defines the amount on the spline to use
  3421. * @returns the new Vector3
  3422. */
  3423. Vector3.CatmullRom = function (value1, value2, value3, value4, amount) {
  3424. var squared = amount * amount;
  3425. var cubed = amount * squared;
  3426. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  3427. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  3428. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  3429. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  3430. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  3431. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  3432. var z = 0.5 * ((((2.0 * value2.z) + ((-value1.z + value3.z) * amount)) +
  3433. (((((2.0 * value1.z) - (5.0 * value2.z)) + (4.0 * value3.z)) - value4.z) * squared)) +
  3434. ((((-value1.z + (3.0 * value2.z)) - (3.0 * value3.z)) + value4.z) * cubed));
  3435. return new Vector3(x, y, z);
  3436. };
  3437. /**
  3438. * 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"
  3439. * If a coordinate value of "value" is lower than one of the "min" coordinate, then this "value" coordinate is set with the "min" one
  3440. * If a coordinate value of "value" is greater than one of the "max" coordinate, then this "value" coordinate is set with the "max" one
  3441. * @param value defines the current value
  3442. * @param min defines the lower range value
  3443. * @param max defines the upper range value
  3444. * @returns the new Vector3
  3445. */
  3446. Vector3.Clamp = function (value, min, max) {
  3447. var x = value.x;
  3448. x = (x > max.x) ? max.x : x;
  3449. x = (x < min.x) ? min.x : x;
  3450. var y = value.y;
  3451. y = (y > max.y) ? max.y : y;
  3452. y = (y < min.y) ? min.y : y;
  3453. var z = value.z;
  3454. z = (z > max.z) ? max.z : z;
  3455. z = (z < min.z) ? min.z : z;
  3456. return new Vector3(x, y, z);
  3457. };
  3458. /**
  3459. * Returns a new Vector3 located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2"
  3460. * @param value1 defines the first control point
  3461. * @param tangent1 defines the first tangent vector
  3462. * @param value2 defines the second control point
  3463. * @param tangent2 defines the second tangent vector
  3464. * @param amount defines the amount on the interpolation spline (between 0 and 1)
  3465. * @returns the new Vector3
  3466. */
  3467. Vector3.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  3468. var squared = amount * amount;
  3469. var cubed = amount * squared;
  3470. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  3471. var part2 = (-2.0 * cubed) + (3.0 * squared);
  3472. var part3 = (cubed - (2.0 * squared)) + amount;
  3473. var part4 = cubed - squared;
  3474. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  3475. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  3476. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  3477. return new Vector3(x, y, z);
  3478. };
  3479. /**
  3480. * Returns a new Vector3 located for "amount" (float) on the linear interpolation between the vectors "start" and "end"
  3481. * @param start defines the start value
  3482. * @param end defines the end value
  3483. * @param amount max defines amount between both (between 0 and 1)
  3484. * @returns the new Vector3
  3485. */
  3486. Vector3.Lerp = function (start, end, amount) {
  3487. var result = new Vector3(0, 0, 0);
  3488. Vector3.LerpToRef(start, end, amount, result);
  3489. return result;
  3490. };
  3491. /**
  3492. * Sets the given vector "result" with the result of the linear interpolation from the vector "start" for "amount" to the vector "end"
  3493. * @param start defines the start value
  3494. * @param end defines the end value
  3495. * @param amount max defines amount between both (between 0 and 1)
  3496. * @param result defines the Vector3 where to store the result
  3497. */
  3498. Vector3.LerpToRef = function (start, end, amount, result) {
  3499. result.x = start.x + ((end.x - start.x) * amount);
  3500. result.y = start.y + ((end.y - start.y) * amount);
  3501. result.z = start.z + ((end.z - start.z) * amount);
  3502. };
  3503. /**
  3504. * Returns the dot product (float) between the vectors "left" and "right"
  3505. * @param left defines the left operand
  3506. * @param right defines the right operand
  3507. * @returns the dot product
  3508. */
  3509. Vector3.Dot = function (left, right) {
  3510. return (left.x * right.x + left.y * right.y + left.z * right.z);
  3511. };
  3512. /**
  3513. * Returns a new Vector3 as the cross product of the vectors "left" and "right"
  3514. * The cross product is then orthogonal to both "left" and "right"
  3515. * @param left defines the left operand
  3516. * @param right defines the right operand
  3517. * @returns the cross product
  3518. */
  3519. Vector3.Cross = function (left, right) {
  3520. var result = Vector3.Zero();
  3521. Vector3.CrossToRef(left, right, result);
  3522. return result;
  3523. };
  3524. /**
  3525. * Sets the given vector "result" with the cross product of "left" and "right"
  3526. * The cross product is then orthogonal to both "left" and "right"
  3527. * @param left defines the left operand
  3528. * @param right defines the right operand
  3529. * @param result defines the Vector3 where to store the result
  3530. */
  3531. Vector3.CrossToRef = function (left, right, result) {
  3532. MathTmp.Vector3[0].x = left.y * right.z - left.z * right.y;
  3533. MathTmp.Vector3[0].y = left.z * right.x - left.x * right.z;
  3534. MathTmp.Vector3[0].z = left.x * right.y - left.y * right.x;
  3535. result.copyFrom(MathTmp.Vector3[0]);
  3536. };
  3537. /**
  3538. * Returns a new Vector3 as the normalization of the given vector
  3539. * @param vector defines the Vector3 to normalize
  3540. * @returns the new Vector3
  3541. */
  3542. Vector3.Normalize = function (vector) {
  3543. var result = Vector3.Zero();
  3544. Vector3.NormalizeToRef(vector, result);
  3545. return result;
  3546. };
  3547. /**
  3548. * Sets the given vector "result" with the normalization of the given first vector
  3549. * @param vector defines the Vector3 to normalize
  3550. * @param result defines the Vector3 where to store the result
  3551. */
  3552. Vector3.NormalizeToRef = function (vector, result) {
  3553. result.copyFrom(vector);
  3554. result.normalize();
  3555. };
  3556. /**
  3557. * Project a Vector3 onto screen space
  3558. * @param vector defines the Vector3 to project
  3559. * @param world defines the world matrix to use
  3560. * @param transform defines the transform (view x projection) matrix to use
  3561. * @param viewport defines the screen viewport to use
  3562. * @returns the new Vector3
  3563. */
  3564. Vector3.Project = function (vector, world, transform, viewport) {
  3565. var cw = viewport.width;
  3566. var ch = viewport.height;
  3567. var cx = viewport.x;
  3568. var cy = viewport.y;
  3569. var viewportMatrix = Vector3._viewportMatrixCache ? Vector3._viewportMatrixCache : (Vector3._viewportMatrixCache = new Matrix());
  3570. 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);
  3571. var matrix = MathTmp.Matrix[0];
  3572. world.multiplyToRef(transform, matrix);
  3573. matrix.multiplyToRef(viewportMatrix, matrix);
  3574. return Vector3.TransformCoordinates(vector, matrix);
  3575. };
  3576. /**
  3577. * Unproject from screen space to object space
  3578. * @param source defines the screen space Vector3 to use
  3579. * @param viewportWidth defines the current width of the viewport
  3580. * @param viewportHeight defines the current height of the viewport
  3581. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3582. * @param transform defines the transform (view x projection) matrix to use
  3583. * @returns the new Vector3
  3584. */
  3585. Vector3.UnprojectFromTransform = function (source, viewportWidth, viewportHeight, world, transform) {
  3586. var matrix = MathTmp.Matrix[0];
  3587. world.multiplyToRef(transform, matrix);
  3588. matrix.invert();
  3589. source.x = source.x / viewportWidth * 2 - 1;
  3590. source.y = -(source.y / viewportHeight * 2 - 1);
  3591. var vector = Vector3.TransformCoordinates(source, matrix);
  3592. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  3593. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  3594. vector = vector.scale(1.0 / num);
  3595. }
  3596. return vector;
  3597. };
  3598. /**
  3599. * Unproject from screen space to object space
  3600. * @param source defines the screen space Vector3 to use
  3601. * @param viewportWidth defines the current width of the viewport
  3602. * @param viewportHeight defines the current height of the viewport
  3603. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3604. * @param view defines the view matrix to use
  3605. * @param projection defines the projection matrix to use
  3606. * @returns the new Vector3
  3607. */
  3608. Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
  3609. var result = Vector3.Zero();
  3610. Vector3.UnprojectToRef(source, viewportWidth, viewportHeight, world, view, projection, result);
  3611. return result;
  3612. };
  3613. /**
  3614. * Unproject from screen space to object space
  3615. * @param source defines the screen space Vector3 to use
  3616. * @param viewportWidth defines the current width of the viewport
  3617. * @param viewportHeight defines the current height of the viewport
  3618. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3619. * @param view defines the view matrix to use
  3620. * @param projection defines the projection matrix to use
  3621. * @param result defines the Vector3 where to store the result
  3622. */
  3623. Vector3.UnprojectToRef = function (source, viewportWidth, viewportHeight, world, view, projection, result) {
  3624. Vector3.UnprojectFloatsToRef(source.x, source.y, source.z, viewportWidth, viewportHeight, world, view, projection, result);
  3625. };
  3626. /**
  3627. * Unproject from screen space to object space
  3628. * @param sourceX defines the screen space x coordinate to use
  3629. * @param sourceY defines the screen space y coordinate to use
  3630. * @param sourceZ defines the screen space z coordinate to use
  3631. * @param viewportWidth defines the current width of the viewport
  3632. * @param viewportHeight defines the current height of the viewport
  3633. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3634. * @param view defines the view matrix to use
  3635. * @param projection defines the projection matrix to use
  3636. * @param result defines the Vector3 where to store the result
  3637. */
  3638. Vector3.UnprojectFloatsToRef = function (sourceX, sourceY, sourceZ, viewportWidth, viewportHeight, world, view, projection, result) {
  3639. var matrix = MathTmp.Matrix[0];
  3640. world.multiplyToRef(view, matrix);
  3641. matrix.multiplyToRef(projection, matrix);
  3642. matrix.invert();
  3643. var screenSource = MathTmp.Vector3[0];
  3644. screenSource.x = sourceX / viewportWidth * 2 - 1;
  3645. screenSource.y = -(sourceY / viewportHeight * 2 - 1);
  3646. screenSource.z = 2 * sourceZ - 1.0;
  3647. Vector3.TransformCoordinatesToRef(screenSource, matrix, result);
  3648. var num = screenSource.x * matrix.m[3] + screenSource.y * matrix.m[7] + screenSource.z * matrix.m[11] + matrix.m[15];
  3649. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  3650. result.scaleInPlace(1.0 / num);
  3651. }
  3652. };
  3653. /**
  3654. * Gets the minimal coordinate values between two Vector3
  3655. * @param left defines the first operand
  3656. * @param right defines the second operand
  3657. * @returns the new Vector3
  3658. */
  3659. Vector3.Minimize = function (left, right) {
  3660. var min = left.clone();
  3661. min.minimizeInPlace(right);
  3662. return min;
  3663. };
  3664. /**
  3665. * Gets the maximal coordinate values between two Vector3
  3666. * @param left defines the first operand
  3667. * @param right defines the second operand
  3668. * @returns the new Vector3
  3669. */
  3670. Vector3.Maximize = function (left, right) {
  3671. var max = left.clone();
  3672. max.maximizeInPlace(right);
  3673. return max;
  3674. };
  3675. /**
  3676. * Returns the distance between the vectors "value1" and "value2"
  3677. * @param value1 defines the first operand
  3678. * @param value2 defines the second operand
  3679. * @returns the distance
  3680. */
  3681. Vector3.Distance = function (value1, value2) {
  3682. return Math.sqrt(Vector3.DistanceSquared(value1, value2));
  3683. };
  3684. /**
  3685. * Returns the squared distance between the vectors "value1" and "value2"
  3686. * @param value1 defines the first operand
  3687. * @param value2 defines the second operand
  3688. * @returns the squared distance
  3689. */
  3690. Vector3.DistanceSquared = function (value1, value2) {
  3691. var x = value1.x - value2.x;
  3692. var y = value1.y - value2.y;
  3693. var z = value1.z - value2.z;
  3694. return (x * x) + (y * y) + (z * z);
  3695. };
  3696. /**
  3697. * Returns a new Vector3 located at the center between "value1" and "value2"
  3698. * @param value1 defines the first operand
  3699. * @param value2 defines the second operand
  3700. * @returns the new Vector3
  3701. */
  3702. Vector3.Center = function (value1, value2) {
  3703. var center = value1.add(value2);
  3704. center.scaleInPlace(0.5);
  3705. return center;
  3706. };
  3707. /**
  3708. * Given three orthogonal normalized left-handed oriented Vector3 axis in space (target system),
  3709. * RotationFromAxis() returns the rotation Euler angles (ex : rotation.x, rotation.y, rotation.z) to apply
  3710. * to something in order to rotate it from its local system to the given target system
  3711. * Note: axis1, axis2 and axis3 are normalized during this operation
  3712. * @param axis1 defines the first axis
  3713. * @param axis2 defines the second axis
  3714. * @param axis3 defines the third axis
  3715. * @returns a new Vector3
  3716. */
  3717. Vector3.RotationFromAxis = function (axis1, axis2, axis3) {
  3718. var rotation = Vector3.Zero();
  3719. Vector3.RotationFromAxisToRef(axis1, axis2, axis3, rotation);
  3720. return rotation;
  3721. };
  3722. /**
  3723. * The same than RotationFromAxis but updates the given ref Vector3 parameter instead of returning a new Vector3
  3724. * @param axis1 defines the first axis
  3725. * @param axis2 defines the second axis
  3726. * @param axis3 defines the third axis
  3727. * @param ref defines the Vector3 where to store the result
  3728. */
  3729. Vector3.RotationFromAxisToRef = function (axis1, axis2, axis3, ref) {
  3730. var quat = MathTmp.Quaternion[0];
  3731. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  3732. quat.toEulerAnglesToRef(ref);
  3733. };
  3734. return Vector3;
  3735. }());
  3736. BABYLON.Vector3 = Vector3;
  3737. //Vector4 class created for EulerAngle class conversion to Quaternion
  3738. var Vector4 = /** @class */ (function () {
  3739. /**
  3740. * Creates a Vector4 object from the given floats.
  3741. */
  3742. function Vector4(x, y, z, w) {
  3743. this.x = x;
  3744. this.y = y;
  3745. this.z = z;
  3746. this.w = w;
  3747. }
  3748. /**
  3749. * Returns the string with the Vector4 coordinates.
  3750. */
  3751. Vector4.prototype.toString = function () {
  3752. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  3753. };
  3754. /**
  3755. * Returns the string "Vector4".
  3756. */
  3757. Vector4.prototype.getClassName = function () {
  3758. return "Vector4";
  3759. };
  3760. /**
  3761. * Returns the Vector4 hash code.
  3762. */
  3763. Vector4.prototype.getHashCode = function () {
  3764. var hash = this.x || 0;
  3765. hash = (hash * 397) ^ (this.y || 0);
  3766. hash = (hash * 397) ^ (this.z || 0);
  3767. hash = (hash * 397) ^ (this.w || 0);
  3768. return hash;
  3769. };
  3770. // Operators
  3771. /**
  3772. * Returns a new array populated with 4 elements : the Vector4 coordinates.
  3773. */
  3774. Vector4.prototype.asArray = function () {
  3775. var result = new Array();
  3776. this.toArray(result, 0);
  3777. return result;
  3778. };
  3779. /**
  3780. * Populates the given array from the given index with the Vector4 coordinates.
  3781. * Returns the Vector4.
  3782. */
  3783. Vector4.prototype.toArray = function (array, index) {
  3784. if (index === undefined) {
  3785. index = 0;
  3786. }
  3787. array[index] = this.x;
  3788. array[index + 1] = this.y;
  3789. array[index + 2] = this.z;
  3790. array[index + 3] = this.w;
  3791. return this;
  3792. };
  3793. /**
  3794. * Adds the given vector to the current Vector4.
  3795. * Returns the updated Vector4.
  3796. */
  3797. Vector4.prototype.addInPlace = function (otherVector) {
  3798. this.x += otherVector.x;
  3799. this.y += otherVector.y;
  3800. this.z += otherVector.z;
  3801. this.w += otherVector.w;
  3802. return this;
  3803. };
  3804. /**
  3805. * Returns a new Vector4 as the result of the addition of the current Vector4 and the given one.
  3806. */
  3807. Vector4.prototype.add = function (otherVector) {
  3808. return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
  3809. };
  3810. /**
  3811. * Updates the given vector "result" with the result of the addition of the current Vector4 and the given one.
  3812. * Returns the current Vector4.
  3813. */
  3814. Vector4.prototype.addToRef = function (otherVector, result) {
  3815. result.x = this.x + otherVector.x;
  3816. result.y = this.y + otherVector.y;
  3817. result.z = this.z + otherVector.z;
  3818. result.w = this.w + otherVector.w;
  3819. return this;
  3820. };
  3821. /**
  3822. * Subtract in place the given vector from the current Vector4.
  3823. * Returns the updated Vector4.
  3824. */
  3825. Vector4.prototype.subtractInPlace = function (otherVector) {
  3826. this.x -= otherVector.x;
  3827. this.y -= otherVector.y;
  3828. this.z -= otherVector.z;
  3829. this.w -= otherVector.w;
  3830. return this;
  3831. };
  3832. /**
  3833. * Returns a new Vector4 with the result of the subtraction of the given vector from the current Vector4.
  3834. */
  3835. Vector4.prototype.subtract = function (otherVector) {
  3836. return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
  3837. };
  3838. /**
  3839. * Sets the given vector "result" with the result of the subtraction of the given vector from the current Vector4.
  3840. * Returns the current Vector4.
  3841. */
  3842. Vector4.prototype.subtractToRef = function (otherVector, result) {
  3843. result.x = this.x - otherVector.x;
  3844. result.y = this.y - otherVector.y;
  3845. result.z = this.z - otherVector.z;
  3846. result.w = this.w - otherVector.w;
  3847. return this;
  3848. };
  3849. /**
  3850. * Returns a new Vector4 set with the result of the subtraction of the given floats from the current Vector4 coordinates.
  3851. */
  3852. Vector4.prototype.subtractFromFloats = function (x, y, z, w) {
  3853. return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
  3854. };
  3855. /**
  3856. * Sets the given vector "result" set with the result of the subtraction of the given floats from the current Vector4 coordinates.
  3857. * Returns the current Vector4.
  3858. */
  3859. Vector4.prototype.subtractFromFloatsToRef = function (x, y, z, w, result) {
  3860. result.x = this.x - x;
  3861. result.y = this.y - y;
  3862. result.z = this.z - z;
  3863. result.w = this.w - w;
  3864. return this;
  3865. };
  3866. /**
  3867. * Returns a new Vector4 set with the current Vector4 negated coordinates.
  3868. */
  3869. Vector4.prototype.negate = function () {
  3870. return new Vector4(-this.x, -this.y, -this.z, -this.w);
  3871. };
  3872. /**
  3873. * Multiplies the current Vector4 coordinates by scale (float).
  3874. * Returns the updated Vector4.
  3875. */
  3876. Vector4.prototype.scaleInPlace = function (scale) {
  3877. this.x *= scale;
  3878. this.y *= scale;
  3879. this.z *= scale;
  3880. this.w *= scale;
  3881. return this;
  3882. };
  3883. /**
  3884. * Returns a new Vector4 set with the current Vector4 coordinates multiplied by scale (float).
  3885. */
  3886. Vector4.prototype.scale = function (scale) {
  3887. return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
  3888. };
  3889. /**
  3890. * Sets the given vector "result" with the current Vector4 coordinates multiplied by scale (float).
  3891. * Returns the current Vector4.
  3892. */
  3893. Vector4.prototype.scaleToRef = function (scale, result) {
  3894. result.x = this.x * scale;
  3895. result.y = this.y * scale;
  3896. result.z = this.z * scale;
  3897. result.w = this.w * scale;
  3898. return this;
  3899. };
  3900. /**
  3901. * Scale the current Vector4 values by a factor and add the result to a given Vector4
  3902. * @param scale defines the scale factor
  3903. * @param result defines the Vector4 object where to store the result
  3904. * @returns the unmodified current Vector4
  3905. */
  3906. Vector4.prototype.scaleAndAddToRef = function (scale, result) {
  3907. result.x += this.x * scale;
  3908. result.y += this.y * scale;
  3909. result.z += this.z * scale;
  3910. result.w += this.w * scale;
  3911. return this;
  3912. };
  3913. /**
  3914. * Boolean : True if the current Vector4 coordinates are stricly equal to the given ones.
  3915. */
  3916. Vector4.prototype.equals = function (otherVector) {
  3917. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
  3918. };
  3919. /**
  3920. * Boolean : True if the current Vector4 coordinates are each beneath the distance "epsilon" from the given vector ones.
  3921. */
  3922. Vector4.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  3923. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  3924. return otherVector
  3925. && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon)
  3926. && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon)
  3927. && BABYLON.Scalar.WithinEpsilon(this.z, otherVector.z, epsilon)
  3928. && BABYLON.Scalar.WithinEpsilon(this.w, otherVector.w, epsilon);
  3929. };
  3930. /**
  3931. * Boolean : True if the given floats are strictly equal to the current Vector4 coordinates.
  3932. */
  3933. Vector4.prototype.equalsToFloats = function (x, y, z, w) {
  3934. return this.x === x && this.y === y && this.z === z && this.w === w;
  3935. };
  3936. /**
  3937. * Multiplies in place the current Vector4 by the given one.
  3938. * Returns the updated Vector4.
  3939. */
  3940. Vector4.prototype.multiplyInPlace = function (otherVector) {
  3941. this.x *= otherVector.x;
  3942. this.y *= otherVector.y;
  3943. this.z *= otherVector.z;
  3944. this.w *= otherVector.w;
  3945. return this;
  3946. };
  3947. /**
  3948. * Returns a new Vector4 set with the multiplication result of the current Vector4 and the given one.
  3949. */
  3950. Vector4.prototype.multiply = function (otherVector) {
  3951. return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
  3952. };
  3953. /**
  3954. * Updates the given vector "result" with the multiplication result of the current Vector4 and the given one.
  3955. * Returns the current Vector4.
  3956. */
  3957. Vector4.prototype.multiplyToRef = function (otherVector, result) {
  3958. result.x = this.x * otherVector.x;
  3959. result.y = this.y * otherVector.y;
  3960. result.z = this.z * otherVector.z;
  3961. result.w = this.w * otherVector.w;
  3962. return this;
  3963. };
  3964. /**
  3965. * Returns a new Vector4 set with the multiplication result of the given floats and the current Vector4 coordinates.
  3966. */
  3967. Vector4.prototype.multiplyByFloats = function (x, y, z, w) {
  3968. return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
  3969. };
  3970. /**
  3971. * Returns a new Vector4 set with the division result of the current Vector4 by the given one.
  3972. */
  3973. Vector4.prototype.divide = function (otherVector) {
  3974. return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
  3975. };
  3976. /**
  3977. * Updates the given vector "result" with the division result of the current Vector4 by the given one.
  3978. * Returns the current Vector4.
  3979. */
  3980. Vector4.prototype.divideToRef = function (otherVector, result) {
  3981. result.x = this.x / otherVector.x;
  3982. result.y = this.y / otherVector.y;
  3983. result.z = this.z / otherVector.z;
  3984. result.w = this.w / otherVector.w;
  3985. return this;
  3986. };
  3987. /**
  3988. * Divides the current Vector3 coordinates by the given ones.
  3989. * @returns the updated Vector3.
  3990. */
  3991. Vector4.prototype.divideInPlace = function (otherVector) {
  3992. return this.divideToRef(otherVector, this);
  3993. };
  3994. /**
  3995. * Updates the Vector4 coordinates with the minimum values between its own and the given vector ones
  3996. * @param other defines the second operand
  3997. * @returns the current updated Vector4
  3998. */
  3999. Vector4.prototype.minimizeInPlace = function (other) {
  4000. if (other.x < this.x)
  4001. this.x = other.x;
  4002. if (other.y < this.y)
  4003. this.y = other.y;
  4004. if (other.z < this.z)
  4005. this.z = other.z;
  4006. if (other.w < this.w)
  4007. this.w = other.w;
  4008. return this;
  4009. };
  4010. /**
  4011. * Updates the Vector4 coordinates with the maximum values between its own and the given vector ones
  4012. * @param other defines the second operand
  4013. * @returns the current updated Vector4
  4014. */
  4015. Vector4.prototype.maximizeInPlace = function (other) {
  4016. if (other.x > this.x)
  4017. this.x = other.x;
  4018. if (other.y > this.y)
  4019. this.y = other.y;
  4020. if (other.z > this.z)
  4021. this.z = other.z;
  4022. if (other.w > this.w)
  4023. this.w = other.w;
  4024. return this;
  4025. };
  4026. // Properties
  4027. /**
  4028. * Returns the Vector4 length (float).
  4029. */
  4030. Vector4.prototype.length = function () {
  4031. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  4032. };
  4033. /**
  4034. * Returns the Vector4 squared length (float).
  4035. */
  4036. Vector4.prototype.lengthSquared = function () {
  4037. return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  4038. };
  4039. // Methods
  4040. /**
  4041. * Normalizes in place the Vector4.
  4042. * Returns the updated Vector4.
  4043. */
  4044. Vector4.prototype.normalize = function () {
  4045. var len = this.length();
  4046. if (len === 0)
  4047. return this;
  4048. var num = 1.0 / len;
  4049. this.x *= num;
  4050. this.y *= num;
  4051. this.z *= num;
  4052. this.w *= num;
  4053. return this;
  4054. };
  4055. /**
  4056. * Returns a new Vector3 from the Vector4 (x, y, z) coordinates.
  4057. */
  4058. Vector4.prototype.toVector3 = function () {
  4059. return new Vector3(this.x, this.y, this.z);
  4060. };
  4061. /**
  4062. * Returns a new Vector4 copied from the current one.
  4063. */
  4064. Vector4.prototype.clone = function () {
  4065. return new Vector4(this.x, this.y, this.z, this.w);
  4066. };
  4067. /**
  4068. * Updates the current Vector4 with the given one coordinates.
  4069. * Returns the updated Vector4.
  4070. */
  4071. Vector4.prototype.copyFrom = function (source) {
  4072. this.x = source.x;
  4073. this.y = source.y;
  4074. this.z = source.z;
  4075. this.w = source.w;
  4076. return this;
  4077. };
  4078. /**
  4079. * Updates the current Vector4 coordinates with the given floats.
  4080. * Returns the updated Vector4.
  4081. */
  4082. Vector4.prototype.copyFromFloats = function (x, y, z, w) {
  4083. this.x = x;
  4084. this.y = y;
  4085. this.z = z;
  4086. this.w = w;
  4087. return this;
  4088. };
  4089. /**
  4090. * Updates the current Vector4 coordinates with the given floats.
  4091. * Returns the updated Vector4.
  4092. */
  4093. Vector4.prototype.set = function (x, y, z, w) {
  4094. return this.copyFromFloats(x, y, z, w);
  4095. };
  4096. // Statics
  4097. /**
  4098. * Returns a new Vector4 set from the starting index of the given array.
  4099. */
  4100. Vector4.FromArray = function (array, offset) {
  4101. if (!offset) {
  4102. offset = 0;
  4103. }
  4104. return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  4105. };
  4106. /**
  4107. * Updates the given vector "result" from the starting index of the given array.
  4108. */
  4109. Vector4.FromArrayToRef = function (array, offset, result) {
  4110. result.x = array[offset];
  4111. result.y = array[offset + 1];
  4112. result.z = array[offset + 2];
  4113. result.w = array[offset + 3];
  4114. };
  4115. /**
  4116. * Updates the given vector "result" from the starting index of the given Float32Array.
  4117. */
  4118. Vector4.FromFloatArrayToRef = function (array, offset, result) {
  4119. Vector4.FromArrayToRef(array, offset, result);
  4120. };
  4121. /**
  4122. * Updates the given vector "result" coordinates from the given floats.
  4123. */
  4124. Vector4.FromFloatsToRef = function (x, y, z, w, result) {
  4125. result.x = x;
  4126. result.y = y;
  4127. result.z = z;
  4128. result.w = w;
  4129. };
  4130. /**
  4131. * Returns a new Vector4 set to (0.0, 0.0, 0.0, 0.0)
  4132. */
  4133. Vector4.Zero = function () {
  4134. return new Vector4(0.0, 0.0, 0.0, 0.0);
  4135. };
  4136. /**
  4137. * Returns a new Vector4 set to (1.0, 1.0, 1.0, 1.0)
  4138. */
  4139. Vector4.One = function () {
  4140. return new Vector4(1.0, 1.0, 1.0, 1.0);
  4141. };
  4142. /**
  4143. * Returns a new normalized Vector4 from the given one.
  4144. */
  4145. Vector4.Normalize = function (vector) {
  4146. var result = Vector4.Zero();
  4147. Vector4.NormalizeToRef(vector, result);
  4148. return result;
  4149. };
  4150. /**
  4151. * Updates the given vector "result" from the normalization of the given one.
  4152. */
  4153. Vector4.NormalizeToRef = function (vector, result) {
  4154. result.copyFrom(vector);
  4155. result.normalize();
  4156. };
  4157. Vector4.Minimize = function (left, right) {
  4158. var min = left.clone();
  4159. min.minimizeInPlace(right);
  4160. return min;
  4161. };
  4162. Vector4.Maximize = function (left, right) {
  4163. var max = left.clone();
  4164. max.maximizeInPlace(right);
  4165. return max;
  4166. };
  4167. /**
  4168. * Returns the distance (float) between the vectors "value1" and "value2".
  4169. */
  4170. Vector4.Distance = function (value1, value2) {
  4171. return Math.sqrt(Vector4.DistanceSquared(value1, value2));
  4172. };
  4173. /**
  4174. * Returns the squared distance (float) between the vectors "value1" and "value2".
  4175. */
  4176. Vector4.DistanceSquared = function (value1, value2) {
  4177. var x = value1.x - value2.x;
  4178. var y = value1.y - value2.y;
  4179. var z = value1.z - value2.z;
  4180. var w = value1.w - value2.w;
  4181. return (x * x) + (y * y) + (z * z) + (w * w);
  4182. };
  4183. /**
  4184. * Returns a new Vector4 located at the center between the vectors "value1" and "value2".
  4185. */
  4186. Vector4.Center = function (value1, value2) {
  4187. var center = value1.add(value2);
  4188. center.scaleInPlace(0.5);
  4189. return center;
  4190. };
  4191. /**
  4192. * Returns a new Vector4 set with the result of the normal transformation by the given matrix of the given vector.
  4193. * This methods computes transformed normalized direction vectors only.
  4194. */
  4195. Vector4.TransformNormal = function (vector, transformation) {
  4196. var result = Vector4.Zero();
  4197. Vector4.TransformNormalToRef(vector, transformation, result);
  4198. return result;
  4199. };
  4200. /**
  4201. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given vector.
  4202. * This methods computes transformed normalized direction vectors only.
  4203. */
  4204. Vector4.TransformNormalToRef = function (vector, transformation, result) {
  4205. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  4206. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  4207. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  4208. result.x = x;
  4209. result.y = y;
  4210. result.z = z;
  4211. result.w = vector.w;
  4212. };
  4213. /**
  4214. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given floats (x, y, z, w).
  4215. * This methods computes transformed normalized direction vectors only.
  4216. */
  4217. Vector4.TransformNormalFromFloatsToRef = function (x, y, z, w, transformation, result) {
  4218. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  4219. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  4220. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  4221. result.w = w;
  4222. };
  4223. return Vector4;
  4224. }());
  4225. BABYLON.Vector4 = Vector4;
  4226. var Size = /** @class */ (function () {
  4227. /**
  4228. * Creates a Size object from the given width and height (floats).
  4229. */
  4230. function Size(width, height) {
  4231. this.width = width;
  4232. this.height = height;
  4233. }
  4234. // Returns a string with the Size width and height.
  4235. Size.prototype.toString = function () {
  4236. return "{W: " + this.width + ", H: " + this.height + "}";
  4237. };
  4238. /**
  4239. * Returns the string "Size"
  4240. */
  4241. Size.prototype.getClassName = function () {
  4242. return "Size";
  4243. };
  4244. /**
  4245. * Returns the Size hash code.
  4246. */
  4247. Size.prototype.getHashCode = function () {
  4248. var hash = this.width || 0;
  4249. hash = (hash * 397) ^ (this.height || 0);
  4250. return hash;
  4251. };
  4252. /**
  4253. * Updates the current size from the given one.
  4254. * Returns the updated Size.
  4255. */
  4256. Size.prototype.copyFrom = function (src) {
  4257. this.width = src.width;
  4258. this.height = src.height;
  4259. };
  4260. /**
  4261. * Updates in place the current Size from the given floats.
  4262. * Returns the updated Size.
  4263. */
  4264. Size.prototype.copyFromFloats = function (width, height) {
  4265. this.width = width;
  4266. this.height = height;
  4267. return this;
  4268. };
  4269. /**
  4270. * Updates in place the current Size from the given floats.
  4271. * Returns the updated Size.
  4272. */
  4273. Size.prototype.set = function (width, height) {
  4274. return this.copyFromFloats(width, height);
  4275. };
  4276. /**
  4277. * Returns a new Size set with the multiplication result of the current Size and the given floats.
  4278. */
  4279. Size.prototype.multiplyByFloats = function (w, h) {
  4280. return new Size(this.width * w, this.height * h);
  4281. };
  4282. /**
  4283. * Returns a new Size copied from the given one.
  4284. */
  4285. Size.prototype.clone = function () {
  4286. return new Size(this.width, this.height);
  4287. };
  4288. /**
  4289. * Boolean : True if the current Size and the given one width and height are strictly equal.
  4290. */
  4291. Size.prototype.equals = function (other) {
  4292. if (!other) {
  4293. return false;
  4294. }
  4295. return (this.width === other.width) && (this.height === other.height);
  4296. };
  4297. Object.defineProperty(Size.prototype, "surface", {
  4298. /**
  4299. * Returns the surface of the Size : width * height (float).
  4300. */
  4301. get: function () {
  4302. return this.width * this.height;
  4303. },
  4304. enumerable: true,
  4305. configurable: true
  4306. });
  4307. /**
  4308. * Returns a new Size set to (0.0, 0.0)
  4309. */
  4310. Size.Zero = function () {
  4311. return new Size(0.0, 0.0);
  4312. };
  4313. /**
  4314. * Returns a new Size set as the addition result of the current Size and the given one.
  4315. */
  4316. Size.prototype.add = function (otherSize) {
  4317. var r = new Size(this.width + otherSize.width, this.height + otherSize.height);
  4318. return r;
  4319. };
  4320. /**
  4321. * Returns a new Size set as the subtraction result of the given one from the current Size.
  4322. */
  4323. Size.prototype.subtract = function (otherSize) {
  4324. var r = new Size(this.width - otherSize.width, this.height - otherSize.height);
  4325. return r;
  4326. };
  4327. /**
  4328. * Returns a new Size set at the linear interpolation "amount" between "start" and "end".
  4329. */
  4330. Size.Lerp = function (start, end, amount) {
  4331. var w = start.width + ((end.width - start.width) * amount);
  4332. var h = start.height + ((end.height - start.height) * amount);
  4333. return new Size(w, h);
  4334. };
  4335. return Size;
  4336. }());
  4337. BABYLON.Size = Size;
  4338. /**
  4339. * Class used to store quaternion data
  4340. * @see https://en.wikipedia.org/wiki/Quaternion
  4341. * @see http://doc.babylonjs.com/features/position,_rotation,_scaling
  4342. */
  4343. var Quaternion = /** @class */ (function () {
  4344. /**
  4345. * Creates a new Quaternion from the given floats
  4346. * @param x defines the first component (0 by default)
  4347. * @param y defines the second component (0 by default)
  4348. * @param z defines the third component (0 by default)
  4349. * @param w defines the fourth component (1.0 by default)
  4350. */
  4351. function Quaternion(
  4352. /** defines the first component (0 by default) */
  4353. x,
  4354. /** defines the second component (0 by default) */
  4355. y,
  4356. /** defines the third component (0 by default) */
  4357. z,
  4358. /** defines the fourth component (1.0 by default) */
  4359. w) {
  4360. if (x === void 0) { x = 0.0; }
  4361. if (y === void 0) { y = 0.0; }
  4362. if (z === void 0) { z = 0.0; }
  4363. if (w === void 0) { w = 1.0; }
  4364. this.x = x;
  4365. this.y = y;
  4366. this.z = z;
  4367. this.w = w;
  4368. }
  4369. /**
  4370. * Gets a string representation for the current quaternion
  4371. * @returns a string with the Quaternion coordinates
  4372. */
  4373. Quaternion.prototype.toString = function () {
  4374. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  4375. };
  4376. /**
  4377. * Gets the class name of the quaternion
  4378. * @returns the string "Quaternion"
  4379. */
  4380. Quaternion.prototype.getClassName = function () {
  4381. return "Quaternion";
  4382. };
  4383. /**
  4384. * Gets a hash code for this quaternion
  4385. * @returns the quaternion hash code
  4386. */
  4387. Quaternion.prototype.getHashCode = function () {
  4388. var hash = this.x || 0;
  4389. hash = (hash * 397) ^ (this.y || 0);
  4390. hash = (hash * 397) ^ (this.z || 0);
  4391. hash = (hash * 397) ^ (this.w || 0);
  4392. return hash;
  4393. };
  4394. /**
  4395. * Copy the quaternion to an array
  4396. * @returns a new array populated with 4 elements from the quaternion coordinates
  4397. */
  4398. Quaternion.prototype.asArray = function () {
  4399. return [this.x, this.y, this.z, this.w];
  4400. };
  4401. /**
  4402. * Check if two quaternions are equals
  4403. * @param otherQuaternion defines the second operand
  4404. * @return true if the current quaternion and the given one coordinates are strictly equals
  4405. */
  4406. Quaternion.prototype.equals = function (otherQuaternion) {
  4407. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  4408. };
  4409. /**
  4410. * Clone the current quaternion
  4411. * @returns a new quaternion copied from the current one
  4412. */
  4413. Quaternion.prototype.clone = function () {
  4414. return new Quaternion(this.x, this.y, this.z, this.w);
  4415. };
  4416. /**
  4417. * Copy a quaternion to the current one
  4418. * @param other defines the other quaternion
  4419. * @returns the updated current quaternion
  4420. */
  4421. Quaternion.prototype.copyFrom = function (other) {
  4422. this.x = other.x;
  4423. this.y = other.y;
  4424. this.z = other.z;
  4425. this.w = other.w;
  4426. return this;
  4427. };
  4428. /**
  4429. * Updates the current quaternion with the given float coordinates
  4430. * @param x defines the x coordinate
  4431. * @param y defines the y coordinate
  4432. * @param z defines the z coordinate
  4433. * @param w defines the w coordinate
  4434. * @returns the updated current quaternion
  4435. */
  4436. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  4437. this.x = x;
  4438. this.y = y;
  4439. this.z = z;
  4440. this.w = w;
  4441. return this;
  4442. };
  4443. /**
  4444. * Updates the current quaternion from the given float coordinates
  4445. * @param x defines the x coordinate
  4446. * @param y defines the y coordinate
  4447. * @param z defines the z coordinate
  4448. * @param w defines the w coordinate
  4449. * @returns the updated current quaternion
  4450. */
  4451. Quaternion.prototype.set = function (x, y, z, w) {
  4452. return this.copyFromFloats(x, y, z, w);
  4453. };
  4454. /**
  4455. * Adds two quaternions
  4456. * @param other defines the second operand
  4457. * @returns a new quaternion as the addition result of the given one and the current quaternion
  4458. */
  4459. Quaternion.prototype.add = function (other) {
  4460. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  4461. };
  4462. /**
  4463. * Add a quaternion to the current one
  4464. * @param other defines the quaternion to add
  4465. * @returns the current quaternion
  4466. */
  4467. Quaternion.prototype.addInPlace = function (other) {
  4468. this.x += other.x;
  4469. this.y += other.y;
  4470. this.z += other.z;
  4471. this.w += other.w;
  4472. return this;
  4473. };
  4474. /**
  4475. * Subtract two quaternions
  4476. * @param other defines the second operand
  4477. * @returns a new quaternion as the subtraction result of the given one from the current one
  4478. */
  4479. Quaternion.prototype.subtract = function (other) {
  4480. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  4481. };
  4482. /**
  4483. * Multiplies the current quaternion by a scale factor
  4484. * @param value defines the scale factor
  4485. * @returns a new quaternion set by multiplying the current quaternion coordinates by the float "scale"
  4486. */
  4487. Quaternion.prototype.scale = function (value) {
  4488. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  4489. };
  4490. /**
  4491. * Scale the current quaternion values by a factor and stores the result to a given quaternion
  4492. * @param scale defines the scale factor
  4493. * @param result defines the Quaternion object where to store the result
  4494. * @returns the unmodified current quaternion
  4495. */
  4496. Quaternion.prototype.scaleToRef = function (scale, result) {
  4497. result.x = this.x * scale;
  4498. result.y = this.y * scale;
  4499. result.z = this.z * scale;
  4500. result.w = this.w * scale;
  4501. return this;
  4502. };
  4503. /**
  4504. * Multiplies in place the current quaternion by a scale factor
  4505. * @param value defines the scale factor
  4506. * @returns the current modified quaternion
  4507. */
  4508. Quaternion.prototype.scaleInPlace = function (value) {
  4509. this.x *= value;
  4510. this.y *= value;
  4511. this.z *= value;
  4512. this.w *= value;
  4513. return this;
  4514. };
  4515. /**
  4516. * Scale the current quaternion values by a factor and add the result to a given quaternion
  4517. * @param scale defines the scale factor
  4518. * @param result defines the Quaternion object where to store the result
  4519. * @returns the unmodified current quaternion
  4520. */
  4521. Quaternion.prototype.scaleAndAddToRef = function (scale, result) {
  4522. result.x += this.x * scale;
  4523. result.y += this.y * scale;
  4524. result.z += this.z * scale;
  4525. result.w += this.w * scale;
  4526. return this;
  4527. };
  4528. /**
  4529. * Multiplies two quaternions
  4530. * @param q1 defines the second operand
  4531. * @returns a new quaternion set as the multiplication result of the current one with the given one "q1"
  4532. */
  4533. Quaternion.prototype.multiply = function (q1) {
  4534. var result = new Quaternion(0, 0, 0, 1.0);
  4535. this.multiplyToRef(q1, result);
  4536. return result;
  4537. };
  4538. /**
  4539. * Sets the given "result" as the the multiplication result of the current one with the given one "q1"
  4540. * @param q1 defines the second operand
  4541. * @param result defines the target quaternion
  4542. * @returns the current quaternion
  4543. */
  4544. Quaternion.prototype.multiplyToRef = function (q1, result) {
  4545. var x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  4546. var y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  4547. var z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  4548. var w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  4549. result.copyFromFloats(x, y, z, w);
  4550. return this;
  4551. };
  4552. /**
  4553. * Updates the current quaternion with the multiplication of itself with the given one "q1"
  4554. * @param q1 defines the second operand
  4555. * @returns the currentupdated quaternion
  4556. */
  4557. Quaternion.prototype.multiplyInPlace = function (q1) {
  4558. this.multiplyToRef(q1, this);
  4559. return this;
  4560. };
  4561. /**
  4562. * Conjugates (1-q) the current quaternion and stores the result in the given quaternion
  4563. * @param ref defines the target quaternion
  4564. * @returns the current quaternion
  4565. */
  4566. Quaternion.prototype.conjugateToRef = function (ref) {
  4567. ref.copyFromFloats(-this.x, -this.y, -this.z, this.w);
  4568. return this;
  4569. };
  4570. /**
  4571. * Conjugates in place (1-q) the current quaternion
  4572. * @returns the current updated quaternion
  4573. */
  4574. Quaternion.prototype.conjugateInPlace = function () {
  4575. this.x *= -1;
  4576. this.y *= -1;
  4577. this.z *= -1;
  4578. return this;
  4579. };
  4580. /**
  4581. * Conjugates in place (1-q) the current quaternion
  4582. * @returns a new quaternion
  4583. */
  4584. Quaternion.prototype.conjugate = function () {
  4585. var result = new Quaternion(-this.x, -this.y, -this.z, this.w);
  4586. return result;
  4587. };
  4588. /**
  4589. * Gets length of current quaternion
  4590. * @returns the quaternion length (float)
  4591. */
  4592. Quaternion.prototype.length = function () {
  4593. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  4594. };
  4595. /**
  4596. * Normalize in place the current quaternion
  4597. * @returns the current updated quaternion
  4598. */
  4599. Quaternion.prototype.normalize = function () {
  4600. var length = 1.0 / this.length();
  4601. this.x *= length;
  4602. this.y *= length;
  4603. this.z *= length;
  4604. this.w *= length;
  4605. return this;
  4606. };
  4607. /**
  4608. * Returns a new Vector3 set with the Euler angles translated from the current quaternion
  4609. * @param order is a reserved parameter and is ignore for now
  4610. * @returns a new Vector3 containing the Euler angles
  4611. */
  4612. Quaternion.prototype.toEulerAngles = function (order) {
  4613. if (order === void 0) { order = "YZX"; }
  4614. var result = Vector3.Zero();
  4615. this.toEulerAnglesToRef(result, order);
  4616. return result;
  4617. };
  4618. /**
  4619. * Sets the given vector3 "result" with the Euler angles translated from the current quaternion
  4620. * @param result defines the vector which will be filled with the Euler angles
  4621. * @param order is a reserved parameter and is ignore for now
  4622. * @returns the current unchanged quaternion
  4623. */
  4624. Quaternion.prototype.toEulerAnglesToRef = function (result, order) {
  4625. if (order === void 0) { order = "YZX"; }
  4626. var qz = this.z;
  4627. var qx = this.x;
  4628. var qy = this.y;
  4629. var qw = this.w;
  4630. var sqw = qw * qw;
  4631. var sqz = qz * qz;
  4632. var sqx = qx * qx;
  4633. var sqy = qy * qy;
  4634. var zAxisY = qy * qz - qx * qw;
  4635. var limit = .4999999;
  4636. if (zAxisY < -limit) {
  4637. result.y = 2 * Math.atan2(qy, qw);
  4638. result.x = Math.PI / 2;
  4639. result.z = 0;
  4640. }
  4641. else if (zAxisY > limit) {
  4642. result.y = 2 * Math.atan2(qy, qw);
  4643. result.x = -Math.PI / 2;
  4644. result.z = 0;
  4645. }
  4646. else {
  4647. result.z = Math.atan2(2.0 * (qx * qy + qz * qw), (-sqz - sqx + sqy + sqw));
  4648. result.x = Math.asin(-2.0 * (qz * qy - qx * qw));
  4649. result.y = Math.atan2(2.0 * (qz * qx + qy * qw), (sqz - sqx - sqy + sqw));
  4650. }
  4651. return this;
  4652. };
  4653. /**
  4654. * Updates the given rotation matrix with the current quaternion values
  4655. * @param result defines the target matrix
  4656. * @returns the current unchanged quaternion
  4657. */
  4658. Quaternion.prototype.toRotationMatrix = function (result) {
  4659. var xx = this.x * this.x;
  4660. var yy = this.y * this.y;
  4661. var zz = this.z * this.z;
  4662. var xy = this.x * this.y;
  4663. var zw = this.z * this.w;
  4664. var zx = this.z * this.x;
  4665. var yw = this.y * this.w;
  4666. var yz = this.y * this.z;
  4667. var xw = this.x * this.w;
  4668. result.m[0] = 1.0 - (2.0 * (yy + zz));
  4669. result.m[1] = 2.0 * (xy + zw);
  4670. result.m[2] = 2.0 * (zx - yw);
  4671. result.m[3] = 0;
  4672. result.m[4] = 2.0 * (xy - zw);
  4673. result.m[5] = 1.0 - (2.0 * (zz + xx));
  4674. result.m[6] = 2.0 * (yz + xw);
  4675. result.m[7] = 0;
  4676. result.m[8] = 2.0 * (zx + yw);
  4677. result.m[9] = 2.0 * (yz - xw);
  4678. result.m[10] = 1.0 - (2.0 * (yy + xx));
  4679. result.m[11] = 0;
  4680. result.m[12] = 0;
  4681. result.m[13] = 0;
  4682. result.m[14] = 0;
  4683. result.m[15] = 1.0;
  4684. result._markAsUpdated();
  4685. return this;
  4686. };
  4687. /**
  4688. * Updates the current quaternion from the given rotation matrix values
  4689. * @param matrix defines the source matrix
  4690. * @returns the current updated quaternion
  4691. */
  4692. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  4693. Quaternion.FromRotationMatrixToRef(matrix, this);
  4694. return this;
  4695. };
  4696. // Statics
  4697. /**
  4698. * Creates a new quaternion from a rotation matrix
  4699. * @param matrix defines the source matrix
  4700. * @returns a new quaternion created from the given rotation matrix values
  4701. */
  4702. Quaternion.FromRotationMatrix = function (matrix) {
  4703. var result = new Quaternion();
  4704. Quaternion.FromRotationMatrixToRef(matrix, result);
  4705. return result;
  4706. };
  4707. /**
  4708. * Updates the given quaternion with the given rotation matrix values
  4709. * @param matrix defines the source matrix
  4710. * @param result defines the target quaternion
  4711. */
  4712. Quaternion.FromRotationMatrixToRef = function (matrix, result) {
  4713. var data = matrix.m;
  4714. var m11 = data[0], m12 = data[4], m13 = data[8];
  4715. var m21 = data[1], m22 = data[5], m23 = data[9];
  4716. var m31 = data[2], m32 = data[6], m33 = data[10];
  4717. var trace = m11 + m22 + m33;
  4718. var s;
  4719. if (trace > 0) {
  4720. s = 0.5 / Math.sqrt(trace + 1.0);
  4721. result.w = 0.25 / s;
  4722. result.x = (m32 - m23) * s;
  4723. result.y = (m13 - m31) * s;
  4724. result.z = (m21 - m12) * s;
  4725. }
  4726. else if (m11 > m22 && m11 > m33) {
  4727. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  4728. result.w = (m32 - m23) / s;
  4729. result.x = 0.25 * s;
  4730. result.y = (m12 + m21) / s;
  4731. result.z = (m13 + m31) / s;
  4732. }
  4733. else if (m22 > m33) {
  4734. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  4735. result.w = (m13 - m31) / s;
  4736. result.x = (m12 + m21) / s;
  4737. result.y = 0.25 * s;
  4738. result.z = (m23 + m32) / s;
  4739. }
  4740. else {
  4741. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  4742. result.w = (m21 - m12) / s;
  4743. result.x = (m13 + m31) / s;
  4744. result.y = (m23 + m32) / s;
  4745. result.z = 0.25 * s;
  4746. }
  4747. };
  4748. /**
  4749. * Returns the dot product (float) between the quaternions "left" and "right"
  4750. * @param left defines the left operand
  4751. * @param right defines the right operand
  4752. * @returns the dot product
  4753. */
  4754. Quaternion.Dot = function (left, right) {
  4755. return (left.x * right.x + left.y * right.y + left.z * right.z + left.w * right.w);
  4756. };
  4757. /**
  4758. * Checks if the two quaternions are close to each other
  4759. * @param quat0 defines the first quaternion to check
  4760. * @param quat1 defines the second quaternion to check
  4761. * @returns true if the two quaternions are close to each other
  4762. */
  4763. Quaternion.AreClose = function (quat0, quat1) {
  4764. var dot = Quaternion.Dot(quat0, quat1);
  4765. return dot >= 0;
  4766. };
  4767. /**
  4768. * Creates an empty quaternion
  4769. * @returns a new quaternion set to (0.0, 0.0, 0.0)
  4770. */
  4771. Quaternion.Zero = function () {
  4772. return new Quaternion(0.0, 0.0, 0.0, 0.0);
  4773. };
  4774. /**
  4775. * Inverse a given quaternion
  4776. * @param q defines the source quaternion
  4777. * @returns a new quaternion as the inverted current quaternion
  4778. */
  4779. Quaternion.Inverse = function (q) {
  4780. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  4781. };
  4782. /**
  4783. * Creates an identity quaternion
  4784. * @returns the identity quaternion
  4785. */
  4786. Quaternion.Identity = function () {
  4787. return new Quaternion(0.0, 0.0, 0.0, 1.0);
  4788. };
  4789. /**
  4790. * Gets a boolean indicating if the given quaternion is identity
  4791. * @param quaternion defines the quaternion to check
  4792. * @returns true if the quaternion is identity
  4793. */
  4794. Quaternion.IsIdentity = function (quaternion) {
  4795. return quaternion && quaternion.x === 0 && quaternion.y === 0 && quaternion.z === 0 && quaternion.w === 1;
  4796. };
  4797. /**
  4798. * Creates a quaternion from a rotation around an axis
  4799. * @param axis defines the axis to use
  4800. * @param angle defines the angle to use
  4801. * @returns a new quaternion created from the given axis (Vector3) and angle in radians (float)
  4802. */
  4803. Quaternion.RotationAxis = function (axis, angle) {
  4804. return Quaternion.RotationAxisToRef(axis, angle, new Quaternion());
  4805. };
  4806. /**
  4807. * Creates a rotation around an axis and stores it into the given quaternion
  4808. * @param axis defines the axis to use
  4809. * @param angle defines the angle to use
  4810. * @param result defines the target quaternion
  4811. * @returns the target quaternion
  4812. */
  4813. Quaternion.RotationAxisToRef = function (axis, angle, result) {
  4814. var sin = Math.sin(angle / 2);
  4815. axis.normalize();
  4816. result.w = Math.cos(angle / 2);
  4817. result.x = axis.x * sin;
  4818. result.y = axis.y * sin;
  4819. result.z = axis.z * sin;
  4820. return result;
  4821. };
  4822. /**
  4823. * Creates a new quaternion from data stored into an array
  4824. * @param array defines the data source
  4825. * @param offset defines the offset in the source array where the data starts
  4826. * @returns a new quaternion
  4827. */
  4828. Quaternion.FromArray = function (array, offset) {
  4829. if (!offset) {
  4830. offset = 0;
  4831. }
  4832. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  4833. };
  4834. /**
  4835. * Creates a new quaternion from the given Euler float angles (y, x, z)
  4836. * @param yaw defines the rotation around Y axis
  4837. * @param pitch defines the rotation around X axis
  4838. * @param roll defines the rotation around Z axis
  4839. * @returns the new quaternion
  4840. */
  4841. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  4842. var q = new Quaternion();
  4843. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, q);
  4844. return q;
  4845. };
  4846. /**
  4847. * Creates a new rotation from the given Euler float angles (y, x, z) and stores it in the target quaternion
  4848. * @param yaw defines the rotation around Y axis
  4849. * @param pitch defines the rotation around X axis
  4850. * @param roll defines the rotation around Z axis
  4851. * @param result defines the target quaternion
  4852. */
  4853. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  4854. // Produces a quaternion from Euler angles in the z-y-x orientation (Tait-Bryan angles)
  4855. var halfRoll = roll * 0.5;
  4856. var halfPitch = pitch * 0.5;
  4857. var halfYaw = yaw * 0.5;
  4858. var sinRoll = Math.sin(halfRoll);
  4859. var cosRoll = Math.cos(halfRoll);
  4860. var sinPitch = Math.sin(halfPitch);
  4861. var cosPitch = Math.cos(halfPitch);
  4862. var sinYaw = Math.sin(halfYaw);
  4863. var cosYaw = Math.cos(halfYaw);
  4864. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  4865. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  4866. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  4867. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  4868. };
  4869. /**
  4870. * Creates a new quaternion from the given Euler float angles expressed in z-x-z orientation
  4871. * @param alpha defines the rotation around first axis
  4872. * @param beta defines the rotation around second axis
  4873. * @param gamma defines the rotation around third axis
  4874. * @returns the new quaternion
  4875. */
  4876. Quaternion.RotationAlphaBetaGamma = function (alpha, beta, gamma) {
  4877. var result = new Quaternion();
  4878. Quaternion.RotationAlphaBetaGammaToRef(alpha, beta, gamma, result);
  4879. return result;
  4880. };
  4881. /**
  4882. * Creates a new quaternion from the given Euler float angles expressed in z-x-z orientation and stores it in the target quaternion
  4883. * @param alpha defines the rotation around first axis
  4884. * @param beta defines the rotation around second axis
  4885. * @param gamma defines the rotation around third axis
  4886. * @param result defines the target quaternion
  4887. */
  4888. Quaternion.RotationAlphaBetaGammaToRef = function (alpha, beta, gamma, result) {
  4889. // Produces a quaternion from Euler angles in the z-x-z orientation
  4890. var halfGammaPlusAlpha = (gamma + alpha) * 0.5;
  4891. var halfGammaMinusAlpha = (gamma - alpha) * 0.5;
  4892. var halfBeta = beta * 0.5;
  4893. result.x = Math.cos(halfGammaMinusAlpha) * Math.sin(halfBeta);
  4894. result.y = Math.sin(halfGammaMinusAlpha) * Math.sin(halfBeta);
  4895. result.z = Math.sin(halfGammaPlusAlpha) * Math.cos(halfBeta);
  4896. result.w = Math.cos(halfGammaPlusAlpha) * Math.cos(halfBeta);
  4897. };
  4898. /**
  4899. * 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)
  4900. * @param axis1 defines the first axis
  4901. * @param axis2 defines the second axis
  4902. * @param axis3 defines the third axis
  4903. * @returns the new quaternion
  4904. */
  4905. Quaternion.RotationQuaternionFromAxis = function (axis1, axis2, axis3) {
  4906. var quat = new Quaternion(0.0, 0.0, 0.0, 0.0);
  4907. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  4908. return quat;
  4909. };
  4910. /**
  4911. * 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
  4912. * @param axis1 defines the first axis
  4913. * @param axis2 defines the second axis
  4914. * @param axis3 defines the third axis
  4915. * @param ref defines the target quaternion
  4916. */
  4917. Quaternion.RotationQuaternionFromAxisToRef = function (axis1, axis2, axis3, ref) {
  4918. var rotMat = MathTmp.Matrix[0];
  4919. Matrix.FromXYZAxesToRef(axis1.normalize(), axis2.normalize(), axis3.normalize(), rotMat);
  4920. Quaternion.FromRotationMatrixToRef(rotMat, ref);
  4921. };
  4922. /**
  4923. * Interpolates between two quaternions
  4924. * @param left defines first quaternion
  4925. * @param right defines second quaternion
  4926. * @param amount defines the gradient to use
  4927. * @returns the new interpolated quaternion
  4928. */
  4929. Quaternion.Slerp = function (left, right, amount) {
  4930. var result = Quaternion.Identity();
  4931. Quaternion.SlerpToRef(left, right, amount, result);
  4932. return result;
  4933. };
  4934. /**
  4935. * Interpolates between two quaternions and stores it into a target quaternion
  4936. * @param left defines first quaternion
  4937. * @param right defines second quaternion
  4938. * @param amount defines the gradient to use
  4939. * @param result defines the target quaternion
  4940. */
  4941. Quaternion.SlerpToRef = function (left, right, amount, result) {
  4942. var num2;
  4943. var num3;
  4944. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  4945. var flag = false;
  4946. if (num4 < 0) {
  4947. flag = true;
  4948. num4 = -num4;
  4949. }
  4950. if (num4 > 0.999999) {
  4951. num3 = 1 - amount;
  4952. num2 = flag ? -amount : amount;
  4953. }
  4954. else {
  4955. var num5 = Math.acos(num4);
  4956. var num6 = (1.0 / Math.sin(num5));
  4957. num3 = (Math.sin((1.0 - amount) * num5)) * num6;
  4958. num2 = flag ? ((-Math.sin(amount * num5)) * num6) : ((Math.sin(amount * num5)) * num6);
  4959. }
  4960. result.x = (num3 * left.x) + (num2 * right.x);
  4961. result.y = (num3 * left.y) + (num2 * right.y);
  4962. result.z = (num3 * left.z) + (num2 * right.z);
  4963. result.w = (num3 * left.w) + (num2 * right.w);
  4964. };
  4965. /**
  4966. * Interpolate between two quaternions using Hermite interpolation
  4967. * @param value1 defines first quaternion
  4968. * @param tangent1 defines the incoming tangent
  4969. * @param value2 defines second quaternion
  4970. * @param tangent2 defines the outgoing tangent
  4971. * @param amount defines the target quaternion
  4972. * @returns the new interpolated quaternion
  4973. */
  4974. Quaternion.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  4975. var squared = amount * amount;
  4976. var cubed = amount * squared;
  4977. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  4978. var part2 = (-2.0 * cubed) + (3.0 * squared);
  4979. var part3 = (cubed - (2.0 * squared)) + amount;
  4980. var part4 = cubed - squared;
  4981. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  4982. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  4983. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  4984. var w = (((value1.w * part1) + (value2.w * part2)) + (tangent1.w * part3)) + (tangent2.w * part4);
  4985. return new Quaternion(x, y, z, w);
  4986. };
  4987. return Quaternion;
  4988. }());
  4989. BABYLON.Quaternion = Quaternion;
  4990. /**
  4991. * Class used to store matrix data (4x4)
  4992. */
  4993. var Matrix = /** @class */ (function () {
  4994. /**
  4995. * Creates an empty matrix (filled with zeros)
  4996. */
  4997. function Matrix() {
  4998. this._isIdentity = false;
  4999. this._isIdentityDirty = true;
  5000. /**
  5001. * Gets or sets the internal data of the matrix
  5002. */
  5003. this.m = new Float32Array(16);
  5004. this._markAsUpdated();
  5005. }
  5006. /** @hidden */
  5007. Matrix.prototype._markAsUpdated = function () {
  5008. this.updateFlag = Matrix._updateFlagSeed++;
  5009. this._isIdentityDirty = true;
  5010. };
  5011. // Properties
  5012. /**
  5013. * Check if the current matrix is indentity
  5014. * @param considerAsTextureMatrix defines if the current matrix must be considered as a texture matrix (3x2)
  5015. * @returns true is the matrix is the identity matrix
  5016. */
  5017. Matrix.prototype.isIdentity = function (considerAsTextureMatrix) {
  5018. if (considerAsTextureMatrix === void 0) { considerAsTextureMatrix = false; }
  5019. if (this._isIdentityDirty) {
  5020. this._isIdentityDirty = false;
  5021. if (this.m[0] !== 1.0 || this.m[5] !== 1.0 || this.m[15] !== 1.0) {
  5022. this._isIdentity = false;
  5023. }
  5024. else if (this.m[1] !== 0.0 || this.m[2] !== 0.0 || this.m[3] !== 0.0 ||
  5025. this.m[4] !== 0.0 || this.m[6] !== 0.0 || this.m[7] !== 0.0 ||
  5026. this.m[8] !== 0.0 || this.m[9] !== 0.0 || this.m[11] !== 0.0 ||
  5027. this.m[12] !== 0.0 || this.m[13] !== 0.0 || this.m[14] !== 0.0) {
  5028. this._isIdentity = false;
  5029. }
  5030. else {
  5031. this._isIdentity = true;
  5032. }
  5033. if (!considerAsTextureMatrix && this.m[10] !== 1.0) {
  5034. this._isIdentity = false;
  5035. }
  5036. }
  5037. return this._isIdentity;
  5038. };
  5039. /**
  5040. * Gets the determinant of the matrix
  5041. * @returns the matrix determinant
  5042. */
  5043. Matrix.prototype.determinant = function () {
  5044. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  5045. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  5046. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  5047. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  5048. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  5049. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  5050. return ((((this.m[0] * (((this.m[5] * temp1) - (this.m[6] * temp2)) + (this.m[7] * temp3))) - (this.m[1] * (((this.m[4] * temp1) -
  5051. (this.m[6] * temp4)) + (this.m[7] * temp5)))) + (this.m[2] * (((this.m[4] * temp2) - (this.m[5] * temp4)) + (this.m[7] * temp6)))) -
  5052. (this.m[3] * (((this.m[4] * temp3) - (this.m[5] * temp5)) + (this.m[6] * temp6))));
  5053. };
  5054. // Methods
  5055. /**
  5056. * Returns the matrix as a Float32Array
  5057. * @returns the matrix underlying array
  5058. */
  5059. Matrix.prototype.toArray = function () {
  5060. return this.m;
  5061. };
  5062. /**
  5063. * Returns the matrix as a Float32Array
  5064. * @returns the matrix underlying array.
  5065. */
  5066. Matrix.prototype.asArray = function () {
  5067. return this.toArray();
  5068. };
  5069. /**
  5070. * Inverts the current matrix in place
  5071. * @returns the current inverted matrix
  5072. */
  5073. Matrix.prototype.invert = function () {
  5074. this.invertToRef(this);
  5075. return this;
  5076. };
  5077. /**
  5078. * Sets all the matrix elements to zero
  5079. * @returns the current matrix
  5080. */
  5081. Matrix.prototype.reset = function () {
  5082. for (var index = 0; index < 16; index++) {
  5083. this.m[index] = 0.0;
  5084. }
  5085. this._markAsUpdated();
  5086. return this;
  5087. };
  5088. /**
  5089. * Adds the current matrix with a second one
  5090. * @param other defines the matrix to add
  5091. * @returns a new matrix as the addition of the current matrix and the given one
  5092. */
  5093. Matrix.prototype.add = function (other) {
  5094. var result = new Matrix();
  5095. this.addToRef(other, result);
  5096. return result;
  5097. };
  5098. /**
  5099. * Sets the given matrix "result" to the addition of the current matrix and the given one
  5100. * @param other defines the matrix to add
  5101. * @param result defines the target matrix
  5102. * @returns the current matrix
  5103. */
  5104. Matrix.prototype.addToRef = function (other, result) {
  5105. for (var index = 0; index < 16; index++) {
  5106. result.m[index] = this.m[index] + other.m[index];
  5107. }
  5108. result._markAsUpdated();
  5109. return this;
  5110. };
  5111. /**
  5112. * Adds in place the given matrix to the current matrix
  5113. * @param other defines the second operand
  5114. * @returns the current updated matrix
  5115. */
  5116. Matrix.prototype.addToSelf = function (other) {
  5117. for (var index = 0; index < 16; index++) {
  5118. this.m[index] += other.m[index];
  5119. }
  5120. this._markAsUpdated();
  5121. return this;
  5122. };
  5123. /**
  5124. * Sets the given matrix to the current inverted Matrix
  5125. * @param other defines the target matrix
  5126. * @returns the unmodified current matrix
  5127. */
  5128. Matrix.prototype.invertToRef = function (other) {
  5129. var l1 = this.m[0];
  5130. var l2 = this.m[1];
  5131. var l3 = this.m[2];
  5132. var l4 = this.m[3];
  5133. var l5 = this.m[4];
  5134. var l6 = this.m[5];
  5135. var l7 = this.m[6];
  5136. var l8 = this.m[7];
  5137. var l9 = this.m[8];
  5138. var l10 = this.m[9];
  5139. var l11 = this.m[10];
  5140. var l12 = this.m[11];
  5141. var l13 = this.m[12];
  5142. var l14 = this.m[13];
  5143. var l15 = this.m[14];
  5144. var l16 = this.m[15];
  5145. var l17 = (l11 * l16) - (l12 * l15);
  5146. var l18 = (l10 * l16) - (l12 * l14);
  5147. var l19 = (l10 * l15) - (l11 * l14);
  5148. var l20 = (l9 * l16) - (l12 * l13);
  5149. var l21 = (l9 * l15) - (l11 * l13);
  5150. var l22 = (l9 * l14) - (l10 * l13);
  5151. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  5152. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  5153. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  5154. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  5155. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  5156. var l28 = (l7 * l16) - (l8 * l15);
  5157. var l29 = (l6 * l16) - (l8 * l14);
  5158. var l30 = (l6 * l15) - (l7 * l14);
  5159. var l31 = (l5 * l16) - (l8 * l13);
  5160. var l32 = (l5 * l15) - (l7 * l13);
  5161. var l33 = (l5 * l14) - (l6 * l13);
  5162. var l34 = (l7 * l12) - (l8 * l11);
  5163. var l35 = (l6 * l12) - (l8 * l10);
  5164. var l36 = (l6 * l11) - (l7 * l10);
  5165. var l37 = (l5 * l12) - (l8 * l9);
  5166. var l38 = (l5 * l11) - (l7 * l9);
  5167. var l39 = (l5 * l10) - (l6 * l9);
  5168. other.m[0] = l23 * l27;
  5169. other.m[4] = l24 * l27;
  5170. other.m[8] = l25 * l27;
  5171. other.m[12] = l26 * l27;
  5172. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  5173. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  5174. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  5175. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  5176. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  5177. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  5178. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  5179. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  5180. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  5181. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  5182. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  5183. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  5184. other._markAsUpdated();
  5185. return this;
  5186. };
  5187. /**
  5188. * Inserts the translation vector (using 3 floats) in the current matrix
  5189. * @param x defines the 1st component of the translation
  5190. * @param y defines the 2nd component of the translation
  5191. * @param z defines the 3rd component of the translation
  5192. * @returns the current updated matrix
  5193. */
  5194. Matrix.prototype.setTranslationFromFloats = function (x, y, z) {
  5195. this.m[12] = x;
  5196. this.m[13] = y;
  5197. this.m[14] = z;
  5198. this._markAsUpdated();
  5199. return this;
  5200. };
  5201. /**
  5202. * Inserts the translation vector in the current matrix
  5203. * @param vector3 defines the translation to insert
  5204. * @returns the current updated matrix
  5205. */
  5206. Matrix.prototype.setTranslation = function (vector3) {
  5207. this.m[12] = vector3.x;
  5208. this.m[13] = vector3.y;
  5209. this.m[14] = vector3.z;
  5210. this._markAsUpdated();
  5211. return this;
  5212. };
  5213. /**
  5214. * Gets the translation value of the current matrix
  5215. * @returns a new Vector3 as the extracted translation from the matrix
  5216. */
  5217. Matrix.prototype.getTranslation = function () {
  5218. return new Vector3(this.m[12], this.m[13], this.m[14]);
  5219. };
  5220. /**
  5221. * Fill a Vector3 with the extracted translation from the matrix
  5222. * @param result defines the Vector3 where to store the translation
  5223. * @returns the current matrix
  5224. */
  5225. Matrix.prototype.getTranslationToRef = function (result) {
  5226. result.x = this.m[12];
  5227. result.y = this.m[13];
  5228. result.z = this.m[14];
  5229. return this;
  5230. };
  5231. /**
  5232. * Remove rotation and scaling part from the matrix
  5233. * @returns the updated matrix
  5234. */
  5235. Matrix.prototype.removeRotationAndScaling = function () {
  5236. this.setRowFromFloats(0, 1, 0, 0, 0);
  5237. this.setRowFromFloats(1, 0, 1, 0, 0);
  5238. this.setRowFromFloats(2, 0, 0, 1, 0);
  5239. return this;
  5240. };
  5241. /**
  5242. * Multiply two matrices
  5243. * @param other defines the second operand
  5244. * @returns a new matrix set with the multiplication result of the current Matrix and the given one
  5245. */
  5246. Matrix.prototype.multiply = function (other) {
  5247. var result = new Matrix();
  5248. this.multiplyToRef(other, result);
  5249. return result;
  5250. };
  5251. /**
  5252. * Copy the current matrix from the given one
  5253. * @param other defines the source matrix
  5254. * @returns the current updated matrix
  5255. */
  5256. Matrix.prototype.copyFrom = function (other) {
  5257. for (var index = 0; index < 16; index++) {
  5258. this.m[index] = other.m[index];
  5259. }
  5260. this._markAsUpdated();
  5261. return this;
  5262. };
  5263. /**
  5264. * Populates the given array from the starting index with the current matrix values
  5265. * @param array defines the target array
  5266. * @param offset defines the offset in the target array where to start storing values
  5267. * @returns the current matrix
  5268. */
  5269. Matrix.prototype.copyToArray = function (array, offset) {
  5270. if (offset === void 0) { offset = 0; }
  5271. for (var index = 0; index < 16; index++) {
  5272. array[offset + index] = this.m[index];
  5273. }
  5274. return this;
  5275. };
  5276. /**
  5277. * Sets the given matrix "result" with the multiplication result of the current Matrix and the given one
  5278. * @param other defines the second operand
  5279. * @param result defines the matrix where to store the multiplication
  5280. * @returns the current matrix
  5281. */
  5282. Matrix.prototype.multiplyToRef = function (other, result) {
  5283. this.multiplyToArray(other, result.m, 0);
  5284. result._markAsUpdated();
  5285. return this;
  5286. };
  5287. /**
  5288. * Sets the Float32Array "result" from the given index "offset" with the multiplication of the current matrix and the given one
  5289. * @param other defines the second operand
  5290. * @param result defines the array where to store the multiplication
  5291. * @param offset defines the offset in the target array where to start storing values
  5292. * @returns the current matrix
  5293. */
  5294. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  5295. var tm0 = this.m[0];
  5296. var tm1 = this.m[1];
  5297. var tm2 = this.m[2];
  5298. var tm3 = this.m[3];
  5299. var tm4 = this.m[4];
  5300. var tm5 = this.m[5];
  5301. var tm6 = this.m[6];
  5302. var tm7 = this.m[7];
  5303. var tm8 = this.m[8];
  5304. var tm9 = this.m[9];
  5305. var tm10 = this.m[10];
  5306. var tm11 = this.m[11];
  5307. var tm12 = this.m[12];
  5308. var tm13 = this.m[13];
  5309. var tm14 = this.m[14];
  5310. var tm15 = this.m[15];
  5311. var om0 = other.m[0];
  5312. var om1 = other.m[1];
  5313. var om2 = other.m[2];
  5314. var om3 = other.m[3];
  5315. var om4 = other.m[4];
  5316. var om5 = other.m[5];
  5317. var om6 = other.m[6];
  5318. var om7 = other.m[7];
  5319. var om8 = other.m[8];
  5320. var om9 = other.m[9];
  5321. var om10 = other.m[10];
  5322. var om11 = other.m[11];
  5323. var om12 = other.m[12];
  5324. var om13 = other.m[13];
  5325. var om14 = other.m[14];
  5326. var om15 = other.m[15];
  5327. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  5328. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  5329. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  5330. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  5331. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  5332. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  5333. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  5334. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  5335. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  5336. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  5337. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  5338. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  5339. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  5340. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  5341. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  5342. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  5343. return this;
  5344. };
  5345. /**
  5346. * Check equality between this matrix and a second one
  5347. * @param value defines the second matrix to compare
  5348. * @returns true is the current matrix and the given one values are strictly equal
  5349. */
  5350. Matrix.prototype.equals = function (value) {
  5351. return value &&
  5352. (this.m[0] === value.m[0] && this.m[1] === value.m[1] && this.m[2] === value.m[2] && this.m[3] === value.m[3] &&
  5353. this.m[4] === value.m[4] && this.m[5] === value.m[5] && this.m[6] === value.m[6] && this.m[7] === value.m[7] &&
  5354. this.m[8] === value.m[8] && this.m[9] === value.m[9] && this.m[10] === value.m[10] && this.m[11] === value.m[11] &&
  5355. this.m[12] === value.m[12] && this.m[13] === value.m[13] && this.m[14] === value.m[14] && this.m[15] === value.m[15]);
  5356. };
  5357. /**
  5358. * Clone the current matrix
  5359. * @returns a new matrix from the current matrix
  5360. */
  5361. Matrix.prototype.clone = function () {
  5362. return Matrix.FromValues(this.m[0], this.m[1], this.m[2], this.m[3], this.m[4], this.m[5], this.m[6], this.m[7], this.m[8], this.m[9], this.m[10], this.m[11], this.m[12], this.m[13], this.m[14], this.m[15]);
  5363. };
  5364. /**
  5365. * Returns the name of the current matrix class
  5366. * @returns the string "Matrix"
  5367. */
  5368. Matrix.prototype.getClassName = function () {
  5369. return "Matrix";
  5370. };
  5371. /**
  5372. * Gets the hash code of the current matrix
  5373. * @returns the hash code
  5374. */
  5375. Matrix.prototype.getHashCode = function () {
  5376. var hash = this.m[0] || 0;
  5377. for (var i = 1; i < 16; i++) {
  5378. hash = (hash * 397) ^ (this.m[i] || 0);
  5379. }
  5380. return hash;
  5381. };
  5382. /**
  5383. * Decomposes the current Matrix into a translation, rotation and scaling components
  5384. * @param scale defines the scale vector3 given as a reference to update
  5385. * @param rotation defines the rotation quaternion given as a reference to update
  5386. * @param translation defines the translation vector3 given as a reference to update
  5387. * @returns true if operation was successful
  5388. */
  5389. Matrix.prototype.decompose = function (scale, rotation, translation) {
  5390. if (translation) {
  5391. translation.x = this.m[12];
  5392. translation.y = this.m[13];
  5393. translation.z = this.m[14];
  5394. }
  5395. scale = scale || MathTmp.Vector3[0];
  5396. scale.x = Math.sqrt(this.m[0] * this.m[0] + this.m[1] * this.m[1] + this.m[2] * this.m[2]);
  5397. scale.y = Math.sqrt(this.m[4] * this.m[4] + this.m[5] * this.m[5] + this.m[6] * this.m[6]);
  5398. scale.z = Math.sqrt(this.m[8] * this.m[8] + this.m[9] * this.m[9] + this.m[10] * this.m[10]);
  5399. if (this.determinant() <= 0) {
  5400. scale.y *= -1;
  5401. }
  5402. if (scale.x === 0 || scale.y === 0 || scale.z === 0) {
  5403. if (rotation) {
  5404. rotation.x = 0;
  5405. rotation.y = 0;
  5406. rotation.z = 0;
  5407. rotation.w = 1;
  5408. }
  5409. return false;
  5410. }
  5411. if (rotation) {
  5412. Matrix.FromValuesToRef(this.m[0] / scale.x, this.m[1] / scale.x, this.m[2] / scale.x, 0, this.m[4] / scale.y, this.m[5] / scale.y, this.m[6] / scale.y, 0, this.m[8] / scale.z, this.m[9] / scale.z, this.m[10] / scale.z, 0, 0, 0, 0, 1, MathTmp.Matrix[0]);
  5413. Quaternion.FromRotationMatrixToRef(MathTmp.Matrix[0], rotation);
  5414. }
  5415. return true;
  5416. };
  5417. /**
  5418. * Gets specific row of the matrix
  5419. * @param index defines the number of the row to get
  5420. * @returns the index-th row of the current matrix as a new Vector4
  5421. */
  5422. Matrix.prototype.getRow = function (index) {
  5423. if (index < 0 || index > 3) {
  5424. return null;
  5425. }
  5426. var i = index * 4;
  5427. return new Vector4(this.m[i + 0], this.m[i + 1], this.m[i + 2], this.m[i + 3]);
  5428. };
  5429. /**
  5430. * Sets the index-th row of the current matrix to the vector4 values
  5431. * @param index defines the number of the row to set
  5432. * @param row defines the target vector4
  5433. * @returns the updated current matrix
  5434. */
  5435. Matrix.prototype.setRow = function (index, row) {
  5436. if (index < 0 || index > 3) {
  5437. return this;
  5438. }
  5439. var i = index * 4;
  5440. this.m[i + 0] = row.x;
  5441. this.m[i + 1] = row.y;
  5442. this.m[i + 2] = row.z;
  5443. this.m[i + 3] = row.w;
  5444. this._markAsUpdated();
  5445. return this;
  5446. };
  5447. /**
  5448. * Compute the transpose of the matrix
  5449. * @returns the new transposed matrix
  5450. */
  5451. Matrix.prototype.transpose = function () {
  5452. return Matrix.Transpose(this);
  5453. };
  5454. /**
  5455. * Compute the transpose of the matrix and store it in a given matrix
  5456. * @param result defines the target matrix
  5457. * @returns the current matrix
  5458. */
  5459. Matrix.prototype.transposeToRef = function (result) {
  5460. Matrix.TransposeToRef(this, result);
  5461. return this;
  5462. };
  5463. /**
  5464. * Sets the index-th row of the current matrix with the given 4 x float values
  5465. * @param index defines the row index
  5466. * @param x defines the x component to set
  5467. * @param y defines the y component to set
  5468. * @param z defines the z component to set
  5469. * @param w defines the w component to set
  5470. * @returns the updated current matrix
  5471. */
  5472. Matrix.prototype.setRowFromFloats = function (index, x, y, z, w) {
  5473. if (index < 0 || index > 3) {
  5474. return this;
  5475. }
  5476. var i = index * 4;
  5477. this.m[i + 0] = x;
  5478. this.m[i + 1] = y;
  5479. this.m[i + 2] = z;
  5480. this.m[i + 3] = w;
  5481. this._markAsUpdated();
  5482. return this;
  5483. };
  5484. /**
  5485. * Compute a new matrix set with the current matrix values multiplied by scale (float)
  5486. * @param scale defines the scale factor
  5487. * @returns a new matrix
  5488. */
  5489. Matrix.prototype.scale = function (scale) {
  5490. var result = new Matrix();
  5491. this.scaleToRef(scale, result);
  5492. return result;
  5493. };
  5494. /**
  5495. * Scale the current matrix values by a factor to a given result matrix
  5496. * @param scale defines the scale factor
  5497. * @param result defines the matrix to store the result
  5498. * @returns the current matrix
  5499. */
  5500. Matrix.prototype.scaleToRef = function (scale, result) {
  5501. for (var index = 0; index < 16; index++) {
  5502. result.m[index] = this.m[index] * scale;
  5503. }
  5504. result._markAsUpdated();
  5505. return this;
  5506. };
  5507. /**
  5508. * Scale the current matrix values by a factor and add the result to a given matrix
  5509. * @param scale defines the scale factor
  5510. * @param result defines the Matrix to store the result
  5511. * @returns the current matrix
  5512. */
  5513. Matrix.prototype.scaleAndAddToRef = function (scale, result) {
  5514. for (var index = 0; index < 16; index++) {
  5515. result.m[index] += this.m[index] * scale;
  5516. }
  5517. result._markAsUpdated();
  5518. return this;
  5519. };
  5520. /**
  5521. * Writes to the given matrix a normal matrix, computed from this one (using values from identity matrix for fourth row and column).
  5522. * @param ref matrix to store the result
  5523. */
  5524. Matrix.prototype.toNormalMatrix = function (ref) {
  5525. this.invertToRef(ref);
  5526. ref.transpose();
  5527. var m = ref.m;
  5528. Matrix.FromValuesToRef(m[0], m[1], m[2], 0, m[4], m[5], m[6], 0, m[8], m[9], m[10], 0, 0, 0, 0, 1, ref);
  5529. };
  5530. /**
  5531. * Gets only rotation part of the current matrix
  5532. * @returns a new matrix sets to the extracted rotation matrix from the current one
  5533. */
  5534. Matrix.prototype.getRotationMatrix = function () {
  5535. var result = Matrix.Identity();
  5536. this.getRotationMatrixToRef(result);
  5537. return result;
  5538. };
  5539. /**
  5540. * Extracts the rotation matrix from the current one and sets it as the given "result"
  5541. * @param result defines the target matrix to store data to
  5542. * @returns the current matrix
  5543. */
  5544. Matrix.prototype.getRotationMatrixToRef = function (result) {
  5545. var m = this.m;
  5546. var sx = Math.sqrt(m[0] * m[0] + m[1] * m[1] + m[2] * m[2]);
  5547. var sy = Math.sqrt(m[4] * m[4] + m[5] * m[5] + m[6] * m[6]);
  5548. var sz = Math.sqrt(m[8] * m[8] + m[9] * m[9] + m[10] * m[10]);
  5549. if (this.determinant() <= 0) {
  5550. sy *= -1;
  5551. }
  5552. if (sx === 0 || sy === 0 || sz === 0) {
  5553. Matrix.IdentityToRef(result);
  5554. }
  5555. else {
  5556. Matrix.FromValuesToRef(m[0] / sx, m[1] / sx, m[2] / sx, 0, m[4] / sy, m[5] / sy, m[6] / sy, 0, m[8] / sz, m[9] / sz, m[10] / sz, 0, 0, 0, 0, 1, result);
  5557. }
  5558. return this;
  5559. };
  5560. // Statics
  5561. /**
  5562. * Creates a matrix from an array
  5563. * @param array defines the source array
  5564. * @param offset defines an offset in the source array
  5565. * @returns a new Matrix set from the starting index of the given array
  5566. */
  5567. Matrix.FromArray = function (array, offset) {
  5568. var result = new Matrix();
  5569. if (!offset) {
  5570. offset = 0;
  5571. }
  5572. Matrix.FromArrayToRef(array, offset, result);
  5573. return result;
  5574. };
  5575. /**
  5576. * Copy the content of an array into a given matrix
  5577. * @param array defines the source array
  5578. * @param offset defines an offset in the source array
  5579. * @param result defines the target matrix
  5580. */
  5581. Matrix.FromArrayToRef = function (array, offset, result) {
  5582. for (var index = 0; index < 16; index++) {
  5583. result.m[index] = array[index + offset];
  5584. }
  5585. result._markAsUpdated();
  5586. };
  5587. /**
  5588. * Stores an array into a matrix after having multiplied each component by a given factor
  5589. * @param array defines the source array
  5590. * @param offset defines the offset in the source array
  5591. * @param scale defines the scaling factor
  5592. * @param result defines the target matrix
  5593. */
  5594. Matrix.FromFloat32ArrayToRefScaled = function (array, offset, scale, result) {
  5595. for (var index = 0; index < 16; index++) {
  5596. result.m[index] = array[index + offset] * scale;
  5597. }
  5598. result._markAsUpdated();
  5599. };
  5600. /**
  5601. * Stores a list of values (16) inside a given matrix
  5602. * @param initialM11 defines 1st value of 1st row
  5603. * @param initialM12 defines 2nd value of 1st row
  5604. * @param initialM13 defines 3rd value of 1st row
  5605. * @param initialM14 defines 4th value of 1st row
  5606. * @param initialM21 defines 1st value of 2nd row
  5607. * @param initialM22 defines 2nd value of 2nd row
  5608. * @param initialM23 defines 3rd value of 2nd row
  5609. * @param initialM24 defines 4th value of 2nd row
  5610. * @param initialM31 defines 1st value of 3rd row
  5611. * @param initialM32 defines 2nd value of 3rd row
  5612. * @param initialM33 defines 3rd value of 3rd row
  5613. * @param initialM34 defines 4th value of 3rd row
  5614. * @param initialM41 defines 1st value of 4th row
  5615. * @param initialM42 defines 2nd value of 4th row
  5616. * @param initialM43 defines 3rd value of 4th row
  5617. * @param initialM44 defines 4th value of 4th row
  5618. * @param result defines the target matrix
  5619. */
  5620. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  5621. result.m[0] = initialM11;
  5622. result.m[1] = initialM12;
  5623. result.m[2] = initialM13;
  5624. result.m[3] = initialM14;
  5625. result.m[4] = initialM21;
  5626. result.m[5] = initialM22;
  5627. result.m[6] = initialM23;
  5628. result.m[7] = initialM24;
  5629. result.m[8] = initialM31;
  5630. result.m[9] = initialM32;
  5631. result.m[10] = initialM33;
  5632. result.m[11] = initialM34;
  5633. result.m[12] = initialM41;
  5634. result.m[13] = initialM42;
  5635. result.m[14] = initialM43;
  5636. result.m[15] = initialM44;
  5637. result._markAsUpdated();
  5638. };
  5639. Object.defineProperty(Matrix, "IdentityReadOnly", {
  5640. /**
  5641. * Gets an identity matrix that must not be updated
  5642. */
  5643. get: function () {
  5644. return Matrix._identityReadOnly;
  5645. },
  5646. enumerable: true,
  5647. configurable: true
  5648. });
  5649. /**
  5650. * Creates new matrix from a list of values (16)
  5651. * @param initialM11 defines 1st value of 1st row
  5652. * @param initialM12 defines 2nd value of 1st row
  5653. * @param initialM13 defines 3rd value of 1st row
  5654. * @param initialM14 defines 4th value of 1st row
  5655. * @param initialM21 defines 1st value of 2nd row
  5656. * @param initialM22 defines 2nd value of 2nd row
  5657. * @param initialM23 defines 3rd value of 2nd row
  5658. * @param initialM24 defines 4th value of 2nd row
  5659. * @param initialM31 defines 1st value of 3rd row
  5660. * @param initialM32 defines 2nd value of 3rd row
  5661. * @param initialM33 defines 3rd value of 3rd row
  5662. * @param initialM34 defines 4th value of 3rd row
  5663. * @param initialM41 defines 1st value of 4th row
  5664. * @param initialM42 defines 2nd value of 4th row
  5665. * @param initialM43 defines 3rd value of 4th row
  5666. * @param initialM44 defines 4th value of 4th row
  5667. * @returns the new matrix
  5668. */
  5669. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  5670. var result = new Matrix();
  5671. result.m[0] = initialM11;
  5672. result.m[1] = initialM12;
  5673. result.m[2] = initialM13;
  5674. result.m[3] = initialM14;
  5675. result.m[4] = initialM21;
  5676. result.m[5] = initialM22;
  5677. result.m[6] = initialM23;
  5678. result.m[7] = initialM24;
  5679. result.m[8] = initialM31;
  5680. result.m[9] = initialM32;
  5681. result.m[10] = initialM33;
  5682. result.m[11] = initialM34;
  5683. result.m[12] = initialM41;
  5684. result.m[13] = initialM42;
  5685. result.m[14] = initialM43;
  5686. result.m[15] = initialM44;
  5687. return result;
  5688. };
  5689. /**
  5690. * Creates a new matrix composed by merging scale (vector3), rotation (quaternion) and translation (vector3)
  5691. * @param scale defines the scale vector3
  5692. * @param rotation defines the rotation quaternion
  5693. * @param translation defines the translation vector3
  5694. * @returns a new matrix
  5695. */
  5696. Matrix.Compose = function (scale, rotation, translation) {
  5697. var result = Matrix.Identity();
  5698. Matrix.ComposeToRef(scale, rotation, translation, result);
  5699. return result;
  5700. };
  5701. /**
  5702. * Sets a matrix to a value composed by merging scale (vector3), rotation (quaternion) and translation (vector3)
  5703. * @param scale defines the scale vector3
  5704. * @param rotation defines the rotation quaternion
  5705. * @param translation defines the translation vector3
  5706. * @param result defines the target matrix
  5707. */
  5708. Matrix.ComposeToRef = function (scale, rotation, translation, result) {
  5709. Matrix.FromValuesToRef(scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1, MathTmp.Matrix[1]);
  5710. rotation.toRotationMatrix(MathTmp.Matrix[0]);
  5711. MathTmp.Matrix[1].multiplyToRef(MathTmp.Matrix[0], result);
  5712. result.setTranslation(translation);
  5713. };
  5714. /**
  5715. * Creates a new identity matrix
  5716. * @returns a new identity matrix
  5717. */
  5718. Matrix.Identity = function () {
  5719. return Matrix.FromValues(1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0);
  5720. };
  5721. /**
  5722. * Creates a new identity matrix and stores the result in a given matrix
  5723. * @param result defines the target matrix
  5724. */
  5725. Matrix.IdentityToRef = function (result) {
  5726. 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);
  5727. };
  5728. /**
  5729. * Creates a new zero matrix
  5730. * @returns a new zero matrix
  5731. */
  5732. Matrix.Zero = function () {
  5733. return Matrix.FromValues(0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0);
  5734. };
  5735. /**
  5736. * Creates a new rotation matrix for "angle" radians around the X axis
  5737. * @param angle defines the angle (in radians) to use
  5738. * @return the new matrix
  5739. */
  5740. Matrix.RotationX = function (angle) {
  5741. var result = new Matrix();
  5742. Matrix.RotationXToRef(angle, result);
  5743. return result;
  5744. };
  5745. /**
  5746. * Creates a new matrix as the invert of a given matrix
  5747. * @param source defines the source matrix
  5748. * @returns the new matrix
  5749. */
  5750. Matrix.Invert = function (source) {
  5751. var result = new Matrix();
  5752. source.invertToRef(result);
  5753. return result;
  5754. };
  5755. /**
  5756. * Creates a new rotation matrix for "angle" radians around the X axis and stores it in a given matrix
  5757. * @param angle defines the angle (in radians) to use
  5758. * @param result defines the target matrix
  5759. */
  5760. Matrix.RotationXToRef = function (angle, result) {
  5761. var s = Math.sin(angle);
  5762. var c = Math.cos(angle);
  5763. result.m[0] = 1.0;
  5764. result.m[15] = 1.0;
  5765. result.m[5] = c;
  5766. result.m[10] = c;
  5767. result.m[9] = -s;
  5768. result.m[6] = s;
  5769. result.m[1] = 0.0;
  5770. result.m[2] = 0.0;
  5771. result.m[3] = 0.0;
  5772. result.m[4] = 0.0;
  5773. result.m[7] = 0.0;
  5774. result.m[8] = 0.0;
  5775. result.m[11] = 0.0;
  5776. result.m[12] = 0.0;
  5777. result.m[13] = 0.0;
  5778. result.m[14] = 0.0;
  5779. result._markAsUpdated();
  5780. };
  5781. /**
  5782. * Creates a new rotation matrix for "angle" radians around the Y axis
  5783. * @param angle defines the angle (in radians) to use
  5784. * @return the new matrix
  5785. */
  5786. Matrix.RotationY = function (angle) {
  5787. var result = new Matrix();
  5788. Matrix.RotationYToRef(angle, result);
  5789. return result;
  5790. };
  5791. /**
  5792. * Creates a new rotation matrix for "angle" radians around the Y axis and stores it in a given matrix
  5793. * @param angle defines the angle (in radians) to use
  5794. * @param result defines the target matrix
  5795. */
  5796. Matrix.RotationYToRef = function (angle, result) {
  5797. var s = Math.sin(angle);
  5798. var c = Math.cos(angle);
  5799. result.m[5] = 1.0;
  5800. result.m[15] = 1.0;
  5801. result.m[0] = c;
  5802. result.m[2] = -s;
  5803. result.m[8] = s;
  5804. result.m[10] = c;
  5805. result.m[1] = 0.0;
  5806. result.m[3] = 0.0;
  5807. result.m[4] = 0.0;
  5808. result.m[6] = 0.0;
  5809. result.m[7] = 0.0;
  5810. result.m[9] = 0.0;
  5811. result.m[11] = 0.0;
  5812. result.m[12] = 0.0;
  5813. result.m[13] = 0.0;
  5814. result.m[14] = 0.0;
  5815. result._markAsUpdated();
  5816. };
  5817. /**
  5818. * Creates a new rotation matrix for "angle" radians around the Z axis
  5819. * @param angle defines the angle (in radians) to use
  5820. * @return the new matrix
  5821. */
  5822. Matrix.RotationZ = function (angle) {
  5823. var result = new Matrix();
  5824. Matrix.RotationZToRef(angle, result);
  5825. return result;
  5826. };
  5827. /**
  5828. * Creates a new rotation matrix for "angle" radians around the Z axis and stores it in a given matrix
  5829. * @param angle defines the angle (in radians) to use
  5830. * @param result defines the target matrix
  5831. */
  5832. Matrix.RotationZToRef = function (angle, result) {
  5833. var s = Math.sin(angle);
  5834. var c = Math.cos(angle);
  5835. result.m[10] = 1.0;
  5836. result.m[15] = 1.0;
  5837. result.m[0] = c;
  5838. result.m[1] = s;
  5839. result.m[4] = -s;
  5840. result.m[5] = c;
  5841. result.m[2] = 0.0;
  5842. result.m[3] = 0.0;
  5843. result.m[6] = 0.0;
  5844. result.m[7] = 0.0;
  5845. result.m[8] = 0.0;
  5846. result.m[9] = 0.0;
  5847. result.m[11] = 0.0;
  5848. result.m[12] = 0.0;
  5849. result.m[13] = 0.0;
  5850. result.m[14] = 0.0;
  5851. result._markAsUpdated();
  5852. };
  5853. /**
  5854. * Creates a new rotation matrix for "angle" radians around the given axis
  5855. * @param axis defines the axis to use
  5856. * @param angle defines the angle (in radians) to use
  5857. * @return the new matrix
  5858. */
  5859. Matrix.RotationAxis = function (axis, angle) {
  5860. var result = Matrix.Zero();
  5861. Matrix.RotationAxisToRef(axis, angle, result);
  5862. return result;
  5863. };
  5864. /**
  5865. * Creates a new rotation matrix for "angle" radians around the given axis and stores it in a given matrix
  5866. * @param axis defines the axis to use
  5867. * @param angle defines the angle (in radians) to use
  5868. * @param result defines the target matrix
  5869. */
  5870. Matrix.RotationAxisToRef = function (axis, angle, result) {
  5871. var s = Math.sin(-angle);
  5872. var c = Math.cos(-angle);
  5873. var c1 = 1 - c;
  5874. axis.normalize();
  5875. result.m[0] = (axis.x * axis.x) * c1 + c;
  5876. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  5877. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  5878. result.m[3] = 0.0;
  5879. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  5880. result.m[5] = (axis.y * axis.y) * c1 + c;
  5881. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  5882. result.m[7] = 0.0;
  5883. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  5884. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  5885. result.m[10] = (axis.z * axis.z) * c1 + c;
  5886. result.m[11] = 0.0;
  5887. result.m[15] = 1.0;
  5888. result._markAsUpdated();
  5889. };
  5890. /**
  5891. * Creates a rotation matrix
  5892. * @param yaw defines the yaw angle in radians (Y axis)
  5893. * @param pitch defines the pitch angle in radians (X axis)
  5894. * @param roll defines the roll angle in radians (X axis)
  5895. * @returns the new rotation matrix
  5896. */
  5897. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  5898. var result = new Matrix();
  5899. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  5900. return result;
  5901. };
  5902. /**
  5903. * Creates a rotation matrix and stores it in a given matrix
  5904. * @param yaw defines the yaw angle in radians (Y axis)
  5905. * @param pitch defines the pitch angle in radians (X axis)
  5906. * @param roll defines the roll angle in radians (X axis)
  5907. * @param result defines the target matrix
  5908. */
  5909. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  5910. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  5911. this._tempQuaternion.toRotationMatrix(result);
  5912. };
  5913. /**
  5914. * Creates a scaling matrix
  5915. * @param x defines the scale factor on X axis
  5916. * @param y defines the scale factor on Y axis
  5917. * @param z defines the scale factor on Z axis
  5918. * @returns the new matrix
  5919. */
  5920. Matrix.Scaling = function (x, y, z) {
  5921. var result = Matrix.Zero();
  5922. Matrix.ScalingToRef(x, y, z, result);
  5923. return result;
  5924. };
  5925. /**
  5926. * Creates a scaling matrix and stores it in a given matrix
  5927. * @param x defines the scale factor on X axis
  5928. * @param y defines the scale factor on Y axis
  5929. * @param z defines the scale factor on Z axis
  5930. * @param result defines the target matrix
  5931. */
  5932. Matrix.ScalingToRef = function (x, y, z, result) {
  5933. result.m[0] = x;
  5934. result.m[1] = 0.0;
  5935. result.m[2] = 0.0;
  5936. result.m[3] = 0.0;
  5937. result.m[4] = 0.0;
  5938. result.m[5] = y;
  5939. result.m[6] = 0.0;
  5940. result.m[7] = 0.0;
  5941. result.m[8] = 0.0;
  5942. result.m[9] = 0.0;
  5943. result.m[10] = z;
  5944. result.m[11] = 0.0;
  5945. result.m[12] = 0.0;
  5946. result.m[13] = 0.0;
  5947. result.m[14] = 0.0;
  5948. result.m[15] = 1.0;
  5949. result._markAsUpdated();
  5950. };
  5951. /**
  5952. * Creates a translation matrix
  5953. * @param x defines the translation on X axis
  5954. * @param y defines the translation on Y axis
  5955. * @param z defines the translationon Z axis
  5956. * @returns the new matrix
  5957. */
  5958. Matrix.Translation = function (x, y, z) {
  5959. var result = Matrix.Identity();
  5960. Matrix.TranslationToRef(x, y, z, result);
  5961. return result;
  5962. };
  5963. /**
  5964. * Creates a translation matrix and stores it in a given matrix
  5965. * @param x defines the translation on X axis
  5966. * @param y defines the translation on Y axis
  5967. * @param z defines the translationon Z axis
  5968. * @param result defines the target matrix
  5969. */
  5970. Matrix.TranslationToRef = function (x, y, z, result) {
  5971. 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);
  5972. };
  5973. /**
  5974. * Returns a new Matrix whose values are the interpolated values for "gradient" (float) between the ones of the matrices "startValue" and "endValue".
  5975. * @param startValue defines the start value
  5976. * @param endValue defines the end value
  5977. * @param gradient defines the gradient factor
  5978. * @returns the new matrix
  5979. */
  5980. Matrix.Lerp = function (startValue, endValue, gradient) {
  5981. var result = Matrix.Zero();
  5982. Matrix.LerpToRef(startValue, endValue, gradient, result);
  5983. return result;
  5984. };
  5985. /**
  5986. * Set the given matrix "result" as the interpolated values for "gradient" (float) between the ones of the matrices "startValue" and "endValue".
  5987. * @param startValue defines the start value
  5988. * @param endValue defines the end value
  5989. * @param gradient defines the gradient factor
  5990. * @param result defines the Matrix object where to store data
  5991. */
  5992. Matrix.LerpToRef = function (startValue, endValue, gradient, result) {
  5993. for (var index = 0; index < 16; index++) {
  5994. result.m[index] = startValue.m[index] * (1.0 - gradient) + endValue.m[index] * gradient;
  5995. }
  5996. result._markAsUpdated();
  5997. };
  5998. /**
  5999. * Builds a new matrix whose values are computed by:
  6000. * * decomposing the the "startValue" and "endValue" matrices into their respective scale, rotation and translation matrices
  6001. * * interpolating for "gradient" (float) the values between each of these decomposed matrices between the start and the end
  6002. * * recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices
  6003. * @param startValue defines the first matrix
  6004. * @param endValue defines the second matrix
  6005. * @param gradient defines the gradient between the two matrices
  6006. * @returns the new matrix
  6007. */
  6008. Matrix.DecomposeLerp = function (startValue, endValue, gradient) {
  6009. var result = Matrix.Zero();
  6010. Matrix.DecomposeLerpToRef(startValue, endValue, gradient, result);
  6011. return result;
  6012. };
  6013. /**
  6014. * Update a matrix to values which are computed by:
  6015. * * decomposing the the "startValue" and "endValue" matrices into their respective scale, rotation and translation matrices
  6016. * * interpolating for "gradient" (float) the values between each of these decomposed matrices between the start and the end
  6017. * * recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices
  6018. * @param startValue defines the first matrix
  6019. * @param endValue defines the second matrix
  6020. * @param gradient defines the gradient between the two matrices
  6021. * @param result defines the target matrix
  6022. */
  6023. Matrix.DecomposeLerpToRef = function (startValue, endValue, gradient, result) {
  6024. var startScale = MathTmp.Vector3[0];
  6025. var startRotation = MathTmp.Quaternion[0];
  6026. var startTranslation = MathTmp.Vector3[1];
  6027. startValue.decompose(startScale, startRotation, startTranslation);
  6028. var endScale = MathTmp.Vector3[2];
  6029. var endRotation = MathTmp.Quaternion[1];
  6030. var endTranslation = MathTmp.Vector3[3];
  6031. endValue.decompose(endScale, endRotation, endTranslation);
  6032. var resultScale = MathTmp.Vector3[4];
  6033. Vector3.LerpToRef(startScale, endScale, gradient, resultScale);
  6034. var resultRotation = MathTmp.Quaternion[2];
  6035. Quaternion.SlerpToRef(startRotation, endRotation, gradient, resultRotation);
  6036. var resultTranslation = MathTmp.Vector3[5];
  6037. Vector3.LerpToRef(startTranslation, endTranslation, gradient, resultTranslation);
  6038. Matrix.ComposeToRef(resultScale, resultRotation, resultTranslation, result);
  6039. };
  6040. /**
  6041. * 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"
  6042. * This function works in left handed mode
  6043. * @param eye defines the final position of the entity
  6044. * @param target defines where the entity should look at
  6045. * @param up defines the up vector for the entity
  6046. * @returns the new matrix
  6047. */
  6048. Matrix.LookAtLH = function (eye, target, up) {
  6049. var result = Matrix.Zero();
  6050. Matrix.LookAtLHToRef(eye, target, up, result);
  6051. return result;
  6052. };
  6053. /**
  6054. * 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".
  6055. * This function works in left handed mode
  6056. * @param eye defines the final position of the entity
  6057. * @param target defines where the entity should look at
  6058. * @param up defines the up vector for the entity
  6059. * @param result defines the target matrix
  6060. */
  6061. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  6062. // Z axis
  6063. target.subtractToRef(eye, this._zAxis);
  6064. this._zAxis.normalize();
  6065. // X axis
  6066. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  6067. if (this._xAxis.lengthSquared() === 0) {
  6068. this._xAxis.x = 1.0;
  6069. }
  6070. else {
  6071. this._xAxis.normalize();
  6072. }
  6073. // Y axis
  6074. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  6075. this._yAxis.normalize();
  6076. // Eye angles
  6077. var ex = -Vector3.Dot(this._xAxis, eye);
  6078. var ey = -Vector3.Dot(this._yAxis, eye);
  6079. var ez = -Vector3.Dot(this._zAxis, eye);
  6080. return Matrix.FromValuesToRef(this._xAxis.x, this._yAxis.x, this._zAxis.x, 0, this._xAxis.y, this._yAxis.y, this._zAxis.y, 0, this._xAxis.z, this._yAxis.z, this._zAxis.z, 0, ex, ey, ez, 1, result);
  6081. };
  6082. /**
  6083. * 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"
  6084. * This function works in right handed mode
  6085. * @param eye defines the final position of the entity
  6086. * @param target defines where the entity should look at
  6087. * @param up defines the up vector for the entity
  6088. * @returns the new matrix
  6089. */
  6090. Matrix.LookAtRH = function (eye, target, up) {
  6091. var result = Matrix.Zero();
  6092. Matrix.LookAtRHToRef(eye, target, up, result);
  6093. return result;
  6094. };
  6095. /**
  6096. * 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".
  6097. * This function works in right handed mode
  6098. * @param eye defines the final position of the entity
  6099. * @param target defines where the entity should look at
  6100. * @param up defines the up vector for the entity
  6101. * @param result defines the target matrix
  6102. */
  6103. Matrix.LookAtRHToRef = function (eye, target, up, result) {
  6104. // Z axis
  6105. eye.subtractToRef(target, this._zAxis);
  6106. this._zAxis.normalize();
  6107. // X axis
  6108. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  6109. if (this._xAxis.lengthSquared() === 0) {
  6110. this._xAxis.x = 1.0;
  6111. }
  6112. else {
  6113. this._xAxis.normalize();
  6114. }
  6115. // Y axis
  6116. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  6117. this._yAxis.normalize();
  6118. // Eye angles
  6119. var ex = -Vector3.Dot(this._xAxis, eye);
  6120. var ey = -Vector3.Dot(this._yAxis, eye);
  6121. var ez = -Vector3.Dot(this._zAxis, eye);
  6122. return Matrix.FromValuesToRef(this._xAxis.x, this._yAxis.x, this._zAxis.x, 0, this._xAxis.y, this._yAxis.y, this._zAxis.y, 0, this._xAxis.z, this._yAxis.z, this._zAxis.z, 0, ex, ey, ez, 1, result);
  6123. };
  6124. /**
  6125. * Create a left-handed orthographic projection matrix
  6126. * @param width defines the viewport width
  6127. * @param height defines the viewport height
  6128. * @param znear defines the near clip plane
  6129. * @param zfar defines the far clip plane
  6130. * @returns a new matrix as a left-handed orthographic projection matrix
  6131. */
  6132. Matrix.OrthoLH = function (width, height, znear, zfar) {
  6133. var matrix = Matrix.Zero();
  6134. Matrix.OrthoLHToRef(width, height, znear, zfar, matrix);
  6135. return matrix;
  6136. };
  6137. /**
  6138. * Store a left-handed orthographic projection to a given matrix
  6139. * @param width defines the viewport width
  6140. * @param height defines the viewport height
  6141. * @param znear defines the near clip plane
  6142. * @param zfar defines the far clip plane
  6143. * @param result defines the target matrix
  6144. */
  6145. Matrix.OrthoLHToRef = function (width, height, znear, zfar, result) {
  6146. var n = znear;
  6147. var f = zfar;
  6148. var a = 2.0 / width;
  6149. var b = 2.0 / height;
  6150. var c = 2.0 / (f - n);
  6151. var d = -(f + n) / (f - n);
  6152. 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);
  6153. };
  6154. /**
  6155. * Create a left-handed orthographic projection matrix
  6156. * @param left defines the viewport left coordinate
  6157. * @param right defines the viewport right coordinate
  6158. * @param bottom defines the viewport bottom coordinate
  6159. * @param top defines the viewport top coordinate
  6160. * @param znear defines the near clip plane
  6161. * @param zfar defines the far clip plane
  6162. * @returns a new matrix as a left-handed orthographic projection matrix
  6163. */
  6164. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  6165. var matrix = Matrix.Zero();
  6166. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  6167. return matrix;
  6168. };
  6169. /**
  6170. * Stores a left-handed orthographic projection into a given matrix
  6171. * @param left defines the viewport left coordinate
  6172. * @param right defines the viewport right coordinate
  6173. * @param bottom defines the viewport bottom coordinate
  6174. * @param top defines the viewport top coordinate
  6175. * @param znear defines the near clip plane
  6176. * @param zfar defines the far clip plane
  6177. * @param result defines the target matrix
  6178. */
  6179. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  6180. var n = znear;
  6181. var f = zfar;
  6182. var a = 2.0 / (right - left);
  6183. var b = 2.0 / (top - bottom);
  6184. var c = 2.0 / (f - n);
  6185. var d = -(f + n) / (f - n);
  6186. var i0 = (left + right) / (left - right);
  6187. var i1 = (top + bottom) / (bottom - top);
  6188. 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);
  6189. };
  6190. /**
  6191. * Creates a right-handed orthographic projection matrix
  6192. * @param left defines the viewport left coordinate
  6193. * @param right defines the viewport right coordinate
  6194. * @param bottom defines the viewport bottom coordinate
  6195. * @param top defines the viewport top coordinate
  6196. * @param znear defines the near clip plane
  6197. * @param zfar defines the far clip plane
  6198. * @returns a new matrix as a right-handed orthographic projection matrix
  6199. */
  6200. Matrix.OrthoOffCenterRH = function (left, right, bottom, top, znear, zfar) {
  6201. var matrix = Matrix.Zero();
  6202. Matrix.OrthoOffCenterRHToRef(left, right, bottom, top, znear, zfar, matrix);
  6203. return matrix;
  6204. };
  6205. /**
  6206. * Stores a right-handed orthographic projection into a given matrix
  6207. * @param left defines the viewport left coordinate
  6208. * @param right defines the viewport right coordinate
  6209. * @param bottom defines the viewport bottom coordinate
  6210. * @param top defines the viewport top coordinate
  6211. * @param znear defines the near clip plane
  6212. * @param zfar defines the far clip plane
  6213. * @param result defines the target matrix
  6214. */
  6215. Matrix.OrthoOffCenterRHToRef = function (left, right, bottom, top, znear, zfar, result) {
  6216. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, result);
  6217. result.m[10] *= -1.0;
  6218. };
  6219. /**
  6220. * Creates a left-handed perspective projection matrix
  6221. * @param width defines the viewport width
  6222. * @param height defines the viewport height
  6223. * @param znear defines the near clip plane
  6224. * @param zfar defines the far clip plane
  6225. * @returns a new matrix as a left-handed perspective projection matrix
  6226. */
  6227. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  6228. var matrix = Matrix.Zero();
  6229. var n = znear;
  6230. var f = zfar;
  6231. var a = 2.0 * n / width;
  6232. var b = 2.0 * n / height;
  6233. var c = (f + n) / (f - n);
  6234. var d = -2.0 * f * n / (f - n);
  6235. 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);
  6236. return matrix;
  6237. };
  6238. /**
  6239. * Creates a left-handed perspective projection matrix
  6240. * @param fov defines the horizontal field of view
  6241. * @param aspect defines the aspect ratio
  6242. * @param znear defines the near clip plane
  6243. * @param zfar defines the far clip plane
  6244. * @returns a new matrix as a left-handed perspective projection matrix
  6245. */
  6246. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  6247. var matrix = Matrix.Zero();
  6248. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  6249. return matrix;
  6250. };
  6251. /**
  6252. * Stores a left-handed perspective projection into a given matrix
  6253. * @param fov defines the horizontal field of view
  6254. * @param aspect defines the aspect ratio
  6255. * @param znear defines the near clip plane
  6256. * @param zfar defines the far clip plane
  6257. * @param result defines the target matrix
  6258. * @param isVerticalFovFixed defines it the fov is vertically fixed (default) or horizontally
  6259. */
  6260. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  6261. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  6262. var n = znear;
  6263. var f = zfar;
  6264. var t = 1.0 / (Math.tan(fov * 0.5));
  6265. var a = isVerticalFovFixed ? (t / aspect) : t;
  6266. var b = isVerticalFovFixed ? t : (t * aspect);
  6267. var c = (f + n) / (f - n);
  6268. var d = -2.0 * f * n / (f - n);
  6269. 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);
  6270. };
  6271. /**
  6272. * Creates a right-handed perspective projection matrix
  6273. * @param fov defines the horizontal field of view
  6274. * @param aspect defines the aspect ratio
  6275. * @param znear defines the near clip plane
  6276. * @param zfar defines the far clip plane
  6277. * @returns a new matrix as a right-handed perspective projection matrix
  6278. */
  6279. Matrix.PerspectiveFovRH = function (fov, aspect, znear, zfar) {
  6280. var matrix = Matrix.Zero();
  6281. Matrix.PerspectiveFovRHToRef(fov, aspect, znear, zfar, matrix);
  6282. return matrix;
  6283. };
  6284. /**
  6285. * Stores a right-handed perspective projection into a given matrix
  6286. * @param fov defines the horizontal field of view
  6287. * @param aspect defines the aspect ratio
  6288. * @param znear defines the near clip plane
  6289. * @param zfar defines the far clip plane
  6290. * @param result defines the target matrix
  6291. * @param isVerticalFovFixed defines it the fov is vertically fixed (default) or horizontally
  6292. */
  6293. Matrix.PerspectiveFovRHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  6294. //alternatively this could be expressed as:
  6295. // m = PerspectiveFovLHToRef
  6296. // m[10] *= -1.0;
  6297. // m[11] *= -1.0;
  6298. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  6299. var n = znear;
  6300. var f = zfar;
  6301. var t = 1.0 / (Math.tan(fov * 0.5));
  6302. var a = isVerticalFovFixed ? (t / aspect) : t;
  6303. var b = isVerticalFovFixed ? t : (t * aspect);
  6304. var c = -(f + n) / (f - n);
  6305. var d = -2 * f * n / (f - n);
  6306. 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);
  6307. };
  6308. /**
  6309. * Stores a perspective projection for WebVR info a given matrix
  6310. * @param fov defines the field of view
  6311. * @param znear defines the near clip plane
  6312. * @param zfar defines the far clip plane
  6313. * @param result defines the target matrix
  6314. * @param rightHanded defines if the matrix must be in right-handed mode (false by default)
  6315. */
  6316. Matrix.PerspectiveFovWebVRToRef = function (fov, znear, zfar, result, rightHanded) {
  6317. if (rightHanded === void 0) { rightHanded = false; }
  6318. var rightHandedFactor = rightHanded ? -1 : 1;
  6319. var upTan = Math.tan(fov.upDegrees * Math.PI / 180.0);
  6320. var downTan = Math.tan(fov.downDegrees * Math.PI / 180.0);
  6321. var leftTan = Math.tan(fov.leftDegrees * Math.PI / 180.0);
  6322. var rightTan = Math.tan(fov.rightDegrees * Math.PI / 180.0);
  6323. var xScale = 2.0 / (leftTan + rightTan);
  6324. var yScale = 2.0 / (upTan + downTan);
  6325. result.m[0] = xScale;
  6326. result.m[1] = result.m[2] = result.m[3] = result.m[4] = 0.0;
  6327. result.m[5] = yScale;
  6328. result.m[6] = result.m[7] = 0.0;
  6329. result.m[8] = ((leftTan - rightTan) * xScale * 0.5);
  6330. result.m[9] = -((upTan - downTan) * yScale * 0.5);
  6331. result.m[10] = -zfar / (znear - zfar);
  6332. result.m[11] = 1.0 * rightHandedFactor;
  6333. result.m[12] = result.m[13] = result.m[15] = 0.0;
  6334. result.m[14] = -(2.0 * zfar * znear) / (zfar - znear);
  6335. result._markAsUpdated();
  6336. };
  6337. /**
  6338. * Computes a complete transformation matrix
  6339. * @param viewport defines the viewport to use
  6340. * @param world defines the world matrix
  6341. * @param view defines the view matrix
  6342. * @param projection defines the projection matrix
  6343. * @param zmin defines the near clip plane
  6344. * @param zmax defines the far clip plane
  6345. * @returns the transformation matrix
  6346. */
  6347. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  6348. var cw = viewport.width;
  6349. var ch = viewport.height;
  6350. var cx = viewport.x;
  6351. var cy = viewport.y;
  6352. 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);
  6353. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  6354. };
  6355. /**
  6356. * Extracts a 2x2 matrix from a given matrix and store the result in a Float32Array
  6357. * @param matrix defines the matrix to use
  6358. * @returns a new Float32Array array with 4 elements : the 2x2 matrix extracted from the given matrix
  6359. */
  6360. Matrix.GetAsMatrix2x2 = function (matrix) {
  6361. return new Float32Array([
  6362. matrix.m[0], matrix.m[1],
  6363. matrix.m[4], matrix.m[5]
  6364. ]);
  6365. };
  6366. /**
  6367. * Extracts a 3x3 matrix from a given matrix and store the result in a Float32Array
  6368. * @param matrix defines the matrix to use
  6369. * @returns a new Float32Array array with 9 elements : the 3x3 matrix extracted from the given matrix
  6370. */
  6371. Matrix.GetAsMatrix3x3 = function (matrix) {
  6372. return new Float32Array([
  6373. matrix.m[0], matrix.m[1], matrix.m[2],
  6374. matrix.m[4], matrix.m[5], matrix.m[6],
  6375. matrix.m[8], matrix.m[9], matrix.m[10]
  6376. ]);
  6377. };
  6378. /**
  6379. * Compute the transpose of a given matrix
  6380. * @param matrix defines the matrix to transpose
  6381. * @returns the new matrix
  6382. */
  6383. Matrix.Transpose = function (matrix) {
  6384. var result = new Matrix();
  6385. Matrix.TransposeToRef(matrix, result);
  6386. return result;
  6387. };
  6388. /**
  6389. * Compute the transpose of a matrix and store it in a target matrix
  6390. * @param matrix defines the matrix to transpose
  6391. * @param result defines the target matrix
  6392. */
  6393. Matrix.TransposeToRef = function (matrix, result) {
  6394. result.m[0] = matrix.m[0];
  6395. result.m[1] = matrix.m[4];
  6396. result.m[2] = matrix.m[8];
  6397. result.m[3] = matrix.m[12];
  6398. result.m[4] = matrix.m[1];
  6399. result.m[5] = matrix.m[5];
  6400. result.m[6] = matrix.m[9];
  6401. result.m[7] = matrix.m[13];
  6402. result.m[8] = matrix.m[2];
  6403. result.m[9] = matrix.m[6];
  6404. result.m[10] = matrix.m[10];
  6405. result.m[11] = matrix.m[14];
  6406. result.m[12] = matrix.m[3];
  6407. result.m[13] = matrix.m[7];
  6408. result.m[14] = matrix.m[11];
  6409. result.m[15] = matrix.m[15];
  6410. };
  6411. /**
  6412. * Computes a reflection matrix from a plane
  6413. * @param plane defines the reflection plane
  6414. * @returns a new matrix
  6415. */
  6416. Matrix.Reflection = function (plane) {
  6417. var matrix = new Matrix();
  6418. Matrix.ReflectionToRef(plane, matrix);
  6419. return matrix;
  6420. };
  6421. /**
  6422. * Computes a reflection matrix from a plane
  6423. * @param plane defines the reflection plane
  6424. * @param result defines the target matrix
  6425. */
  6426. Matrix.ReflectionToRef = function (plane, result) {
  6427. plane.normalize();
  6428. var x = plane.normal.x;
  6429. var y = plane.normal.y;
  6430. var z = plane.normal.z;
  6431. var temp = -2 * x;
  6432. var temp2 = -2 * y;
  6433. var temp3 = -2 * z;
  6434. result.m[0] = (temp * x) + 1;
  6435. result.m[1] = temp2 * x;
  6436. result.m[2] = temp3 * x;
  6437. result.m[3] = 0.0;
  6438. result.m[4] = temp * y;
  6439. result.m[5] = (temp2 * y) + 1;
  6440. result.m[6] = temp3 * y;
  6441. result.m[7] = 0.0;
  6442. result.m[8] = temp * z;
  6443. result.m[9] = temp2 * z;
  6444. result.m[10] = (temp3 * z) + 1;
  6445. result.m[11] = 0.0;
  6446. result.m[12] = temp * plane.d;
  6447. result.m[13] = temp2 * plane.d;
  6448. result.m[14] = temp3 * plane.d;
  6449. result.m[15] = 1.0;
  6450. result._markAsUpdated();
  6451. };
  6452. /**
  6453. * Sets the given matrix as a rotation matrix composed from the 3 left handed axes
  6454. * @param xaxis defines the value of the 1st axis
  6455. * @param yaxis defines the value of the 2nd axis
  6456. * @param zaxis defines the value of the 3rd axis
  6457. * @param result defines the target matrix
  6458. */
  6459. Matrix.FromXYZAxesToRef = function (xaxis, yaxis, zaxis, result) {
  6460. result.m[0] = xaxis.x;
  6461. result.m[1] = xaxis.y;
  6462. result.m[2] = xaxis.z;
  6463. result.m[3] = 0.0;
  6464. result.m[4] = yaxis.x;
  6465. result.m[5] = yaxis.y;
  6466. result.m[6] = yaxis.z;
  6467. result.m[7] = 0.0;
  6468. result.m[8] = zaxis.x;
  6469. result.m[9] = zaxis.y;
  6470. result.m[10] = zaxis.z;
  6471. result.m[11] = 0.0;
  6472. result.m[12] = 0.0;
  6473. result.m[13] = 0.0;
  6474. result.m[14] = 0.0;
  6475. result.m[15] = 1.0;
  6476. result._markAsUpdated();
  6477. };
  6478. /**
  6479. * Creates a rotation matrix from a quaternion and stores it in a target matrix
  6480. * @param quat defines the quaternion to use
  6481. * @param result defines the target matrix
  6482. */
  6483. Matrix.FromQuaternionToRef = function (quat, result) {
  6484. var xx = quat.x * quat.x;
  6485. var yy = quat.y * quat.y;
  6486. var zz = quat.z * quat.z;
  6487. var xy = quat.x * quat.y;
  6488. var zw = quat.z * quat.w;
  6489. var zx = quat.z * quat.x;
  6490. var yw = quat.y * quat.w;
  6491. var yz = quat.y * quat.z;
  6492. var xw = quat.x * quat.w;
  6493. result.m[0] = 1.0 - (2.0 * (yy + zz));
  6494. result.m[1] = 2.0 * (xy + zw);
  6495. result.m[2] = 2.0 * (zx - yw);
  6496. result.m[3] = 0.0;
  6497. result.m[4] = 2.0 * (xy - zw);
  6498. result.m[5] = 1.0 - (2.0 * (zz + xx));
  6499. result.m[6] = 2.0 * (yz + xw);
  6500. result.m[7] = 0.0;
  6501. result.m[8] = 2.0 * (zx + yw);
  6502. result.m[9] = 2.0 * (yz - xw);
  6503. result.m[10] = 1.0 - (2.0 * (yy + xx));
  6504. result.m[11] = 0.0;
  6505. result.m[12] = 0.0;
  6506. result.m[13] = 0.0;
  6507. result.m[14] = 0.0;
  6508. result.m[15] = 1.0;
  6509. result._markAsUpdated();
  6510. };
  6511. Matrix._tempQuaternion = new Quaternion();
  6512. Matrix._xAxis = Vector3.Zero();
  6513. Matrix._yAxis = Vector3.Zero();
  6514. Matrix._zAxis = Vector3.Zero();
  6515. Matrix._updateFlagSeed = 0;
  6516. Matrix._identityReadOnly = Matrix.Identity();
  6517. return Matrix;
  6518. }());
  6519. BABYLON.Matrix = Matrix;
  6520. var Plane = /** @class */ (function () {
  6521. /**
  6522. * Creates a Plane object according to the given floats a, b, c, d and the plane equation : ax + by + cz + d = 0
  6523. */
  6524. function Plane(a, b, c, d) {
  6525. this.normal = new Vector3(a, b, c);
  6526. this.d = d;
  6527. }
  6528. /**
  6529. * Returns the plane coordinates as a new array of 4 elements [a, b, c, d].
  6530. */
  6531. Plane.prototype.asArray = function () {
  6532. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  6533. };
  6534. // Methods
  6535. /**
  6536. * Returns a new plane copied from the current Plane.
  6537. */
  6538. Plane.prototype.clone = function () {
  6539. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  6540. };
  6541. /**
  6542. * Returns the string "Plane".
  6543. */
  6544. Plane.prototype.getClassName = function () {
  6545. return "Plane";
  6546. };
  6547. /**
  6548. * Returns the Plane hash code.
  6549. */
  6550. Plane.prototype.getHashCode = function () {
  6551. var hash = this.normal.getHashCode();
  6552. hash = (hash * 397) ^ (this.d || 0);
  6553. return hash;
  6554. };
  6555. /**
  6556. * Normalize the current Plane in place.
  6557. * Returns the updated Plane.
  6558. */
  6559. Plane.prototype.normalize = function () {
  6560. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  6561. var magnitude = 0.0;
  6562. if (norm !== 0) {
  6563. magnitude = 1.0 / norm;
  6564. }
  6565. this.normal.x *= magnitude;
  6566. this.normal.y *= magnitude;
  6567. this.normal.z *= magnitude;
  6568. this.d *= magnitude;
  6569. return this;
  6570. };
  6571. /**
  6572. * Returns a new Plane as the result of the transformation of the current Plane by the given matrix.
  6573. */
  6574. Plane.prototype.transform = function (transformation) {
  6575. var transposedMatrix = Matrix.Transpose(transformation);
  6576. var x = this.normal.x;
  6577. var y = this.normal.y;
  6578. var z = this.normal.z;
  6579. var d = this.d;
  6580. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  6581. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  6582. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  6583. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  6584. return new Plane(normalX, normalY, normalZ, finalD);
  6585. };
  6586. /**
  6587. * Returns the dot product (float) of the point coordinates and the plane normal.
  6588. */
  6589. Plane.prototype.dotCoordinate = function (point) {
  6590. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  6591. };
  6592. /**
  6593. * Updates the current Plane from the plane defined by the three given points.
  6594. * Returns the updated Plane.
  6595. */
  6596. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  6597. var x1 = point2.x - point1.x;
  6598. var y1 = point2.y - point1.y;
  6599. var z1 = point2.z - point1.z;
  6600. var x2 = point3.x - point1.x;
  6601. var y2 = point3.y - point1.y;
  6602. var z2 = point3.z - point1.z;
  6603. var yz = (y1 * z2) - (z1 * y2);
  6604. var xz = (z1 * x2) - (x1 * z2);
  6605. var xy = (x1 * y2) - (y1 * x2);
  6606. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  6607. var invPyth;
  6608. if (pyth !== 0) {
  6609. invPyth = 1.0 / pyth;
  6610. }
  6611. else {
  6612. invPyth = 0.0;
  6613. }
  6614. this.normal.x = yz * invPyth;
  6615. this.normal.y = xz * invPyth;
  6616. this.normal.z = xy * invPyth;
  6617. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  6618. return this;
  6619. };
  6620. /**
  6621. * Boolean : True is the vector "direction" is the same side than the plane normal.
  6622. */
  6623. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  6624. var dot = Vector3.Dot(this.normal, direction);
  6625. return (dot <= epsilon);
  6626. };
  6627. /**
  6628. * Returns the signed distance (float) from the given point to the Plane.
  6629. */
  6630. Plane.prototype.signedDistanceTo = function (point) {
  6631. return Vector3.Dot(point, this.normal) + this.d;
  6632. };
  6633. // Statics
  6634. /**
  6635. * Returns a new Plane from the given array.
  6636. */
  6637. Plane.FromArray = function (array) {
  6638. return new Plane(array[0], array[1], array[2], array[3]);
  6639. };
  6640. /**
  6641. * Returns a new Plane defined by the three given points.
  6642. */
  6643. Plane.FromPoints = function (point1, point2, point3) {
  6644. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  6645. result.copyFromPoints(point1, point2, point3);
  6646. return result;
  6647. };
  6648. /**
  6649. * Returns a new Plane the normal vector to this plane at the given origin point.
  6650. * Note : the vector "normal" is updated because normalized.
  6651. */
  6652. Plane.FromPositionAndNormal = function (origin, normal) {
  6653. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  6654. normal.normalize();
  6655. result.normal = normal;
  6656. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  6657. return result;
  6658. };
  6659. /**
  6660. * Returns the signed distance between the plane defined by the normal vector at the "origin"" point and the given other point.
  6661. */
  6662. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  6663. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  6664. return Vector3.Dot(point, normal) + d;
  6665. };
  6666. return Plane;
  6667. }());
  6668. BABYLON.Plane = Plane;
  6669. var Viewport = /** @class */ (function () {
  6670. /**
  6671. * Creates a Viewport object located at (x, y) and sized (width, height).
  6672. */
  6673. function Viewport(x, y, width, height) {
  6674. this.x = x;
  6675. this.y = y;
  6676. this.width = width;
  6677. this.height = height;
  6678. }
  6679. Viewport.prototype.toGlobal = function (renderWidthOrEngine, renderHeight) {
  6680. if (renderWidthOrEngine.getRenderWidth) {
  6681. var engine = renderWidthOrEngine;
  6682. return this.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  6683. }
  6684. var renderWidth = renderWidthOrEngine;
  6685. return new Viewport(this.x * renderWidth, this.y * renderHeight, this.width * renderWidth, this.height * renderHeight);
  6686. };
  6687. /**
  6688. * Returns a new Viewport copied from the current one.
  6689. */
  6690. Viewport.prototype.clone = function () {
  6691. return new Viewport(this.x, this.y, this.width, this.height);
  6692. };
  6693. return Viewport;
  6694. }());
  6695. BABYLON.Viewport = Viewport;
  6696. var Frustum = /** @class */ (function () {
  6697. function Frustum() {
  6698. }
  6699. /**
  6700. * Returns a new array of 6 Frustum planes computed by the given transformation matrix.
  6701. */
  6702. Frustum.GetPlanes = function (transform) {
  6703. var frustumPlanes = [];
  6704. for (var index = 0; index < 6; index++) {
  6705. frustumPlanes.push(new Plane(0.0, 0.0, 0.0, 0.0));
  6706. }
  6707. Frustum.GetPlanesToRef(transform, frustumPlanes);
  6708. return frustumPlanes;
  6709. };
  6710. Frustum.GetNearPlaneToRef = function (transform, frustumPlane) {
  6711. frustumPlane.normal.x = transform.m[3] + transform.m[2];
  6712. frustumPlane.normal.y = transform.m[7] + transform.m[6];
  6713. frustumPlane.normal.z = transform.m[11] + transform.m[10];
  6714. frustumPlane.d = transform.m[15] + transform.m[14];
  6715. frustumPlane.normalize();
  6716. };
  6717. Frustum.GetFarPlaneToRef = function (transform, frustumPlane) {
  6718. frustumPlane.normal.x = transform.m[3] - transform.m[2];
  6719. frustumPlane.normal.y = transform.m[7] - transform.m[6];
  6720. frustumPlane.normal.z = transform.m[11] - transform.m[10];
  6721. frustumPlane.d = transform.m[15] - transform.m[14];
  6722. frustumPlane.normalize();
  6723. };
  6724. Frustum.GetLeftPlaneToRef = function (transform, frustumPlane) {
  6725. frustumPlane.normal.x = transform.m[3] + transform.m[0];
  6726. frustumPlane.normal.y = transform.m[7] + transform.m[4];
  6727. frustumPlane.normal.z = transform.m[11] + transform.m[8];
  6728. frustumPlane.d = transform.m[15] + transform.m[12];
  6729. frustumPlane.normalize();
  6730. };
  6731. Frustum.GetRightPlaneToRef = function (transform, frustumPlane) {
  6732. frustumPlane.normal.x = transform.m[3] - transform.m[0];
  6733. frustumPlane.normal.y = transform.m[7] - transform.m[4];
  6734. frustumPlane.normal.z = transform.m[11] - transform.m[8];
  6735. frustumPlane.d = transform.m[15] - transform.m[12];
  6736. frustumPlane.normalize();
  6737. };
  6738. Frustum.GetTopPlaneToRef = function (transform, frustumPlane) {
  6739. frustumPlane.normal.x = transform.m[3] - transform.m[1];
  6740. frustumPlane.normal.y = transform.m[7] - transform.m[5];
  6741. frustumPlane.normal.z = transform.m[11] - transform.m[9];
  6742. frustumPlane.d = transform.m[15] - transform.m[13];
  6743. frustumPlane.normalize();
  6744. };
  6745. Frustum.GetBottomPlaneToRef = function (transform, frustumPlane) {
  6746. frustumPlane.normal.x = transform.m[3] + transform.m[1];
  6747. frustumPlane.normal.y = transform.m[7] + transform.m[5];
  6748. frustumPlane.normal.z = transform.m[11] + transform.m[9];
  6749. frustumPlane.d = transform.m[15] + transform.m[13];
  6750. frustumPlane.normalize();
  6751. };
  6752. /**
  6753. * Sets the given array "frustumPlanes" with the 6 Frustum planes computed by the given transformation matrix.
  6754. */
  6755. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  6756. // Near
  6757. Frustum.GetNearPlaneToRef(transform, frustumPlanes[0]);
  6758. // Far
  6759. Frustum.GetFarPlaneToRef(transform, frustumPlanes[1]);
  6760. // Left
  6761. Frustum.GetLeftPlaneToRef(transform, frustumPlanes[2]);
  6762. // Right
  6763. Frustum.GetRightPlaneToRef(transform, frustumPlanes[3]);
  6764. // Top
  6765. Frustum.GetTopPlaneToRef(transform, frustumPlanes[4]);
  6766. // Bottom
  6767. Frustum.GetBottomPlaneToRef(transform, frustumPlanes[5]);
  6768. };
  6769. return Frustum;
  6770. }());
  6771. BABYLON.Frustum = Frustum;
  6772. /** Defines supported spaces */
  6773. var Space;
  6774. (function (Space) {
  6775. /** Local (object) space */
  6776. Space[Space["LOCAL"] = 0] = "LOCAL";
  6777. /** World space */
  6778. Space[Space["WORLD"] = 1] = "WORLD";
  6779. /** Bone space */
  6780. Space[Space["BONE"] = 2] = "BONE";
  6781. })(Space = BABYLON.Space || (BABYLON.Space = {}));
  6782. /** Defines the 3 main axes */
  6783. var Axis = /** @class */ (function () {
  6784. function Axis() {
  6785. }
  6786. /** X axis */
  6787. Axis.X = new Vector3(1.0, 0.0, 0.0);
  6788. /** Y axis */
  6789. Axis.Y = new Vector3(0.0, 1.0, 0.0);
  6790. /** Z axis */
  6791. Axis.Z = new Vector3(0.0, 0.0, 1.0);
  6792. return Axis;
  6793. }());
  6794. BABYLON.Axis = Axis;
  6795. ;
  6796. var BezierCurve = /** @class */ (function () {
  6797. function BezierCurve() {
  6798. }
  6799. /**
  6800. * Returns the cubic Bezier interpolated value (float) at "t" (float) from the given x1, y1, x2, y2 floats.
  6801. */
  6802. BezierCurve.interpolate = function (t, x1, y1, x2, y2) {
  6803. // Extract X (which is equal to time here)
  6804. var f0 = 1 - 3 * x2 + 3 * x1;
  6805. var f1 = 3 * x2 - 6 * x1;
  6806. var f2 = 3 * x1;
  6807. var refinedT = t;
  6808. for (var i = 0; i < 5; i++) {
  6809. var refinedT2 = refinedT * refinedT;
  6810. var refinedT3 = refinedT2 * refinedT;
  6811. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  6812. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  6813. refinedT -= (x - t) * slope;
  6814. refinedT = Math.min(1, Math.max(0, refinedT));
  6815. }
  6816. // Resolve cubic bezier for the given x
  6817. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 +
  6818. 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 +
  6819. Math.pow(refinedT, 3);
  6820. };
  6821. return BezierCurve;
  6822. }());
  6823. BABYLON.BezierCurve = BezierCurve;
  6824. /**
  6825. * Defines potential orientation for back face culling
  6826. */
  6827. var Orientation;
  6828. (function (Orientation) {
  6829. /**
  6830. * Clockwise
  6831. */
  6832. Orientation[Orientation["CW"] = 0] = "CW";
  6833. /** Counter clockwise */
  6834. Orientation[Orientation["CCW"] = 1] = "CCW";
  6835. })(Orientation = BABYLON.Orientation || (BABYLON.Orientation = {}));
  6836. /**
  6837. * Defines angle representation
  6838. */
  6839. var Angle = /** @class */ (function () {
  6840. /**
  6841. * Creates an Angle object of "radians" radians (float).
  6842. */
  6843. function Angle(radians) {
  6844. this._radians = radians;
  6845. if (this._radians < 0.0)
  6846. this._radians += (2.0 * Math.PI);
  6847. }
  6848. /**
  6849. * Get value in degrees
  6850. * @returns the Angle value in degrees (float)
  6851. */
  6852. Angle.prototype.degrees = function () {
  6853. return this._radians * 180.0 / Math.PI;
  6854. };
  6855. /**
  6856. * Get value in radians
  6857. * @returns the Angle value in radians (float)
  6858. */
  6859. Angle.prototype.radians = function () {
  6860. return this._radians;
  6861. };
  6862. /**
  6863. * Gets a new Angle object valued with the angle value in radians between the two given vectors
  6864. * @param a defines first vector
  6865. * @param b defines second vector
  6866. * @returns a new Angle
  6867. */
  6868. Angle.BetweenTwoPoints = function (a, b) {
  6869. var delta = b.subtract(a);
  6870. var theta = Math.atan2(delta.y, delta.x);
  6871. return new Angle(theta);
  6872. };
  6873. /**
  6874. * Gets a new Angle object from the given float in radians
  6875. * @param radians defines the angle value in radians
  6876. * @returns a new Angle
  6877. */
  6878. Angle.FromRadians = function (radians) {
  6879. return new Angle(radians);
  6880. };
  6881. /**
  6882. * Gets a new Angle object from the given float in degrees
  6883. * @param degrees defines the angle value in degrees
  6884. * @returns a new Angle
  6885. */
  6886. Angle.FromDegrees = function (degrees) {
  6887. return new Angle(degrees * Math.PI / 180.0);
  6888. };
  6889. return Angle;
  6890. }());
  6891. BABYLON.Angle = Angle;
  6892. var Arc2 = /** @class */ (function () {
  6893. /**
  6894. * Creates an Arc object from the three given points : start, middle and end.
  6895. */
  6896. function Arc2(startPoint, midPoint, endPoint) {
  6897. this.startPoint = startPoint;
  6898. this.midPoint = midPoint;
  6899. this.endPoint = endPoint;
  6900. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  6901. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  6902. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  6903. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  6904. 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);
  6905. this.radius = this.centerPoint.subtract(this.startPoint).length();
  6906. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  6907. var a1 = this.startAngle.degrees();
  6908. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  6909. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  6910. // angles correction
  6911. if (a2 - a1 > +180.0)
  6912. a2 -= 360.0;
  6913. if (a2 - a1 < -180.0)
  6914. a2 += 360.0;
  6915. if (a3 - a2 > +180.0)
  6916. a3 -= 360.0;
  6917. if (a3 - a2 < -180.0)
  6918. a3 += 360.0;
  6919. this.orientation = (a2 - a1) < 0 ? Orientation.CW : Orientation.CCW;
  6920. this.angle = Angle.FromDegrees(this.orientation === Orientation.CW ? a1 - a3 : a3 - a1);
  6921. }
  6922. return Arc2;
  6923. }());
  6924. BABYLON.Arc2 = Arc2;
  6925. var Path2 = /** @class */ (function () {
  6926. /**
  6927. * Creates a Path2 object from the starting 2D coordinates x and y.
  6928. */
  6929. function Path2(x, y) {
  6930. this._points = new Array();
  6931. this._length = 0.0;
  6932. this.closed = false;
  6933. this._points.push(new Vector2(x, y));
  6934. }
  6935. /**
  6936. * Adds a new segment until the given coordinates (x, y) to the current Path2.
  6937. * Returns the updated Path2.
  6938. */
  6939. Path2.prototype.addLineTo = function (x, y) {
  6940. if (this.closed) {
  6941. return this;
  6942. }
  6943. var newPoint = new Vector2(x, y);
  6944. var previousPoint = this._points[this._points.length - 1];
  6945. this._points.push(newPoint);
  6946. this._length += newPoint.subtract(previousPoint).length();
  6947. return this;
  6948. };
  6949. /**
  6950. * 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.
  6951. * Returns the updated Path2.
  6952. */
  6953. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  6954. if (numberOfSegments === void 0) { numberOfSegments = 36; }
  6955. if (this.closed) {
  6956. return this;
  6957. }
  6958. var startPoint = this._points[this._points.length - 1];
  6959. var midPoint = new Vector2(midX, midY);
  6960. var endPoint = new Vector2(endX, endY);
  6961. var arc = new Arc2(startPoint, midPoint, endPoint);
  6962. var increment = arc.angle.radians() / numberOfSegments;
  6963. if (arc.orientation === Orientation.CW)
  6964. increment *= -1;
  6965. var currentAngle = arc.startAngle.radians() + increment;
  6966. for (var i = 0; i < numberOfSegments; i++) {
  6967. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  6968. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  6969. this.addLineTo(x, y);
  6970. currentAngle += increment;
  6971. }
  6972. return this;
  6973. };
  6974. /**
  6975. * Closes the Path2.
  6976. * Returns the Path2.
  6977. */
  6978. Path2.prototype.close = function () {
  6979. this.closed = true;
  6980. return this;
  6981. };
  6982. /**
  6983. * Returns the Path2 total length (float).
  6984. */
  6985. Path2.prototype.length = function () {
  6986. var result = this._length;
  6987. if (!this.closed) {
  6988. var lastPoint = this._points[this._points.length - 1];
  6989. var firstPoint = this._points[0];
  6990. result += (firstPoint.subtract(lastPoint).length());
  6991. }
  6992. return result;
  6993. };
  6994. /**
  6995. * Returns the Path2 internal array of points.
  6996. */
  6997. Path2.prototype.getPoints = function () {
  6998. return this._points;
  6999. };
  7000. /**
  7001. * Returns a new Vector2 located at a percentage of the Path2 total length on this path.
  7002. */
  7003. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  7004. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  7005. return Vector2.Zero();
  7006. }
  7007. var lengthPosition = normalizedLengthPosition * this.length();
  7008. var previousOffset = 0;
  7009. for (var i = 0; i < this._points.length; i++) {
  7010. var j = (i + 1) % this._points.length;
  7011. var a = this._points[i];
  7012. var b = this._points[j];
  7013. var bToA = b.subtract(a);
  7014. var nextOffset = (bToA.length() + previousOffset);
  7015. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  7016. var dir = bToA.normalize();
  7017. var localOffset = lengthPosition - previousOffset;
  7018. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  7019. }
  7020. previousOffset = nextOffset;
  7021. }
  7022. return Vector2.Zero();
  7023. };
  7024. /**
  7025. * Returns a new Path2 starting at the coordinates (x, y).
  7026. */
  7027. Path2.StartingAt = function (x, y) {
  7028. return new Path2(x, y);
  7029. };
  7030. return Path2;
  7031. }());
  7032. BABYLON.Path2 = Path2;
  7033. var Path3D = /** @class */ (function () {
  7034. /**
  7035. * new Path3D(path, normal, raw)
  7036. * Creates a Path3D. A Path3D is a logical math object, so not a mesh.
  7037. * please read the description in the tutorial : http://doc.babylonjs.com/tutorials/How_to_use_Path3D
  7038. * path : an array of Vector3, the curve axis of the Path3D
  7039. * normal (optional) : Vector3, the first wanted normal to the curve. Ex (0, 1, 0) for a vertical normal.
  7040. * raw (optional, default false) : boolean, if true the returned Path3D isn't normalized. Useful to depict path acceleration or speed.
  7041. */
  7042. function Path3D(path, firstNormal, raw) {
  7043. if (firstNormal === void 0) { firstNormal = null; }
  7044. this.path = path;
  7045. this._curve = new Array();
  7046. this._distances = new Array();
  7047. this._tangents = new Array();
  7048. this._normals = new Array();
  7049. this._binormals = new Array();
  7050. for (var p = 0; p < path.length; p++) {
  7051. this._curve[p] = path[p].clone(); // hard copy
  7052. }
  7053. this._raw = raw || false;
  7054. this._compute(firstNormal);
  7055. }
  7056. /**
  7057. * Returns the Path3D array of successive Vector3 designing its curve.
  7058. */
  7059. Path3D.prototype.getCurve = function () {
  7060. return this._curve;
  7061. };
  7062. /**
  7063. * Returns an array populated with tangent vectors on each Path3D curve point.
  7064. */
  7065. Path3D.prototype.getTangents = function () {
  7066. return this._tangents;
  7067. };
  7068. /**
  7069. * Returns an array populated with normal vectors on each Path3D curve point.
  7070. */
  7071. Path3D.prototype.getNormals = function () {
  7072. return this._normals;
  7073. };
  7074. /**
  7075. * Returns an array populated with binormal vectors on each Path3D curve point.
  7076. */
  7077. Path3D.prototype.getBinormals = function () {
  7078. return this._binormals;
  7079. };
  7080. /**
  7081. * Returns an array populated with distances (float) of the i-th point from the first curve point.
  7082. */
  7083. Path3D.prototype.getDistances = function () {
  7084. return this._distances;
  7085. };
  7086. /**
  7087. * Forces the Path3D tangent, normal, binormal and distance recomputation.
  7088. * Returns the same object updated.
  7089. */
  7090. Path3D.prototype.update = function (path, firstNormal) {
  7091. if (firstNormal === void 0) { firstNormal = null; }
  7092. for (var p = 0; p < path.length; p++) {
  7093. this._curve[p].x = path[p].x;
  7094. this._curve[p].y = path[p].y;
  7095. this._curve[p].z = path[p].z;
  7096. }
  7097. this._compute(firstNormal);
  7098. return this;
  7099. };
  7100. // private function compute() : computes tangents, normals and binormals
  7101. Path3D.prototype._compute = function (firstNormal) {
  7102. var l = this._curve.length;
  7103. // first and last tangents
  7104. this._tangents[0] = this._getFirstNonNullVector(0);
  7105. if (!this._raw) {
  7106. this._tangents[0].normalize();
  7107. }
  7108. this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);
  7109. if (!this._raw) {
  7110. this._tangents[l - 1].normalize();
  7111. }
  7112. // normals and binormals at first point : arbitrary vector with _normalVector()
  7113. var tg0 = this._tangents[0];
  7114. var pp0 = this._normalVector(this._curve[0], tg0, firstNormal);
  7115. this._normals[0] = pp0;
  7116. if (!this._raw) {
  7117. this._normals[0].normalize();
  7118. }
  7119. this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);
  7120. if (!this._raw) {
  7121. this._binormals[0].normalize();
  7122. }
  7123. this._distances[0] = 0.0;
  7124. // normals and binormals : next points
  7125. var prev; // previous vector (segment)
  7126. var cur; // current vector (segment)
  7127. var curTang; // current tangent
  7128. // previous normal
  7129. var prevBinor; // previous binormal
  7130. for (var i = 1; i < l; i++) {
  7131. // tangents
  7132. prev = this._getLastNonNullVector(i);
  7133. if (i < l - 1) {
  7134. cur = this._getFirstNonNullVector(i);
  7135. this._tangents[i] = prev.add(cur);
  7136. this._tangents[i].normalize();
  7137. }
  7138. this._distances[i] = this._distances[i - 1] + prev.length();
  7139. // normals and binormals
  7140. // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html
  7141. curTang = this._tangents[i];
  7142. prevBinor = this._binormals[i - 1];
  7143. this._normals[i] = Vector3.Cross(prevBinor, curTang);
  7144. if (!this._raw) {
  7145. this._normals[i].normalize();
  7146. }
  7147. this._binormals[i] = Vector3.Cross(curTang, this._normals[i]);
  7148. if (!this._raw) {
  7149. this._binormals[i].normalize();
  7150. }
  7151. }
  7152. };
  7153. // private function getFirstNonNullVector(index)
  7154. // returns the first non null vector from index : curve[index + N].subtract(curve[index])
  7155. Path3D.prototype._getFirstNonNullVector = function (index) {
  7156. var i = 1;
  7157. var nNVector = this._curve[index + i].subtract(this._curve[index]);
  7158. while (nNVector.length() === 0 && index + i + 1 < this._curve.length) {
  7159. i++;
  7160. nNVector = this._curve[index + i].subtract(this._curve[index]);
  7161. }
  7162. return nNVector;
  7163. };
  7164. // private function getLastNonNullVector(index)
  7165. // returns the last non null vector from index : curve[index].subtract(curve[index - N])
  7166. Path3D.prototype._getLastNonNullVector = function (index) {
  7167. var i = 1;
  7168. var nLVector = this._curve[index].subtract(this._curve[index - i]);
  7169. while (nLVector.length() === 0 && index > i + 1) {
  7170. i++;
  7171. nLVector = this._curve[index].subtract(this._curve[index - i]);
  7172. }
  7173. return nLVector;
  7174. };
  7175. // private function normalVector(v0, vt, va) :
  7176. // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane
  7177. // if va is passed, it returns the va projection on the plane orthogonal to vt at the point v0
  7178. Path3D.prototype._normalVector = function (v0, vt, va) {
  7179. var normal0;
  7180. var tgl = vt.length();
  7181. if (tgl === 0.0) {
  7182. tgl = 1.0;
  7183. }
  7184. if (va === undefined || va === null) {
  7185. var point;
  7186. if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.y) / tgl, 1.0, BABYLON.Epsilon)) { // search for a point in the plane
  7187. point = new Vector3(0.0, -1.0, 0.0);
  7188. }
  7189. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.x) / tgl, 1.0, BABYLON.Epsilon)) {
  7190. point = new Vector3(1.0, 0.0, 0.0);
  7191. }
  7192. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.z) / tgl, 1.0, BABYLON.Epsilon)) {
  7193. point = new Vector3(0.0, 0.0, 1.0);
  7194. }
  7195. else {
  7196. point = Vector3.Zero();
  7197. }
  7198. normal0 = Vector3.Cross(vt, point);
  7199. }
  7200. else {
  7201. normal0 = Vector3.Cross(vt, va);
  7202. Vector3.CrossToRef(normal0, vt, normal0);
  7203. }
  7204. normal0.normalize();
  7205. return normal0;
  7206. };
  7207. return Path3D;
  7208. }());
  7209. BABYLON.Path3D = Path3D;
  7210. var Curve3 = /** @class */ (function () {
  7211. /**
  7212. * A Curve3 object is a logical object, so not a mesh, to handle curves in the 3D geometric space.
  7213. * A Curve3 is designed from a series of successive Vector3.
  7214. * Tuto : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#curve3-object
  7215. */
  7216. function Curve3(points) {
  7217. this._length = 0.0;
  7218. this._points = points;
  7219. this._length = this._computeLength(points);
  7220. }
  7221. /**
  7222. * Returns a Curve3 object along a Quadratic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#quadratic-bezier-curve
  7223. * @param v0 (Vector3) the origin point of the Quadratic Bezier
  7224. * @param v1 (Vector3) the control point
  7225. * @param v2 (Vector3) the end point of the Quadratic Bezier
  7226. * @param nbPoints (integer) the wanted number of points in the curve
  7227. */
  7228. Curve3.CreateQuadraticBezier = function (v0, v1, v2, nbPoints) {
  7229. nbPoints = nbPoints > 2 ? nbPoints : 3;
  7230. var bez = new Array();
  7231. var equation = function (t, val0, val1, val2) {
  7232. var res = (1.0 - t) * (1.0 - t) * val0 + 2.0 * t * (1.0 - t) * val1 + t * t * val2;
  7233. return res;
  7234. };
  7235. for (var i = 0; i <= nbPoints; i++) {
  7236. 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)));
  7237. }
  7238. return new Curve3(bez);
  7239. };
  7240. /**
  7241. * Returns a Curve3 object along a Cubic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#cubic-bezier-curve
  7242. * @param v0 (Vector3) the origin point of the Cubic Bezier
  7243. * @param v1 (Vector3) the first control point
  7244. * @param v2 (Vector3) the second control point
  7245. * @param v3 (Vector3) the end point of the Cubic Bezier
  7246. * @param nbPoints (integer) the wanted number of points in the curve
  7247. */
  7248. Curve3.CreateCubicBezier = function (v0, v1, v2, v3, nbPoints) {
  7249. nbPoints = nbPoints > 3 ? nbPoints : 4;
  7250. var bez = new Array();
  7251. var equation = function (t, val0, val1, val2, val3) {
  7252. 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;
  7253. return res;
  7254. };
  7255. for (var i = 0; i <= nbPoints; i++) {
  7256. 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)));
  7257. }
  7258. return new Curve3(bez);
  7259. };
  7260. /**
  7261. * Returns a Curve3 object along a Hermite Spline curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#hermite-spline
  7262. * @param p1 (Vector3) the origin point of the Hermite Spline
  7263. * @param t1 (Vector3) the tangent vector at the origin point
  7264. * @param p2 (Vector3) the end point of the Hermite Spline
  7265. * @param t2 (Vector3) the tangent vector at the end point
  7266. * @param nbPoints (integer) the wanted number of points in the curve
  7267. */
  7268. Curve3.CreateHermiteSpline = function (p1, t1, p2, t2, nbPoints) {
  7269. var hermite = new Array();
  7270. var step = 1.0 / nbPoints;
  7271. for (var i = 0; i <= nbPoints; i++) {
  7272. hermite.push(Vector3.Hermite(p1, t1, p2, t2, i * step));
  7273. }
  7274. return new Curve3(hermite);
  7275. };
  7276. /**
  7277. * Returns a Curve3 object along a CatmullRom Spline curve :
  7278. * @param points (array of Vector3) the points the spline must pass through. At least, four points required
  7279. * @param nbPoints (integer) the wanted number of points between each curve control points
  7280. * @param closed (boolean) optional with default false, when true forms a closed loop from the points
  7281. */
  7282. Curve3.CreateCatmullRomSpline = function (points, nbPoints, closed) {
  7283. var catmullRom = new Array();
  7284. var step = 1.0 / nbPoints;
  7285. var amount = 0.0;
  7286. if (closed) {
  7287. var pointsCount = points.length;
  7288. for (var i = 0; i < pointsCount; i++) {
  7289. amount = 0;
  7290. for (var c = 0; c < nbPoints; c++) {
  7291. catmullRom.push(Vector3.CatmullRom(points[i % pointsCount], points[(i + 1) % pointsCount], points[(i + 2) % pointsCount], points[(i + 3) % pointsCount], amount));
  7292. amount += step;
  7293. }
  7294. }
  7295. catmullRom.push(catmullRom[0]);
  7296. }
  7297. else {
  7298. var totalPoints = new Array();
  7299. totalPoints.push(points[0].clone());
  7300. Array.prototype.push.apply(totalPoints, points);
  7301. totalPoints.push(points[points.length - 1].clone());
  7302. for (var i = 0; i < totalPoints.length - 3; i++) {
  7303. amount = 0;
  7304. for (var c = 0; c < nbPoints; c++) {
  7305. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  7306. amount += step;
  7307. }
  7308. }
  7309. i--;
  7310. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  7311. }
  7312. return new Curve3(catmullRom);
  7313. };
  7314. /**
  7315. * Returns the Curve3 stored array of successive Vector3
  7316. */
  7317. Curve3.prototype.getPoints = function () {
  7318. return this._points;
  7319. };
  7320. /**
  7321. * Returns the computed length (float) of the curve.
  7322. */
  7323. Curve3.prototype.length = function () {
  7324. return this._length;
  7325. };
  7326. /**
  7327. * Returns a new instance of Curve3 object : var curve = curveA.continue(curveB);
  7328. * This new Curve3 is built by translating and sticking the curveB at the end of the curveA.
  7329. * curveA and curveB keep unchanged.
  7330. */
  7331. Curve3.prototype.continue = function (curve) {
  7332. var lastPoint = this._points[this._points.length - 1];
  7333. var continuedPoints = this._points.slice();
  7334. var curvePoints = curve.getPoints();
  7335. for (var i = 1; i < curvePoints.length; i++) {
  7336. continuedPoints.push(curvePoints[i].subtract(curvePoints[0]).add(lastPoint));
  7337. }
  7338. var continuedCurve = new Curve3(continuedPoints);
  7339. return continuedCurve;
  7340. };
  7341. Curve3.prototype._computeLength = function (path) {
  7342. var l = 0;
  7343. for (var i = 1; i < path.length; i++) {
  7344. l += (path[i].subtract(path[i - 1])).length();
  7345. }
  7346. return l;
  7347. };
  7348. return Curve3;
  7349. }());
  7350. BABYLON.Curve3 = Curve3;
  7351. // Vertex formats
  7352. var PositionNormalVertex = /** @class */ (function () {
  7353. function PositionNormalVertex(position, normal) {
  7354. if (position === void 0) { position = Vector3.Zero(); }
  7355. if (normal === void 0) { normal = Vector3.Up(); }
  7356. this.position = position;
  7357. this.normal = normal;
  7358. }
  7359. PositionNormalVertex.prototype.clone = function () {
  7360. return new PositionNormalVertex(this.position.clone(), this.normal.clone());
  7361. };
  7362. return PositionNormalVertex;
  7363. }());
  7364. BABYLON.PositionNormalVertex = PositionNormalVertex;
  7365. var PositionNormalTextureVertex = /** @class */ (function () {
  7366. function PositionNormalTextureVertex(position, normal, uv) {
  7367. if (position === void 0) { position = Vector3.Zero(); }
  7368. if (normal === void 0) { normal = Vector3.Up(); }
  7369. if (uv === void 0) { uv = Vector2.Zero(); }
  7370. this.position = position;
  7371. this.normal = normal;
  7372. this.uv = uv;
  7373. }
  7374. PositionNormalTextureVertex.prototype.clone = function () {
  7375. return new PositionNormalTextureVertex(this.position.clone(), this.normal.clone(), this.uv.clone());
  7376. };
  7377. return PositionNormalTextureVertex;
  7378. }());
  7379. BABYLON.PositionNormalTextureVertex = PositionNormalTextureVertex;
  7380. // Temporary pre-allocated objects for engine internal use
  7381. // usage in any internal function :
  7382. // var tmp = Tmp.Vector3[0]; <= gets access to the first pre-created Vector3
  7383. // There's a Tmp array per object type : int, float, Vector2, Vector3, Vector4, Quaternion, Matrix
  7384. var Tmp = /** @class */ (function () {
  7385. function Tmp() {
  7386. }
  7387. Tmp.Color3 = [Color3.Black(), Color3.Black(), Color3.Black()];
  7388. Tmp.Vector2 = [Vector2.Zero(), Vector2.Zero(), Vector2.Zero()]; // 3 temp Vector2 at once should be enough
  7389. Tmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(),
  7390. Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()]; // 9 temp Vector3 at once should be enough
  7391. Tmp.Vector4 = [Vector4.Zero(), Vector4.Zero(), Vector4.Zero()]; // 3 temp Vector4 at once should be enough
  7392. Tmp.Quaternion = [Quaternion.Zero(), Quaternion.Zero()]; // 2 temp Quaternion at once should be enough
  7393. Tmp.Matrix = [Matrix.Zero(), Matrix.Zero(),
  7394. Matrix.Zero(), Matrix.Zero(),
  7395. Matrix.Zero(), Matrix.Zero(),
  7396. Matrix.Zero(), Matrix.Zero()]; // 6 temp Matrices at once should be enough
  7397. return Tmp;
  7398. }());
  7399. BABYLON.Tmp = Tmp;
  7400. // Same as Tmp but not exported to keep it only for math functions to avoid conflicts
  7401. var MathTmp = /** @class */ (function () {
  7402. function MathTmp() {
  7403. }
  7404. MathTmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()];
  7405. MathTmp.Matrix = [Matrix.Zero(), Matrix.Zero()];
  7406. MathTmp.Quaternion = [Quaternion.Zero(), Quaternion.Zero(), Quaternion.Zero()];
  7407. return MathTmp;
  7408. }());
  7409. })(BABYLON || (BABYLON = {}));
  7410. //# sourceMappingURL=babylon.math.js.map
  7411. var BABYLON;
  7412. (function (BABYLON) {
  7413. var Scalar = /** @class */ (function () {
  7414. function Scalar() {
  7415. }
  7416. /**
  7417. * Boolean : true if the absolute difference between a and b is lower than epsilon (default = 1.401298E-45)
  7418. */
  7419. Scalar.WithinEpsilon = function (a, b, epsilon) {
  7420. if (epsilon === void 0) { epsilon = 1.401298E-45; }
  7421. var num = a - b;
  7422. return -epsilon <= num && num <= epsilon;
  7423. };
  7424. /**
  7425. * Returns a string : the upper case translation of the number i to hexadecimal.
  7426. */
  7427. Scalar.ToHex = function (i) {
  7428. var str = i.toString(16);
  7429. if (i <= 15) {
  7430. return ("0" + str).toUpperCase();
  7431. }
  7432. return str.toUpperCase();
  7433. };
  7434. /**
  7435. * Returns -1 if value is negative and +1 is value is positive.
  7436. * Returns the value itself if it's equal to zero.
  7437. */
  7438. Scalar.Sign = function (value) {
  7439. value = +value; // convert to a number
  7440. if (value === 0 || isNaN(value))
  7441. return value;
  7442. return value > 0 ? 1 : -1;
  7443. };
  7444. /**
  7445. * Returns the value itself if it's between min and max.
  7446. * Returns min if the value is lower than min.
  7447. * Returns max if the value is greater than max.
  7448. */
  7449. Scalar.Clamp = function (value, min, max) {
  7450. if (min === void 0) { min = 0; }
  7451. if (max === void 0) { max = 1; }
  7452. return Math.min(max, Math.max(min, value));
  7453. };
  7454. /**
  7455. * Returns the log2 of value.
  7456. */
  7457. Scalar.Log2 = function (value) {
  7458. return Math.log(value) * Math.LOG2E;
  7459. };
  7460. /**
  7461. * Loops the value, so that it is never larger than length and never smaller than 0.
  7462. *
  7463. * This is similar to the modulo operator but it works with floating point numbers.
  7464. * For example, using 3.0 for t and 2.5 for length, the result would be 0.5.
  7465. * With t = 5 and length = 2.5, the result would be 0.0.
  7466. * Note, however, that the behaviour is not defined for negative numbers as it is for the modulo operator
  7467. */
  7468. Scalar.Repeat = function (value, length) {
  7469. return value - Math.floor(value / length) * length;
  7470. };
  7471. /**
  7472. * Normalize the value between 0.0 and 1.0 using min and max values
  7473. */
  7474. Scalar.Normalize = function (value, min, max) {
  7475. return (value - min) / (max - min);
  7476. };
  7477. /**
  7478. * Denormalize the value from 0.0 and 1.0 using min and max values
  7479. */
  7480. Scalar.Denormalize = function (normalized, min, max) {
  7481. return (normalized * (max - min) + min);
  7482. };
  7483. /**
  7484. * Calculates the shortest difference between two given angles given in degrees.
  7485. */
  7486. Scalar.DeltaAngle = function (current, target) {
  7487. var num = Scalar.Repeat(target - current, 360.0);
  7488. if (num > 180.0) {
  7489. num -= 360.0;
  7490. }
  7491. return num;
  7492. };
  7493. /**
  7494. * PingPongs the value t, so that it is never larger than length and never smaller than 0.
  7495. *
  7496. * The returned value will move back and forth between 0 and length
  7497. */
  7498. Scalar.PingPong = function (tx, length) {
  7499. var t = Scalar.Repeat(tx, length * 2.0);
  7500. return length - Math.abs(t - length);
  7501. };
  7502. /**
  7503. * Interpolates between min and max with smoothing at the limits.
  7504. *
  7505. * This function interpolates between min and max in a similar way to Lerp. However, the interpolation will gradually speed up
  7506. * from the start and slow down toward the end. This is useful for creating natural-looking animation, fading and other transitions.
  7507. */
  7508. Scalar.SmoothStep = function (from, to, tx) {
  7509. var t = Scalar.Clamp(tx);
  7510. t = -2.0 * t * t * t + 3.0 * t * t;
  7511. return to * t + from * (1.0 - t);
  7512. };
  7513. /**
  7514. * Moves a value current towards target.
  7515. *
  7516. * This is essentially the same as Mathf.Lerp but instead the function will ensure that the speed never exceeds maxDelta.
  7517. * Negative values of maxDelta pushes the value away from target.
  7518. */
  7519. Scalar.MoveTowards = function (current, target, maxDelta) {
  7520. var result = 0;
  7521. if (Math.abs(target - current) <= maxDelta) {
  7522. result = target;
  7523. }
  7524. else {
  7525. result = current + Scalar.Sign(target - current) * maxDelta;
  7526. }
  7527. return result;
  7528. };
  7529. /**
  7530. * Same as MoveTowards but makes sure the values interpolate correctly when they wrap around 360 degrees.
  7531. *
  7532. * Variables current and target are assumed to be in degrees. For optimization reasons, negative values of maxDelta
  7533. * are not supported and may cause oscillation. To push current away from a target angle, add 180 to that angle instead.
  7534. */
  7535. Scalar.MoveTowardsAngle = function (current, target, maxDelta) {
  7536. var num = Scalar.DeltaAngle(current, target);
  7537. var result = 0;
  7538. if (-maxDelta < num && num < maxDelta) {
  7539. result = target;
  7540. }
  7541. else {
  7542. target = current + num;
  7543. result = Scalar.MoveTowards(current, target, maxDelta);
  7544. }
  7545. return result;
  7546. };
  7547. /**
  7548. * Creates a new scalar with values linearly interpolated of "amount" between the start scalar and the end scalar.
  7549. */
  7550. Scalar.Lerp = function (start, end, amount) {
  7551. return start + ((end - start) * amount);
  7552. };
  7553. /**
  7554. * Same as Lerp but makes sure the values interpolate correctly when they wrap around 360 degrees.
  7555. * The parameter t is clamped to the range [0, 1]. Variables a and b are assumed to be in degrees.
  7556. */
  7557. Scalar.LerpAngle = function (start, end, amount) {
  7558. var num = Scalar.Repeat(end - start, 360.0);
  7559. if (num > 180.0) {
  7560. num -= 360.0;
  7561. }
  7562. return start + num * Scalar.Clamp(amount);
  7563. };
  7564. /**
  7565. * Calculates the linear parameter t that produces the interpolant value within the range [a, b].
  7566. */
  7567. Scalar.InverseLerp = function (a, b, value) {
  7568. var result = 0;
  7569. if (a != b) {
  7570. result = Scalar.Clamp((value - a) / (b - a));
  7571. }
  7572. else {
  7573. result = 0.0;
  7574. }
  7575. return result;
  7576. };
  7577. /**
  7578. * Returns a new scalar located for "amount" (float) on the Hermite spline defined by the scalars "value1", "value3", "tangent1", "tangent2".
  7579. */
  7580. Scalar.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  7581. var squared = amount * amount;
  7582. var cubed = amount * squared;
  7583. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  7584. var part2 = (-2.0 * cubed) + (3.0 * squared);
  7585. var part3 = (cubed - (2.0 * squared)) + amount;
  7586. var part4 = cubed - squared;
  7587. return (((value1 * part1) + (value2 * part2)) + (tangent1 * part3)) + (tangent2 * part4);
  7588. };
  7589. /**
  7590. * Returns a random float number between and min and max values
  7591. */
  7592. Scalar.RandomRange = function (min, max) {
  7593. if (min === max)
  7594. return min;
  7595. return ((Math.random() * (max - min)) + min);
  7596. };
  7597. /**
  7598. * This function returns percentage of a number in a given range.
  7599. *
  7600. * RangeToPercent(40,20,60) will return 0.5 (50%)
  7601. * RangeToPercent(34,0,100) will return 0.34 (34%)
  7602. */
  7603. Scalar.RangeToPercent = function (number, min, max) {
  7604. return ((number - min) / (max - min));
  7605. };
  7606. /**
  7607. * This function returns number that corresponds to the percentage in a given range.
  7608. *
  7609. * PercentToRange(0.34,0,100) will return 34.
  7610. */
  7611. Scalar.PercentToRange = function (percent, min, max) {
  7612. return ((max - min) * percent + min);
  7613. };
  7614. /**
  7615. * Returns the angle converted to equivalent value between -Math.PI and Math.PI radians.
  7616. * @param angle The angle to normalize in radian.
  7617. * @return The converted angle.
  7618. */
  7619. Scalar.NormalizeRadians = function (angle) {
  7620. // More precise but slower version kept for reference.
  7621. // angle = angle % Tools.TwoPi;
  7622. // angle = (angle + Tools.TwoPi) % Tools.TwoPi;
  7623. //if (angle > Math.PI) {
  7624. // angle -= Tools.TwoPi;
  7625. //}
  7626. angle -= (Scalar.TwoPi * Math.floor((angle + Math.PI) / Scalar.TwoPi));
  7627. return angle;
  7628. };
  7629. /**
  7630. * Two pi constants convenient for computation.
  7631. */
  7632. Scalar.TwoPi = Math.PI * 2;
  7633. return Scalar;
  7634. }());
  7635. BABYLON.Scalar = Scalar;
  7636. })(BABYLON || (BABYLON = {}));
  7637. //# sourceMappingURL=babylon.math.scalar.js.map
  7638. //# sourceMappingURL=babylon.mixins.js.map
  7639. // Type definitions for WebGL 2, Editor's Draft Fri Feb 24 16:10:18 2017 -0800
  7640. // Project: https://www.khronos.org/registry/webgl/specs/latest/2.0/
  7641. // Definitions by: Nico Kemnitz <https://github.com/nkemnitz/>
  7642. // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
  7643. //# sourceMappingURL=babylon.webgl2.js.map
  7644. var BABYLON;
  7645. (function (BABYLON) {
  7646. var __decoratorInitialStore = {};
  7647. var __mergedStore = {};
  7648. var _copySource = function (creationFunction, source, instanciate) {
  7649. var destination = creationFunction();
  7650. // Tags
  7651. if (BABYLON.Tags) {
  7652. BABYLON.Tags.AddTagsTo(destination, source.tags);
  7653. }
  7654. var classStore = getMergedStore(destination);
  7655. // Properties
  7656. for (var property in classStore) {
  7657. var propertyDescriptor = classStore[property];
  7658. var sourceProperty = source[property];
  7659. var propertyType = propertyDescriptor.type;
  7660. if (sourceProperty !== undefined && sourceProperty !== null) {
  7661. switch (propertyType) {
  7662. case 0: // Value
  7663. case 6: // Mesh reference
  7664. case 11: // Camera reference
  7665. destination[property] = sourceProperty;
  7666. break;
  7667. case 1: // Texture
  7668. destination[property] = (instanciate || sourceProperty.isRenderTarget) ? sourceProperty : sourceProperty.clone();
  7669. break;
  7670. case 2: // Color3
  7671. case 3: // FresnelParameters
  7672. case 4: // Vector2
  7673. case 5: // Vector3
  7674. case 7: // Color Curves
  7675. case 10: // Quaternion
  7676. destination[property] = instanciate ? sourceProperty : sourceProperty.clone();
  7677. break;
  7678. }
  7679. }
  7680. }
  7681. return destination;
  7682. };
  7683. function getDirectStore(target) {
  7684. var classKey = target.getClassName();
  7685. if (!__decoratorInitialStore[classKey]) {
  7686. __decoratorInitialStore[classKey] = {};
  7687. }
  7688. return __decoratorInitialStore[classKey];
  7689. }
  7690. /**
  7691. * Return the list of properties flagged as serializable
  7692. * @param target: host object
  7693. */
  7694. function getMergedStore(target) {
  7695. var classKey = target.getClassName();
  7696. if (__mergedStore[classKey]) {
  7697. return __mergedStore[classKey];
  7698. }
  7699. __mergedStore[classKey] = {};
  7700. var store = __mergedStore[classKey];
  7701. var currentTarget = target;
  7702. var currentKey = classKey;
  7703. while (currentKey) {
  7704. var initialStore = __decoratorInitialStore[currentKey];
  7705. for (var property in initialStore) {
  7706. store[property] = initialStore[property];
  7707. }
  7708. var parent_1 = void 0;
  7709. var done = false;
  7710. do {
  7711. parent_1 = Object.getPrototypeOf(currentTarget);
  7712. if (!parent_1.getClassName) {
  7713. done = true;
  7714. break;
  7715. }
  7716. if (parent_1.getClassName() !== currentKey) {
  7717. break;
  7718. }
  7719. currentTarget = parent_1;
  7720. } while (parent_1);
  7721. if (done) {
  7722. break;
  7723. }
  7724. currentKey = parent_1.getClassName();
  7725. currentTarget = parent_1;
  7726. }
  7727. return store;
  7728. }
  7729. function generateSerializableMember(type, sourceName) {
  7730. return function (target, propertyKey) {
  7731. var classStore = getDirectStore(target);
  7732. if (!classStore[propertyKey]) {
  7733. classStore[propertyKey] = { type: type, sourceName: sourceName };
  7734. }
  7735. };
  7736. }
  7737. function generateExpandMember(setCallback, targetKey) {
  7738. if (targetKey === void 0) { targetKey = null; }
  7739. return function (target, propertyKey) {
  7740. var key = targetKey || ("_" + propertyKey);
  7741. Object.defineProperty(target, propertyKey, {
  7742. get: function () {
  7743. return this[key];
  7744. },
  7745. set: function (value) {
  7746. if (this[key] === value) {
  7747. return;
  7748. }
  7749. this[key] = value;
  7750. target[setCallback].apply(this);
  7751. },
  7752. enumerable: true,
  7753. configurable: true
  7754. });
  7755. };
  7756. }
  7757. function expandToProperty(callback, targetKey) {
  7758. if (targetKey === void 0) { targetKey = null; }
  7759. return generateExpandMember(callback, targetKey);
  7760. }
  7761. BABYLON.expandToProperty = expandToProperty;
  7762. function serialize(sourceName) {
  7763. return generateSerializableMember(0, sourceName); // value member
  7764. }
  7765. BABYLON.serialize = serialize;
  7766. function serializeAsTexture(sourceName) {
  7767. return generateSerializableMember(1, sourceName); // texture member
  7768. }
  7769. BABYLON.serializeAsTexture = serializeAsTexture;
  7770. function serializeAsColor3(sourceName) {
  7771. return generateSerializableMember(2, sourceName); // color3 member
  7772. }
  7773. BABYLON.serializeAsColor3 = serializeAsColor3;
  7774. function serializeAsFresnelParameters(sourceName) {
  7775. return generateSerializableMember(3, sourceName); // fresnel parameters member
  7776. }
  7777. BABYLON.serializeAsFresnelParameters = serializeAsFresnelParameters;
  7778. function serializeAsVector2(sourceName) {
  7779. return generateSerializableMember(4, sourceName); // vector2 member
  7780. }
  7781. BABYLON.serializeAsVector2 = serializeAsVector2;
  7782. function serializeAsVector3(sourceName) {
  7783. return generateSerializableMember(5, sourceName); // vector3 member
  7784. }
  7785. BABYLON.serializeAsVector3 = serializeAsVector3;
  7786. function serializeAsMeshReference(sourceName) {
  7787. return generateSerializableMember(6, sourceName); // mesh reference member
  7788. }
  7789. BABYLON.serializeAsMeshReference = serializeAsMeshReference;
  7790. function serializeAsColorCurves(sourceName) {
  7791. return generateSerializableMember(7, sourceName); // color curves
  7792. }
  7793. BABYLON.serializeAsColorCurves = serializeAsColorCurves;
  7794. function serializeAsColor4(sourceName) {
  7795. return generateSerializableMember(8, sourceName); // color 4
  7796. }
  7797. BABYLON.serializeAsColor4 = serializeAsColor4;
  7798. function serializeAsImageProcessingConfiguration(sourceName) {
  7799. return generateSerializableMember(9, sourceName); // image processing
  7800. }
  7801. BABYLON.serializeAsImageProcessingConfiguration = serializeAsImageProcessingConfiguration;
  7802. function serializeAsQuaternion(sourceName) {
  7803. return generateSerializableMember(10, sourceName); // quaternion member
  7804. }
  7805. BABYLON.serializeAsQuaternion = serializeAsQuaternion;
  7806. /**
  7807. * Decorator used to define property that can be serialized as reference to a camera
  7808. * @param sourceName defines the name of the property to decorate
  7809. */
  7810. function serializeAsCameraReference(sourceName) {
  7811. return generateSerializableMember(11, sourceName); // camera reference member
  7812. }
  7813. BABYLON.serializeAsCameraReference = serializeAsCameraReference;
  7814. var SerializationHelper = /** @class */ (function () {
  7815. function SerializationHelper() {
  7816. }
  7817. SerializationHelper.Serialize = function (entity, serializationObject) {
  7818. if (!serializationObject) {
  7819. serializationObject = {};
  7820. }
  7821. // Tags
  7822. if (BABYLON.Tags) {
  7823. serializationObject.tags = BABYLON.Tags.GetTags(entity);
  7824. }
  7825. var serializedProperties = getMergedStore(entity);
  7826. // Properties
  7827. for (var property in serializedProperties) {
  7828. var propertyDescriptor = serializedProperties[property];
  7829. var targetPropertyName = propertyDescriptor.sourceName || property;
  7830. var propertyType = propertyDescriptor.type;
  7831. var sourceProperty = entity[property];
  7832. if (sourceProperty !== undefined && sourceProperty !== null) {
  7833. switch (propertyType) {
  7834. case 0: // Value
  7835. serializationObject[targetPropertyName] = sourceProperty;
  7836. break;
  7837. case 1: // Texture
  7838. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7839. break;
  7840. case 2: // Color3
  7841. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7842. break;
  7843. case 3: // FresnelParameters
  7844. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7845. break;
  7846. case 4: // Vector2
  7847. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7848. break;
  7849. case 5: // Vector3
  7850. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7851. break;
  7852. case 6: // Mesh reference
  7853. serializationObject[targetPropertyName] = sourceProperty.id;
  7854. break;
  7855. case 7: // Color Curves
  7856. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7857. break;
  7858. case 8: // Color 4
  7859. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7860. break;
  7861. case 9: // Image Processing
  7862. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7863. break;
  7864. case 10: // Quaternion
  7865. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7866. break;
  7867. case 11: // Camera reference
  7868. serializationObject[targetPropertyName] = sourceProperty.id;
  7869. break;
  7870. }
  7871. }
  7872. }
  7873. return serializationObject;
  7874. };
  7875. SerializationHelper.Parse = function (creationFunction, source, scene, rootUrl) {
  7876. if (rootUrl === void 0) { rootUrl = null; }
  7877. var destination = creationFunction();
  7878. if (!rootUrl) {
  7879. rootUrl = "";
  7880. }
  7881. // Tags
  7882. if (BABYLON.Tags) {
  7883. BABYLON.Tags.AddTagsTo(destination, source.tags);
  7884. }
  7885. var classStore = getMergedStore(destination);
  7886. // Properties
  7887. for (var property in classStore) {
  7888. var propertyDescriptor = classStore[property];
  7889. var sourceProperty = source[propertyDescriptor.sourceName || property];
  7890. var propertyType = propertyDescriptor.type;
  7891. if (sourceProperty !== undefined && sourceProperty !== null) {
  7892. var dest = destination;
  7893. switch (propertyType) {
  7894. case 0: // Value
  7895. dest[property] = sourceProperty;
  7896. break;
  7897. case 1: // Texture
  7898. if (scene) {
  7899. dest[property] = BABYLON.Texture.Parse(sourceProperty, scene, rootUrl);
  7900. }
  7901. break;
  7902. case 2: // Color3
  7903. dest[property] = BABYLON.Color3.FromArray(sourceProperty);
  7904. break;
  7905. case 3: // FresnelParameters
  7906. dest[property] = BABYLON.FresnelParameters.Parse(sourceProperty);
  7907. break;
  7908. case 4: // Vector2
  7909. dest[property] = BABYLON.Vector2.FromArray(sourceProperty);
  7910. break;
  7911. case 5: // Vector3
  7912. dest[property] = BABYLON.Vector3.FromArray(sourceProperty);
  7913. break;
  7914. case 6: // Mesh reference
  7915. if (scene) {
  7916. dest[property] = scene.getLastMeshByID(sourceProperty);
  7917. }
  7918. break;
  7919. case 7: // Color Curves
  7920. dest[property] = BABYLON.ColorCurves.Parse(sourceProperty);
  7921. break;
  7922. case 8: // Color 4
  7923. dest[property] = BABYLON.Color4.FromArray(sourceProperty);
  7924. break;
  7925. case 9: // Image Processing
  7926. dest[property] = BABYLON.ImageProcessingConfiguration.Parse(sourceProperty);
  7927. break;
  7928. case 10: // Quaternion
  7929. dest[property] = BABYLON.Quaternion.FromArray(sourceProperty);
  7930. break;
  7931. case 11: // Camera reference
  7932. if (scene) {
  7933. dest[property] = scene.getCameraByID(sourceProperty);
  7934. }
  7935. break;
  7936. }
  7937. }
  7938. }
  7939. return destination;
  7940. };
  7941. SerializationHelper.Clone = function (creationFunction, source) {
  7942. return _copySource(creationFunction, source, false);
  7943. };
  7944. SerializationHelper.Instanciate = function (creationFunction, source) {
  7945. return _copySource(creationFunction, source, true);
  7946. };
  7947. return SerializationHelper;
  7948. }());
  7949. BABYLON.SerializationHelper = SerializationHelper;
  7950. })(BABYLON || (BABYLON = {}));
  7951. //# sourceMappingURL=babylon.decorators.js.map
  7952. var BABYLON;
  7953. (function (BABYLON) {
  7954. /**
  7955. * Wrapper class for promise with external resolve and reject.
  7956. */
  7957. var Deferred = /** @class */ (function () {
  7958. /**
  7959. * Constructor for this deferred object.
  7960. */
  7961. function Deferred() {
  7962. var _this = this;
  7963. this.promise = new Promise(function (resolve, reject) {
  7964. _this._resolve = resolve;
  7965. _this._reject = reject;
  7966. });
  7967. }
  7968. Object.defineProperty(Deferred.prototype, "resolve", {
  7969. /**
  7970. * The resolve method of the promise associated with this deferred object.
  7971. */
  7972. get: function () {
  7973. return this._resolve;
  7974. },
  7975. enumerable: true,
  7976. configurable: true
  7977. });
  7978. Object.defineProperty(Deferred.prototype, "reject", {
  7979. /**
  7980. * The reject method of the promise associated with this deferred object.
  7981. */
  7982. get: function () {
  7983. return this._reject;
  7984. },
  7985. enumerable: true,
  7986. configurable: true
  7987. });
  7988. return Deferred;
  7989. }());
  7990. BABYLON.Deferred = Deferred;
  7991. })(BABYLON || (BABYLON = {}));
  7992. //# sourceMappingURL=babylon.deferred.js.map
  7993. var BABYLON;
  7994. (function (BABYLON) {
  7995. /**
  7996. * A class serves as a medium between the observable and its observers
  7997. */
  7998. var EventState = /** @class */ (function () {
  7999. /**
  8000. * Create a new EventState
  8001. * @param mask defines the mask associated with this state
  8002. * @param skipNextObservers defines a flag which will instruct the observable to skip following observers when set to true
  8003. * @param target defines the original target of the state
  8004. * @param currentTarget defines the current target of the state
  8005. */
  8006. function EventState(mask, skipNextObservers, target, currentTarget) {
  8007. if (skipNextObservers === void 0) { skipNextObservers = false; }
  8008. this.initalize(mask, skipNextObservers, target, currentTarget);
  8009. }
  8010. /**
  8011. * Initialize the current event state
  8012. * @param mask defines the mask associated with this state
  8013. * @param skipNextObservers defines a flag which will instruct the observable to skip following observers when set to true
  8014. * @param target defines the original target of the state
  8015. * @param currentTarget defines the current target of the state
  8016. * @returns the current event state
  8017. */
  8018. EventState.prototype.initalize = function (mask, skipNextObservers, target, currentTarget) {
  8019. if (skipNextObservers === void 0) { skipNextObservers = false; }
  8020. this.mask = mask;
  8021. this.skipNextObservers = skipNextObservers;
  8022. this.target = target;
  8023. this.currentTarget = currentTarget;
  8024. return this;
  8025. };
  8026. return EventState;
  8027. }());
  8028. BABYLON.EventState = EventState;
  8029. /**
  8030. * Represent an Observer registered to a given Observable object.
  8031. */
  8032. var Observer = /** @class */ (function () {
  8033. /**
  8034. * Creates a new observer
  8035. * @param callback defines the callback to call when the observer is notified
  8036. * @param mask defines the mask of the observer (used to filter notifications)
  8037. * @param scope defines the current scope used to restore the JS context
  8038. */
  8039. function Observer(
  8040. /**
  8041. * Defines the callback to call when the observer is notified
  8042. */
  8043. callback,
  8044. /**
  8045. * Defines the mask of the observer (used to filter notifications)
  8046. */
  8047. mask,
  8048. /**
  8049. * Defines the current scope used to restore the JS context
  8050. */
  8051. scope) {
  8052. if (scope === void 0) { scope = null; }
  8053. this.callback = callback;
  8054. this.mask = mask;
  8055. this.scope = scope;
  8056. /** @hidden */
  8057. this._willBeUnregistered = false;
  8058. /**
  8059. * Gets or sets a property defining that the observer as to be unregistered after the next notification
  8060. */
  8061. this.unregisterOnNextCall = false;
  8062. }
  8063. return Observer;
  8064. }());
  8065. BABYLON.Observer = Observer;
  8066. /**
  8067. * Represent a list of observers registered to multiple Observables object.
  8068. */
  8069. var MultiObserver = /** @class */ (function () {
  8070. function MultiObserver() {
  8071. }
  8072. /**
  8073. * Release associated resources
  8074. */
  8075. MultiObserver.prototype.dispose = function () {
  8076. if (this._observers && this._observables) {
  8077. for (var index = 0; index < this._observers.length; index++) {
  8078. this._observables[index].remove(this._observers[index]);
  8079. }
  8080. }
  8081. this._observers = null;
  8082. this._observables = null;
  8083. };
  8084. /**
  8085. * Raise a callback when one of the observable will notify
  8086. * @param observables defines a list of observables to watch
  8087. * @param callback defines the callback to call on notification
  8088. * @param mask defines the mask used to filter notifications
  8089. * @param scope defines the current scope used to restore the JS context
  8090. * @returns the new MultiObserver
  8091. */
  8092. MultiObserver.Watch = function (observables, callback, mask, scope) {
  8093. if (mask === void 0) { mask = -1; }
  8094. if (scope === void 0) { scope = null; }
  8095. var result = new MultiObserver();
  8096. result._observers = new Array();
  8097. result._observables = observables;
  8098. for (var _i = 0, observables_1 = observables; _i < observables_1.length; _i++) {
  8099. var observable = observables_1[_i];
  8100. var observer = observable.add(callback, mask, false, scope);
  8101. if (observer) {
  8102. result._observers.push(observer);
  8103. }
  8104. }
  8105. return result;
  8106. };
  8107. return MultiObserver;
  8108. }());
  8109. BABYLON.MultiObserver = MultiObserver;
  8110. /**
  8111. * The Observable class is a simple implementation of the Observable pattern.
  8112. *
  8113. * 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.
  8114. * This enable a more fine grained execution without having to rely on multiple different Observable objects.
  8115. * 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).
  8116. * 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.
  8117. */
  8118. var Observable = /** @class */ (function () {
  8119. /**
  8120. * Creates a new observable
  8121. * @param onObserverAdded defines a callback to call when a new observer is added
  8122. */
  8123. function Observable(onObserverAdded) {
  8124. this._observers = new Array();
  8125. this._eventState = new EventState(0);
  8126. if (onObserverAdded) {
  8127. this._onObserverAdded = onObserverAdded;
  8128. }
  8129. }
  8130. /**
  8131. * Create a new Observer with the specified callback
  8132. * @param callback the callback that will be executed for that Observer
  8133. * @param mask the mask used to filter observers
  8134. * @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.
  8135. * @param scope optional scope for the callback to be called from
  8136. * @param unregisterOnFirstCall defines if the observer as to be unregistered after the next notification
  8137. * @returns the new observer created for the callback
  8138. */
  8139. Observable.prototype.add = function (callback, mask, insertFirst, scope, unregisterOnFirstCall) {
  8140. if (mask === void 0) { mask = -1; }
  8141. if (insertFirst === void 0) { insertFirst = false; }
  8142. if (scope === void 0) { scope = null; }
  8143. if (unregisterOnFirstCall === void 0) { unregisterOnFirstCall = false; }
  8144. if (!callback) {
  8145. return null;
  8146. }
  8147. var observer = new Observer(callback, mask, scope);
  8148. observer.unregisterOnNextCall = unregisterOnFirstCall;
  8149. if (insertFirst) {
  8150. this._observers.unshift(observer);
  8151. }
  8152. else {
  8153. this._observers.push(observer);
  8154. }
  8155. if (this._onObserverAdded) {
  8156. this._onObserverAdded(observer);
  8157. }
  8158. return observer;
  8159. };
  8160. /**
  8161. * Create a new Observer with the specified callback and unregisters after the next notification
  8162. * @param callback the callback that will be executed for that Observer
  8163. * @returns the new observer created for the callback
  8164. */
  8165. Observable.prototype.addOnce = function (callback) {
  8166. return this.add(callback, undefined, undefined, undefined, true);
  8167. };
  8168. /**
  8169. * Remove an Observer from the Observable object
  8170. * @param observer the instance of the Observer to remove
  8171. * @returns false if it doesn't belong to this Observable
  8172. */
  8173. Observable.prototype.remove = function (observer) {
  8174. if (!observer) {
  8175. return false;
  8176. }
  8177. var index = this._observers.indexOf(observer);
  8178. if (index !== -1) {
  8179. this._observers.splice(index, 1);
  8180. return true;
  8181. }
  8182. return false;
  8183. };
  8184. /**
  8185. * Remove a callback from the Observable object
  8186. * @param callback the callback to remove
  8187. * @param scope optional scope. If used only the callbacks with this scope will be removed
  8188. * @returns false if it doesn't belong to this Observable
  8189. */
  8190. Observable.prototype.removeCallback = function (callback, scope) {
  8191. for (var index = 0; index < this._observers.length; index++) {
  8192. if (this._observers[index].callback === callback && (!scope || scope === this._observers[index].scope)) {
  8193. this._observers.splice(index, 1);
  8194. return true;
  8195. }
  8196. }
  8197. return false;
  8198. };
  8199. Observable.prototype._deferUnregister = function (observer) {
  8200. var _this = this;
  8201. observer.unregisterOnNextCall = false;
  8202. observer._willBeUnregistered = true;
  8203. BABYLON.Tools.SetImmediate(function () {
  8204. _this.remove(observer);
  8205. });
  8206. };
  8207. /**
  8208. * Notify all Observers by calling their respective callback with the given data
  8209. * Will return true if all observers were executed, false if an observer set skipNextObservers to true, then prevent the subsequent ones to execute
  8210. * @param eventData defines the data to send to all observers
  8211. * @param mask defines the mask of the current notification (observers with incompatible mask (ie mask & observer.mask === 0) will not be notified)
  8212. * @param target defines the original target of the state
  8213. * @param currentTarget defines the current target of the state
  8214. * @returns false if the complete observer chain was not processed (because one observer set the skipNextObservers to true)
  8215. */
  8216. Observable.prototype.notifyObservers = function (eventData, mask, target, currentTarget) {
  8217. if (mask === void 0) { mask = -1; }
  8218. if (!this._observers.length) {
  8219. return true;
  8220. }
  8221. var state = this._eventState;
  8222. state.mask = mask;
  8223. state.target = target;
  8224. state.currentTarget = currentTarget;
  8225. state.skipNextObservers = false;
  8226. state.lastReturnValue = eventData;
  8227. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  8228. var obs = _a[_i];
  8229. if (obs._willBeUnregistered) {
  8230. continue;
  8231. }
  8232. if (obs.mask & mask) {
  8233. if (obs.scope) {
  8234. state.lastReturnValue = obs.callback.apply(obs.scope, [eventData, state]);
  8235. }
  8236. else {
  8237. state.lastReturnValue = obs.callback(eventData, state);
  8238. }
  8239. if (obs.unregisterOnNextCall) {
  8240. this._deferUnregister(obs);
  8241. }
  8242. }
  8243. if (state.skipNextObservers) {
  8244. return false;
  8245. }
  8246. }
  8247. return true;
  8248. };
  8249. /**
  8250. * Calling this will execute each callback, expecting it to be a promise or return a value.
  8251. * If at any point in the chain one function fails, the promise will fail and the execution will not continue.
  8252. * This is useful when a chain of events (sometimes async events) is needed to initialize a certain object
  8253. * and it is crucial that all callbacks will be executed.
  8254. * The order of the callbacks is kept, callbacks are not executed parallel.
  8255. *
  8256. * @param eventData The data to be sent to each callback
  8257. * @param mask is used to filter observers defaults to -1
  8258. * @param target defines the callback target (see EventState)
  8259. * @param currentTarget defines he current object in the bubbling phase
  8260. * @returns {Promise<T>} will return a Promise than resolves when all callbacks executed successfully.
  8261. */
  8262. Observable.prototype.notifyObserversWithPromise = function (eventData, mask, target, currentTarget) {
  8263. var _this = this;
  8264. if (mask === void 0) { mask = -1; }
  8265. // create an empty promise
  8266. var p = Promise.resolve(eventData);
  8267. // no observers? return this promise.
  8268. if (!this._observers.length) {
  8269. return p;
  8270. }
  8271. var state = this._eventState;
  8272. state.mask = mask;
  8273. state.target = target;
  8274. state.currentTarget = currentTarget;
  8275. state.skipNextObservers = false;
  8276. // execute one callback after another (not using Promise.all, the order is important)
  8277. this._observers.forEach(function (obs) {
  8278. if (state.skipNextObservers) {
  8279. return;
  8280. }
  8281. if (obs._willBeUnregistered) {
  8282. return;
  8283. }
  8284. if (obs.mask & mask) {
  8285. if (obs.scope) {
  8286. p = p.then(function (lastReturnedValue) {
  8287. state.lastReturnValue = lastReturnedValue;
  8288. return obs.callback.apply(obs.scope, [eventData, state]);
  8289. });
  8290. }
  8291. else {
  8292. p = p.then(function (lastReturnedValue) {
  8293. state.lastReturnValue = lastReturnedValue;
  8294. return obs.callback(eventData, state);
  8295. });
  8296. }
  8297. if (obs.unregisterOnNextCall) {
  8298. _this._deferUnregister(obs);
  8299. }
  8300. }
  8301. });
  8302. // return the eventData
  8303. return p.then(function () { return eventData; });
  8304. };
  8305. /**
  8306. * Notify a specific observer
  8307. * @param observer defines the observer to notify
  8308. * @param eventData defines the data to be sent to each callback
  8309. * @param mask is used to filter observers defaults to -1
  8310. */
  8311. Observable.prototype.notifyObserver = function (observer, eventData, mask) {
  8312. if (mask === void 0) { mask = -1; }
  8313. var state = this._eventState;
  8314. state.mask = mask;
  8315. state.skipNextObservers = false;
  8316. observer.callback(eventData, state);
  8317. };
  8318. /**
  8319. * Gets a boolean indicating if the observable has at least one observer
  8320. * @returns true is the Observable has at least one Observer registered
  8321. */
  8322. Observable.prototype.hasObservers = function () {
  8323. return this._observers.length > 0;
  8324. };
  8325. /**
  8326. * Clear the list of observers
  8327. */
  8328. Observable.prototype.clear = function () {
  8329. this._observers = new Array();
  8330. this._onObserverAdded = null;
  8331. };
  8332. /**
  8333. * Clone the current observable
  8334. * @returns a new observable
  8335. */
  8336. Observable.prototype.clone = function () {
  8337. var result = new Observable();
  8338. result._observers = this._observers.slice(0);
  8339. return result;
  8340. };
  8341. /**
  8342. * Does this observable handles observer registered with a given mask
  8343. * @param mask defines the mask to be tested
  8344. * @return whether or not one observer registered with the given mask is handeled
  8345. **/
  8346. Observable.prototype.hasSpecificMask = function (mask) {
  8347. if (mask === void 0) { mask = -1; }
  8348. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  8349. var obs = _a[_i];
  8350. if (obs.mask & mask || obs.mask === mask) {
  8351. return true;
  8352. }
  8353. }
  8354. return false;
  8355. };
  8356. return Observable;
  8357. }());
  8358. BABYLON.Observable = Observable;
  8359. })(BABYLON || (BABYLON = {}));
  8360. //# sourceMappingURL=babylon.observable.js.map
  8361. var BABYLON;
  8362. (function (BABYLON) {
  8363. var SmartArray = /** @class */ (function () {
  8364. function SmartArray(capacity) {
  8365. this.length = 0;
  8366. this.data = new Array(capacity);
  8367. this._id = SmartArray._GlobalId++;
  8368. }
  8369. SmartArray.prototype.push = function (value) {
  8370. this.data[this.length++] = value;
  8371. if (this.length > this.data.length) {
  8372. this.data.length *= 2;
  8373. }
  8374. };
  8375. SmartArray.prototype.forEach = function (func) {
  8376. for (var index = 0; index < this.length; index++) {
  8377. func(this.data[index]);
  8378. }
  8379. };
  8380. SmartArray.prototype.sort = function (compareFn) {
  8381. this.data.sort(compareFn);
  8382. };
  8383. SmartArray.prototype.reset = function () {
  8384. this.length = 0;
  8385. };
  8386. SmartArray.prototype.dispose = function () {
  8387. this.reset();
  8388. if (this.data) {
  8389. this.data.length = 0;
  8390. this.data = [];
  8391. }
  8392. };
  8393. SmartArray.prototype.concat = function (array) {
  8394. if (array.length === 0) {
  8395. return;
  8396. }
  8397. if (this.length + array.length > this.data.length) {
  8398. this.data.length = (this.length + array.length) * 2;
  8399. }
  8400. for (var index = 0; index < array.length; index++) {
  8401. this.data[this.length++] = (array.data || array)[index];
  8402. }
  8403. };
  8404. SmartArray.prototype.indexOf = function (value) {
  8405. var position = this.data.indexOf(value);
  8406. if (position >= this.length) {
  8407. return -1;
  8408. }
  8409. return position;
  8410. };
  8411. SmartArray.prototype.contains = function (value) {
  8412. return this.data.indexOf(value) !== -1;
  8413. };
  8414. // Statics
  8415. SmartArray._GlobalId = 0;
  8416. return SmartArray;
  8417. }());
  8418. BABYLON.SmartArray = SmartArray;
  8419. var SmartArrayNoDuplicate = /** @class */ (function (_super) {
  8420. __extends(SmartArrayNoDuplicate, _super);
  8421. function SmartArrayNoDuplicate() {
  8422. var _this = _super !== null && _super.apply(this, arguments) || this;
  8423. _this._duplicateId = 0;
  8424. return _this;
  8425. }
  8426. SmartArrayNoDuplicate.prototype.push = function (value) {
  8427. _super.prototype.push.call(this, value);
  8428. if (!value.__smartArrayFlags) {
  8429. value.__smartArrayFlags = {};
  8430. }
  8431. value.__smartArrayFlags[this._id] = this._duplicateId;
  8432. };
  8433. SmartArrayNoDuplicate.prototype.pushNoDuplicate = function (value) {
  8434. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  8435. return false;
  8436. }
  8437. this.push(value);
  8438. return true;
  8439. };
  8440. SmartArrayNoDuplicate.prototype.reset = function () {
  8441. _super.prototype.reset.call(this);
  8442. this._duplicateId++;
  8443. };
  8444. SmartArrayNoDuplicate.prototype.concatWithNoDuplicate = function (array) {
  8445. if (array.length === 0) {
  8446. return;
  8447. }
  8448. if (this.length + array.length > this.data.length) {
  8449. this.data.length = (this.length + array.length) * 2;
  8450. }
  8451. for (var index = 0; index < array.length; index++) {
  8452. var item = (array.data || array)[index];
  8453. this.pushNoDuplicate(item);
  8454. }
  8455. };
  8456. return SmartArrayNoDuplicate;
  8457. }(SmartArray));
  8458. BABYLON.SmartArrayNoDuplicate = SmartArrayNoDuplicate;
  8459. })(BABYLON || (BABYLON = {}));
  8460. //# sourceMappingURL=babylon.smartArray.js.map
  8461. var BABYLON;
  8462. (function (BABYLON) {
  8463. // See https://stackoverflow.com/questions/12915412/how-do-i-extend-a-host-object-e-g-error-in-typescript
  8464. // and https://github.com/Microsoft/TypeScript/wiki/Breaking-Changes#extending-built-ins-like-error-array-and-map-may-no-longer-work
  8465. var LoadFileError = /** @class */ (function (_super) {
  8466. __extends(LoadFileError, _super);
  8467. function LoadFileError(message, request) {
  8468. var _this = _super.call(this, message) || this;
  8469. _this.request = request;
  8470. _this.name = "LoadFileError";
  8471. LoadFileError._setPrototypeOf(_this, LoadFileError.prototype);
  8472. return _this;
  8473. }
  8474. // Polyfill for Object.setPrototypeOf if necessary.
  8475. LoadFileError._setPrototypeOf = Object.setPrototypeOf || (function (o, proto) { o.__proto__ = proto; return o; });
  8476. return LoadFileError;
  8477. }(Error));
  8478. BABYLON.LoadFileError = LoadFileError;
  8479. var RetryStrategy = /** @class */ (function () {
  8480. function RetryStrategy() {
  8481. }
  8482. RetryStrategy.ExponentialBackoff = function (maxRetries, baseInterval) {
  8483. if (maxRetries === void 0) { maxRetries = 3; }
  8484. if (baseInterval === void 0) { baseInterval = 500; }
  8485. return function (url, request, retryIndex) {
  8486. if (request.status !== 0 || retryIndex >= maxRetries || url.indexOf("file:") !== -1) {
  8487. return -1;
  8488. }
  8489. return Math.pow(2, retryIndex) * baseInterval;
  8490. };
  8491. };
  8492. return RetryStrategy;
  8493. }());
  8494. BABYLON.RetryStrategy = RetryStrategy;
  8495. // Screenshots
  8496. var screenshotCanvas;
  8497. var cloneValue = function (source, destinationObject) {
  8498. if (!source)
  8499. return null;
  8500. if (source instanceof BABYLON.Mesh) {
  8501. return null;
  8502. }
  8503. if (source instanceof BABYLON.SubMesh) {
  8504. return source.clone(destinationObject);
  8505. }
  8506. else if (source.clone) {
  8507. return source.clone();
  8508. }
  8509. return null;
  8510. };
  8511. var Tools = /** @class */ (function () {
  8512. function Tools() {
  8513. }
  8514. /**
  8515. * Interpolates between a and b via alpha
  8516. * @param a The lower value (returned when alpha = 0)
  8517. * @param b The upper value (returned when alpha = 1)
  8518. * @param alpha The interpolation-factor
  8519. * @return The mixed value
  8520. */
  8521. Tools.Mix = function (a, b, alpha) {
  8522. return a * (1 - alpha) + b * alpha;
  8523. };
  8524. Tools.Instantiate = function (className) {
  8525. if (Tools.RegisteredExternalClasses && Tools.RegisteredExternalClasses[className]) {
  8526. return Tools.RegisteredExternalClasses[className];
  8527. }
  8528. var arr = className.split(".");
  8529. var fn = (window || this);
  8530. for (var i = 0, len = arr.length; i < len; i++) {
  8531. fn = fn[arr[i]];
  8532. }
  8533. if (typeof fn !== "function") {
  8534. return null;
  8535. }
  8536. return fn;
  8537. };
  8538. /**
  8539. * Provides a slice function that will work even on IE
  8540. * @param data defines the array to slice
  8541. * @param start defines the start of the data (optional)
  8542. * @param end defines the end of the data (optional)
  8543. * @returns the new sliced array
  8544. */
  8545. Tools.Slice = function (data, start, end) {
  8546. if (data.slice) {
  8547. return data.slice(start, end);
  8548. }
  8549. return Array.prototype.slice.call(data, start, end);
  8550. };
  8551. Tools.SetImmediate = function (action) {
  8552. if (window.setImmediate) {
  8553. window.setImmediate(action);
  8554. }
  8555. else {
  8556. setTimeout(action, 1);
  8557. }
  8558. };
  8559. Tools.IsExponentOfTwo = function (value) {
  8560. var count = 1;
  8561. do {
  8562. count *= 2;
  8563. } while (count < value);
  8564. return count === value;
  8565. };
  8566. /**
  8567. * Returns the nearest 32-bit single precision float representation of a Number
  8568. * @param value A Number. If the parameter is of a different type, it will get converted
  8569. * to a number or to NaN if it cannot be converted
  8570. * @returns number
  8571. */
  8572. Tools.FloatRound = function (value) {
  8573. if (Math.fround) {
  8574. return Math.fround(value);
  8575. }
  8576. return (Tools._tmpFloatArray[0] = value);
  8577. };
  8578. /**
  8579. * Find the next highest power of two.
  8580. * @param x Number to start search from.
  8581. * @return Next highest power of two.
  8582. */
  8583. Tools.CeilingPOT = function (x) {
  8584. x--;
  8585. x |= x >> 1;
  8586. x |= x >> 2;
  8587. x |= x >> 4;
  8588. x |= x >> 8;
  8589. x |= x >> 16;
  8590. x++;
  8591. return x;
  8592. };
  8593. /**
  8594. * Find the next lowest power of two.
  8595. * @param x Number to start search from.
  8596. * @return Next lowest power of two.
  8597. */
  8598. Tools.FloorPOT = function (x) {
  8599. x = x | (x >> 1);
  8600. x = x | (x >> 2);
  8601. x = x | (x >> 4);
  8602. x = x | (x >> 8);
  8603. x = x | (x >> 16);
  8604. return x - (x >> 1);
  8605. };
  8606. /**
  8607. * Find the nearest power of two.
  8608. * @param x Number to start search from.
  8609. * @return Next nearest power of two.
  8610. */
  8611. Tools.NearestPOT = function (x) {
  8612. var c = Tools.CeilingPOT(x);
  8613. var f = Tools.FloorPOT(x);
  8614. return (c - x) > (x - f) ? f : c;
  8615. };
  8616. Tools.GetExponentOfTwo = function (value, max, mode) {
  8617. if (mode === void 0) { mode = BABYLON.Engine.SCALEMODE_NEAREST; }
  8618. var pot;
  8619. switch (mode) {
  8620. case BABYLON.Engine.SCALEMODE_FLOOR:
  8621. pot = Tools.FloorPOT(value);
  8622. break;
  8623. case BABYLON.Engine.SCALEMODE_NEAREST:
  8624. pot = Tools.NearestPOT(value);
  8625. break;
  8626. case BABYLON.Engine.SCALEMODE_CEILING:
  8627. default:
  8628. pot = Tools.CeilingPOT(value);
  8629. break;
  8630. }
  8631. return Math.min(pot, max);
  8632. };
  8633. Tools.GetFilename = function (path) {
  8634. var index = path.lastIndexOf("/");
  8635. if (index < 0)
  8636. return path;
  8637. return path.substring(index + 1);
  8638. };
  8639. /**
  8640. * Extracts the "folder" part of a path (everything before the filename).
  8641. * @param uri The URI to extract the info from
  8642. * @param returnUnchangedIfNoSlash Do not touch the URI if no slashes are present
  8643. * @returns The "folder" part of the path
  8644. */
  8645. Tools.GetFolderPath = function (uri, returnUnchangedIfNoSlash) {
  8646. if (returnUnchangedIfNoSlash === void 0) { returnUnchangedIfNoSlash = false; }
  8647. var index = uri.lastIndexOf("/");
  8648. if (index < 0) {
  8649. if (returnUnchangedIfNoSlash) {
  8650. return uri;
  8651. }
  8652. return "";
  8653. }
  8654. return uri.substring(0, index + 1);
  8655. };
  8656. Tools.GetDOMTextContent = function (element) {
  8657. var result = "";
  8658. var child = element.firstChild;
  8659. while (child) {
  8660. if (child.nodeType === 3) {
  8661. result += child.textContent;
  8662. }
  8663. child = child.nextSibling;
  8664. }
  8665. return result;
  8666. };
  8667. Tools.ToDegrees = function (angle) {
  8668. return angle * 180 / Math.PI;
  8669. };
  8670. Tools.ToRadians = function (angle) {
  8671. return angle * Math.PI / 180;
  8672. };
  8673. Tools.EncodeArrayBufferTobase64 = function (buffer) {
  8674. var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  8675. var output = "";
  8676. var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
  8677. var i = 0;
  8678. var bytes = new Uint8Array(buffer);
  8679. while (i < bytes.length) {
  8680. chr1 = bytes[i++];
  8681. chr2 = i < bytes.length ? bytes[i++] : Number.NaN; // Not sure if the index
  8682. chr3 = i < bytes.length ? bytes[i++] : Number.NaN; // checks are needed here
  8683. enc1 = chr1 >> 2;
  8684. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  8685. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  8686. enc4 = chr3 & 63;
  8687. if (isNaN(chr2)) {
  8688. enc3 = enc4 = 64;
  8689. }
  8690. else if (isNaN(chr3)) {
  8691. enc4 = 64;
  8692. }
  8693. output += keyStr.charAt(enc1) + keyStr.charAt(enc2) +
  8694. keyStr.charAt(enc3) + keyStr.charAt(enc4);
  8695. }
  8696. return "data:image/png;base64," + output;
  8697. };
  8698. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount, bias) {
  8699. if (bias === void 0) { bias = null; }
  8700. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  8701. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  8702. for (var index = indexStart; index < indexStart + indexCount; index++) {
  8703. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  8704. minimum = BABYLON.Vector3.Minimize(current, minimum);
  8705. maximum = BABYLON.Vector3.Maximize(current, maximum);
  8706. }
  8707. if (bias) {
  8708. minimum.x -= minimum.x * bias.x + bias.y;
  8709. minimum.y -= minimum.y * bias.x + bias.y;
  8710. minimum.z -= minimum.z * bias.x + bias.y;
  8711. maximum.x += maximum.x * bias.x + bias.y;
  8712. maximum.y += maximum.y * bias.x + bias.y;
  8713. maximum.z += maximum.z * bias.x + bias.y;
  8714. }
  8715. return {
  8716. minimum: minimum,
  8717. maximum: maximum
  8718. };
  8719. };
  8720. Tools.ExtractMinAndMax = function (positions, start, count, bias, stride) {
  8721. if (bias === void 0) { bias = null; }
  8722. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  8723. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  8724. if (!stride) {
  8725. stride = 3;
  8726. }
  8727. for (var index = start; index < start + count; index++) {
  8728. var current = new BABYLON.Vector3(positions[index * stride], positions[index * stride + 1], positions[index * stride + 2]);
  8729. minimum = BABYLON.Vector3.Minimize(current, minimum);
  8730. maximum = BABYLON.Vector3.Maximize(current, maximum);
  8731. }
  8732. if (bias) {
  8733. minimum.x -= minimum.x * bias.x + bias.y;
  8734. minimum.y -= minimum.y * bias.x + bias.y;
  8735. minimum.z -= minimum.z * bias.x + bias.y;
  8736. maximum.x += maximum.x * bias.x + bias.y;
  8737. maximum.y += maximum.y * bias.x + bias.y;
  8738. maximum.z += maximum.z * bias.x + bias.y;
  8739. }
  8740. return {
  8741. minimum: minimum,
  8742. maximum: maximum
  8743. };
  8744. };
  8745. Tools.Vector2ArrayFeeder = function (array) {
  8746. return function (index) {
  8747. var isFloatArray = (array.BYTES_PER_ELEMENT !== undefined);
  8748. var length = isFloatArray ? array.length / 2 : array.length;
  8749. if (index >= length) {
  8750. return null;
  8751. }
  8752. if (isFloatArray) {
  8753. var fa = array;
  8754. return new BABYLON.Vector2(fa[index * 2 + 0], fa[index * 2 + 1]);
  8755. }
  8756. var a = array;
  8757. return a[index];
  8758. };
  8759. };
  8760. Tools.ExtractMinAndMaxVector2 = function (feeder, bias) {
  8761. if (bias === void 0) { bias = null; }
  8762. var minimum = new BABYLON.Vector2(Number.MAX_VALUE, Number.MAX_VALUE);
  8763. var maximum = new BABYLON.Vector2(-Number.MAX_VALUE, -Number.MAX_VALUE);
  8764. var i = 0;
  8765. var cur = feeder(i++);
  8766. while (cur) {
  8767. minimum = BABYLON.Vector2.Minimize(cur, minimum);
  8768. maximum = BABYLON.Vector2.Maximize(cur, maximum);
  8769. cur = feeder(i++);
  8770. }
  8771. if (bias) {
  8772. minimum.x -= minimum.x * bias.x + bias.y;
  8773. minimum.y -= minimum.y * bias.x + bias.y;
  8774. maximum.x += maximum.x * bias.x + bias.y;
  8775. maximum.y += maximum.y * bias.x + bias.y;
  8776. }
  8777. return {
  8778. minimum: minimum,
  8779. maximum: maximum
  8780. };
  8781. };
  8782. Tools.MakeArray = function (obj, allowsNullUndefined) {
  8783. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  8784. return null;
  8785. return Array.isArray(obj) ? obj : [obj];
  8786. };
  8787. // Misc.
  8788. Tools.GetPointerPrefix = function () {
  8789. var eventPrefix = "pointer";
  8790. // Check if pointer events are supported
  8791. if (Tools.IsWindowObjectExist() && !window.PointerEvent && !navigator.pointerEnabled) {
  8792. eventPrefix = "mouse";
  8793. }
  8794. return eventPrefix;
  8795. };
  8796. /**
  8797. * @param func - the function to be called
  8798. * @param requester - the object that will request the next frame. Falls back to window.
  8799. */
  8800. Tools.QueueNewFrame = function (func, requester) {
  8801. if (!Tools.IsWindowObjectExist()) {
  8802. return setTimeout(func, 16);
  8803. }
  8804. if (!requester) {
  8805. requester = window;
  8806. }
  8807. if (requester.requestAnimationFrame) {
  8808. return requester.requestAnimationFrame(func);
  8809. }
  8810. else if (requester.msRequestAnimationFrame) {
  8811. return requester.msRequestAnimationFrame(func);
  8812. }
  8813. else if (requester.webkitRequestAnimationFrame) {
  8814. return requester.webkitRequestAnimationFrame(func);
  8815. }
  8816. else if (requester.mozRequestAnimationFrame) {
  8817. return requester.mozRequestAnimationFrame(func);
  8818. }
  8819. else if (requester.oRequestAnimationFrame) {
  8820. return requester.oRequestAnimationFrame(func);
  8821. }
  8822. else {
  8823. return window.setTimeout(func, 16);
  8824. }
  8825. };
  8826. Tools.RequestFullscreen = function (element) {
  8827. var requestFunction = element.requestFullscreen || element.msRequestFullscreen || element.webkitRequestFullscreen || element.mozRequestFullScreen;
  8828. if (!requestFunction)
  8829. return;
  8830. requestFunction.call(element);
  8831. };
  8832. Tools.ExitFullscreen = function () {
  8833. if (document.exitFullscreen) {
  8834. document.exitFullscreen();
  8835. }
  8836. else if (document.mozCancelFullScreen) {
  8837. document.mozCancelFullScreen();
  8838. }
  8839. else if (document.webkitCancelFullScreen) {
  8840. document.webkitCancelFullScreen();
  8841. }
  8842. else if (document.msCancelFullScreen) {
  8843. document.msCancelFullScreen();
  8844. }
  8845. };
  8846. Tools.SetCorsBehavior = function (url, element) {
  8847. if (url && url.indexOf("data:") === 0) {
  8848. return;
  8849. }
  8850. if (Tools.CorsBehavior) {
  8851. if (typeof (Tools.CorsBehavior) === 'string' || Tools.CorsBehavior instanceof String) {
  8852. element.crossOrigin = Tools.CorsBehavior;
  8853. }
  8854. else {
  8855. var result = Tools.CorsBehavior(url);
  8856. if (result) {
  8857. element.crossOrigin = result;
  8858. }
  8859. }
  8860. }
  8861. };
  8862. // External files
  8863. Tools.CleanUrl = function (url) {
  8864. url = url.replace(/#/mg, "%23");
  8865. return url;
  8866. };
  8867. /**
  8868. * Loads an image as an HTMLImageElement.
  8869. * @param input url string, ArrayBuffer, or Blob to load
  8870. * @param onLoad callback called when the image successfully loads
  8871. * @param onError callback called when the image fails to load
  8872. * @param database database for caching
  8873. * @returns the HTMLImageElement of the loaded image
  8874. */
  8875. Tools.LoadImage = function (input, onLoad, onError, database) {
  8876. var url;
  8877. var usingObjectURL = false;
  8878. if (input instanceof ArrayBuffer) {
  8879. url = URL.createObjectURL(new Blob([input]));
  8880. usingObjectURL = true;
  8881. }
  8882. else if (input instanceof Blob) {
  8883. url = URL.createObjectURL(input);
  8884. usingObjectURL = true;
  8885. }
  8886. else {
  8887. url = Tools.CleanUrl(input);
  8888. url = Tools.PreprocessUrl(input);
  8889. }
  8890. var img = new Image();
  8891. Tools.SetCorsBehavior(url, img);
  8892. var loadHandler = function () {
  8893. if (usingObjectURL && img.src) {
  8894. URL.revokeObjectURL(img.src);
  8895. }
  8896. img.removeEventListener("load", loadHandler);
  8897. img.removeEventListener("error", errorHandler);
  8898. onLoad(img);
  8899. };
  8900. var errorHandler = function (err) {
  8901. if (usingObjectURL && img.src) {
  8902. URL.revokeObjectURL(img.src);
  8903. }
  8904. img.removeEventListener("load", loadHandler);
  8905. img.removeEventListener("error", errorHandler);
  8906. Tools.Error("Error while trying to load image: " + input);
  8907. if (onError) {
  8908. onError("Error while trying to load image: " + input, err);
  8909. }
  8910. };
  8911. img.addEventListener("load", loadHandler);
  8912. img.addEventListener("error", errorHandler);
  8913. var noIndexedDB = function () {
  8914. img.src = url;
  8915. };
  8916. var loadFromIndexedDB = function () {
  8917. if (database) {
  8918. database.loadImageFromDB(url, img);
  8919. }
  8920. };
  8921. //ANY database to do!
  8922. if (url.substr(0, 5) !== "data:" && database && database.enableTexturesOffline && BABYLON.Database.IsUASupportingBlobStorage) {
  8923. database.openAsync(loadFromIndexedDB, noIndexedDB);
  8924. }
  8925. else {
  8926. if (url.indexOf("file:") !== -1) {
  8927. var textureName = decodeURIComponent(url.substring(5).toLowerCase());
  8928. if (BABYLON.FilesInput.FilesToLoad[textureName]) {
  8929. try {
  8930. var blobURL;
  8931. try {
  8932. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName], { oneTimeOnly: true });
  8933. }
  8934. catch (ex) {
  8935. // Chrome doesn't support oneTimeOnly parameter
  8936. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName]);
  8937. }
  8938. img.src = blobURL;
  8939. usingObjectURL = true;
  8940. }
  8941. catch (e) {
  8942. img.src = "";
  8943. }
  8944. return img;
  8945. }
  8946. }
  8947. noIndexedDB();
  8948. }
  8949. return img;
  8950. };
  8951. Tools.LoadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  8952. url = Tools.CleanUrl(url);
  8953. url = Tools.PreprocessUrl(url);
  8954. // If file and file input are set
  8955. if (url.indexOf("file:") !== -1) {
  8956. var fileName = decodeURIComponent(url.substring(5).toLowerCase());
  8957. if (BABYLON.FilesInput.FilesToLoad[fileName]) {
  8958. return Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], onSuccess, onProgress, useArrayBuffer);
  8959. }
  8960. }
  8961. var loadUrl = Tools.BaseUrl + url;
  8962. var aborted = false;
  8963. var fileRequest = {
  8964. onCompleteObservable: new BABYLON.Observable(),
  8965. abort: function () { return aborted = true; },
  8966. };
  8967. var requestFile = function () {
  8968. var request = new XMLHttpRequest();
  8969. var retryHandle = null;
  8970. fileRequest.abort = function () {
  8971. aborted = true;
  8972. if (request.readyState !== (XMLHttpRequest.DONE || 4)) {
  8973. request.abort();
  8974. }
  8975. if (retryHandle !== null) {
  8976. clearTimeout(retryHandle);
  8977. retryHandle = null;
  8978. }
  8979. };
  8980. var retryLoop = function (retryIndex) {
  8981. request.open('GET', loadUrl, true);
  8982. if (useArrayBuffer) {
  8983. request.responseType = "arraybuffer";
  8984. }
  8985. if (onProgress) {
  8986. request.addEventListener("progress", onProgress);
  8987. }
  8988. var onLoadEnd = function () {
  8989. request.removeEventListener("loadend", onLoadEnd);
  8990. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  8991. fileRequest.onCompleteObservable.clear();
  8992. };
  8993. request.addEventListener("loadend", onLoadEnd);
  8994. var onReadyStateChange = function () {
  8995. if (aborted) {
  8996. return;
  8997. }
  8998. // In case of undefined state in some browsers.
  8999. if (request.readyState === (XMLHttpRequest.DONE || 4)) {
  9000. // Some browsers have issues where onreadystatechange can be called multiple times with the same value.
  9001. request.removeEventListener("readystatechange", onReadyStateChange);
  9002. if (request.status >= 200 && request.status < 300 || (!Tools.IsWindowObjectExist() && (request.status === 0))) {
  9003. onSuccess(!useArrayBuffer ? request.responseText : request.response, request.responseURL);
  9004. return;
  9005. }
  9006. var retryStrategy = Tools.DefaultRetryStrategy;
  9007. if (retryStrategy) {
  9008. var waitTime = retryStrategy(loadUrl, request, retryIndex);
  9009. if (waitTime !== -1) {
  9010. // Prevent the request from completing for retry.
  9011. request.removeEventListener("loadend", onLoadEnd);
  9012. request = new XMLHttpRequest();
  9013. retryHandle = setTimeout(function () { return retryLoop(retryIndex + 1); }, waitTime);
  9014. return;
  9015. }
  9016. }
  9017. var e = new LoadFileError("Error status: " + request.status + " " + request.statusText + " - Unable to load " + loadUrl, request);
  9018. if (onError) {
  9019. onError(request, e);
  9020. }
  9021. else {
  9022. throw e;
  9023. }
  9024. }
  9025. };
  9026. request.addEventListener("readystatechange", onReadyStateChange);
  9027. request.send();
  9028. };
  9029. retryLoop(0);
  9030. };
  9031. // Caching all files
  9032. if (database && database.enableSceneOffline) {
  9033. var noIndexedDB_1 = function () {
  9034. if (!aborted) {
  9035. requestFile();
  9036. }
  9037. };
  9038. var loadFromIndexedDB = function () {
  9039. // TODO: database needs to support aborting and should return a IFileRequest
  9040. if (aborted) {
  9041. return;
  9042. }
  9043. if (database) {
  9044. database.loadFileFromDB(url, function (data) {
  9045. if (!aborted) {
  9046. onSuccess(data);
  9047. }
  9048. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  9049. }, onProgress ? function (event) {
  9050. if (!aborted) {
  9051. onProgress(event);
  9052. }
  9053. } : undefined, noIndexedDB_1, useArrayBuffer);
  9054. }
  9055. };
  9056. database.openAsync(loadFromIndexedDB, noIndexedDB_1);
  9057. }
  9058. else {
  9059. requestFile();
  9060. }
  9061. return fileRequest;
  9062. };
  9063. /**
  9064. * Load a script (identified by an url). When the url returns, the
  9065. * content of this file is added into a new script element, attached to the DOM (body element)
  9066. */
  9067. Tools.LoadScript = function (scriptUrl, onSuccess, onError) {
  9068. var head = document.getElementsByTagName('head')[0];
  9069. var script = document.createElement('script');
  9070. script.type = 'text/javascript';
  9071. script.src = scriptUrl;
  9072. script.onload = function () {
  9073. if (onSuccess) {
  9074. onSuccess();
  9075. }
  9076. };
  9077. script.onerror = function (e) {
  9078. if (onError) {
  9079. onError("Unable to load script '" + scriptUrl + "'", e);
  9080. }
  9081. };
  9082. head.appendChild(script);
  9083. };
  9084. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  9085. var reader = new FileReader();
  9086. var request = {
  9087. onCompleteObservable: new BABYLON.Observable(),
  9088. abort: function () { return reader.abort(); },
  9089. };
  9090. reader.onloadend = function (e) {
  9091. request.onCompleteObservable.notifyObservers(request);
  9092. };
  9093. reader.onload = function (e) {
  9094. //target doesn't have result from ts 1.3
  9095. callback(e.target['result']);
  9096. };
  9097. reader.onprogress = progressCallback;
  9098. reader.readAsDataURL(fileToLoad);
  9099. return request;
  9100. };
  9101. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  9102. var reader = new FileReader();
  9103. var request = {
  9104. onCompleteObservable: new BABYLON.Observable(),
  9105. abort: function () { return reader.abort(); },
  9106. };
  9107. reader.onloadend = function (e) { return request.onCompleteObservable.notifyObservers(request); };
  9108. reader.onerror = function (e) {
  9109. Tools.Log("Error while reading file: " + fileToLoad.name);
  9110. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.807, 0], meshes: [], cameras: [], lights: [] }));
  9111. };
  9112. reader.onload = function (e) {
  9113. //target doesn't have result from ts 1.3
  9114. callback(e.target['result']);
  9115. };
  9116. if (progressCallBack) {
  9117. reader.onprogress = progressCallBack;
  9118. }
  9119. if (!useArrayBuffer) {
  9120. // Asynchronous read
  9121. reader.readAsText(fileToLoad);
  9122. }
  9123. else {
  9124. reader.readAsArrayBuffer(fileToLoad);
  9125. }
  9126. return request;
  9127. };
  9128. //returns a downloadable url to a file content.
  9129. Tools.FileAsURL = function (content) {
  9130. var fileBlob = new Blob([content]);
  9131. var url = window.URL || window.webkitURL;
  9132. var link = url.createObjectURL(fileBlob);
  9133. return link;
  9134. };
  9135. // Misc.
  9136. Tools.Format = function (value, decimals) {
  9137. if (decimals === void 0) { decimals = 2; }
  9138. return value.toFixed(decimals);
  9139. };
  9140. Tools.CheckExtends = function (v, min, max) {
  9141. if (v.x < min.x)
  9142. min.x = v.x;
  9143. if (v.y < min.y)
  9144. min.y = v.y;
  9145. if (v.z < min.z)
  9146. min.z = v.z;
  9147. if (v.x > max.x)
  9148. max.x = v.x;
  9149. if (v.y > max.y)
  9150. max.y = v.y;
  9151. if (v.z > max.z)
  9152. max.z = v.z;
  9153. };
  9154. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  9155. for (var prop in source) {
  9156. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  9157. continue;
  9158. }
  9159. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  9160. continue;
  9161. }
  9162. var sourceValue = source[prop];
  9163. var typeOfSourceValue = typeof sourceValue;
  9164. if (typeOfSourceValue === "function") {
  9165. continue;
  9166. }
  9167. try {
  9168. if (typeOfSourceValue === "object") {
  9169. if (sourceValue instanceof Array) {
  9170. destination[prop] = [];
  9171. if (sourceValue.length > 0) {
  9172. if (typeof sourceValue[0] == "object") {
  9173. for (var index = 0; index < sourceValue.length; index++) {
  9174. var clonedValue = cloneValue(sourceValue[index], destination);
  9175. if (destination[prop].indexOf(clonedValue) === -1) { // Test if auto inject was not done
  9176. destination[prop].push(clonedValue);
  9177. }
  9178. }
  9179. }
  9180. else {
  9181. destination[prop] = sourceValue.slice(0);
  9182. }
  9183. }
  9184. }
  9185. else {
  9186. destination[prop] = cloneValue(sourceValue, destination);
  9187. }
  9188. }
  9189. else {
  9190. destination[prop] = sourceValue;
  9191. }
  9192. }
  9193. catch (e) {
  9194. // Just ignore error (it could be because of a read-only property)
  9195. }
  9196. }
  9197. };
  9198. Tools.IsEmpty = function (obj) {
  9199. for (var i in obj) {
  9200. if (obj.hasOwnProperty(i)) {
  9201. return false;
  9202. }
  9203. }
  9204. return true;
  9205. };
  9206. Tools.RegisterTopRootEvents = function (events) {
  9207. for (var index = 0; index < events.length; index++) {
  9208. var event = events[index];
  9209. window.addEventListener(event.name, event.handler, false);
  9210. try {
  9211. if (window.parent) {
  9212. window.parent.addEventListener(event.name, event.handler, false);
  9213. }
  9214. }
  9215. catch (e) {
  9216. // Silently fails...
  9217. }
  9218. }
  9219. };
  9220. Tools.UnregisterTopRootEvents = function (events) {
  9221. for (var index = 0; index < events.length; index++) {
  9222. var event = events[index];
  9223. window.removeEventListener(event.name, event.handler);
  9224. try {
  9225. if (window.parent) {
  9226. window.parent.removeEventListener(event.name, event.handler);
  9227. }
  9228. }
  9229. catch (e) {
  9230. // Silently fails...
  9231. }
  9232. }
  9233. };
  9234. Tools.DumpFramebuffer = function (width, height, engine, successCallback, mimeType, fileName) {
  9235. if (mimeType === void 0) { mimeType = "image/png"; }
  9236. // Read the contents of the framebuffer
  9237. var numberOfChannelsByLine = width * 4;
  9238. var halfHeight = height / 2;
  9239. //Reading datas from WebGL
  9240. var data = engine.readPixels(0, 0, width, height);
  9241. //To flip image on Y axis.
  9242. for (var i = 0; i < halfHeight; i++) {
  9243. for (var j = 0; j < numberOfChannelsByLine; j++) {
  9244. var currentCell = j + i * numberOfChannelsByLine;
  9245. var targetLine = height - i - 1;
  9246. var targetCell = j + targetLine * numberOfChannelsByLine;
  9247. var temp = data[currentCell];
  9248. data[currentCell] = data[targetCell];
  9249. data[targetCell] = temp;
  9250. }
  9251. }
  9252. // Create a 2D canvas to store the result
  9253. if (!screenshotCanvas) {
  9254. screenshotCanvas = document.createElement('canvas');
  9255. }
  9256. screenshotCanvas.width = width;
  9257. screenshotCanvas.height = height;
  9258. var context = screenshotCanvas.getContext('2d');
  9259. if (context) {
  9260. // Copy the pixels to a 2D canvas
  9261. var imageData = context.createImageData(width, height);
  9262. var castData = (imageData.data);
  9263. castData.set(data);
  9264. context.putImageData(imageData, 0, 0);
  9265. Tools.EncodeScreenshotCanvasData(successCallback, mimeType, fileName);
  9266. }
  9267. };
  9268. Tools.EncodeScreenshotCanvasData = function (successCallback, mimeType, fileName) {
  9269. if (mimeType === void 0) { mimeType = "image/png"; }
  9270. var base64Image = screenshotCanvas.toDataURL(mimeType);
  9271. if (successCallback) {
  9272. successCallback(base64Image);
  9273. }
  9274. else {
  9275. // We need HTMLCanvasElement.toBlob for HD screenshots
  9276. if (!screenshotCanvas.toBlob) {
  9277. // low performance polyfill based on toDataURL (https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toBlob)
  9278. screenshotCanvas.toBlob = function (callback, type, quality) {
  9279. var _this = this;
  9280. setTimeout(function () {
  9281. var binStr = atob(_this.toDataURL(type, quality).split(',')[1]), len = binStr.length, arr = new Uint8Array(len);
  9282. for (var i = 0; i < len; i++) {
  9283. arr[i] = binStr.charCodeAt(i);
  9284. }
  9285. callback(new Blob([arr], { type: type || 'image/png' }));
  9286. });
  9287. };
  9288. }
  9289. screenshotCanvas.toBlob(function (blob) {
  9290. var url = URL.createObjectURL(blob);
  9291. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  9292. if (("download" in document.createElement("a"))) {
  9293. var a = window.document.createElement("a");
  9294. a.href = url;
  9295. if (fileName) {
  9296. a.setAttribute("download", fileName);
  9297. }
  9298. else {
  9299. var date = new Date();
  9300. var stringDate = (date.getFullYear() + "-" + (date.getMonth() + 1)).slice(-2) + "-" + date.getDate() + "_" + date.getHours() + "-" + ('0' + date.getMinutes()).slice(-2);
  9301. a.setAttribute("download", "screenshot_" + stringDate + ".png");
  9302. }
  9303. window.document.body.appendChild(a);
  9304. a.addEventListener("click", function () {
  9305. if (a.parentElement) {
  9306. a.parentElement.removeChild(a);
  9307. }
  9308. });
  9309. a.click();
  9310. }
  9311. else {
  9312. var newWindow = window.open("");
  9313. if (!newWindow)
  9314. return;
  9315. var img = newWindow.document.createElement("img");
  9316. img.onload = function () {
  9317. // no longer need to read the blob so it's revoked
  9318. URL.revokeObjectURL(url);
  9319. };
  9320. img.src = url;
  9321. newWindow.document.body.appendChild(img);
  9322. }
  9323. });
  9324. }
  9325. };
  9326. Tools.CreateScreenshot = function (engine, camera, size, successCallback, mimeType) {
  9327. if (mimeType === void 0) { mimeType = "image/png"; }
  9328. var width;
  9329. var height;
  9330. // If a precision value is specified
  9331. if (size.precision) {
  9332. width = Math.round(engine.getRenderWidth() * size.precision);
  9333. height = Math.round(width / engine.getAspectRatio(camera));
  9334. }
  9335. else if (size.width && size.height) {
  9336. width = size.width;
  9337. height = size.height;
  9338. }
  9339. //If passing only width, computing height to keep display canvas ratio.
  9340. else if (size.width && !size.height) {
  9341. width = size.width;
  9342. height = Math.round(width / engine.getAspectRatio(camera));
  9343. }
  9344. //If passing only height, computing width to keep display canvas ratio.
  9345. else if (size.height && !size.width) {
  9346. height = size.height;
  9347. width = Math.round(height * engine.getAspectRatio(camera));
  9348. }
  9349. //Assuming here that "size" parameter is a number
  9350. else if (!isNaN(size)) {
  9351. height = size;
  9352. width = size;
  9353. }
  9354. else {
  9355. Tools.Error("Invalid 'size' parameter !");
  9356. return;
  9357. }
  9358. if (!screenshotCanvas) {
  9359. screenshotCanvas = document.createElement('canvas');
  9360. }
  9361. screenshotCanvas.width = width;
  9362. screenshotCanvas.height = height;
  9363. var renderContext = screenshotCanvas.getContext("2d");
  9364. var ratio = engine.getRenderWidth() / engine.getRenderHeight();
  9365. var newWidth = width;
  9366. var newHeight = newWidth / ratio;
  9367. if (newHeight > height) {
  9368. newHeight = height;
  9369. newWidth = newHeight * ratio;
  9370. }
  9371. var offsetX = Math.max(0, width - newWidth) / 2;
  9372. var offsetY = Math.max(0, height - newHeight) / 2;
  9373. var renderingCanvas = engine.getRenderingCanvas();
  9374. if (renderContext && renderingCanvas) {
  9375. renderContext.drawImage(renderingCanvas, offsetX, offsetY, newWidth, newHeight);
  9376. }
  9377. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  9378. };
  9379. /**
  9380. * Generates an image screenshot from the specified camera.
  9381. *
  9382. * @param engine The engine to use for rendering
  9383. * @param camera The camera to use for rendering
  9384. * @param size This parameter can be set to a single number or to an object with the
  9385. * following (optional) properties: precision, width, height. If a single number is passed,
  9386. * it will be used for both width and height. If an object is passed, the screenshot size
  9387. * will be derived from the parameters. The precision property is a multiplier allowing
  9388. * rendering at a higher or lower resolution.
  9389. * @param successCallback The callback receives a single parameter which contains the
  9390. * screenshot as a string of base64-encoded characters. This string can be assigned to the
  9391. * src parameter of an <img> to display it.
  9392. * @param mimeType The MIME type of the screenshot image (default: image/png).
  9393. * Check your browser for supported MIME types.
  9394. * @param samples Texture samples (default: 1)
  9395. * @param antialiasing Whether antialiasing should be turned on or not (default: false)
  9396. * @param fileName A name for for the downloaded file.
  9397. * @constructor
  9398. */
  9399. Tools.CreateScreenshotUsingRenderTarget = function (engine, camera, size, successCallback, mimeType, samples, antialiasing, fileName) {
  9400. if (mimeType === void 0) { mimeType = "image/png"; }
  9401. if (samples === void 0) { samples = 1; }
  9402. if (antialiasing === void 0) { antialiasing = false; }
  9403. var width;
  9404. var height;
  9405. //If a precision value is specified
  9406. if (size.precision) {
  9407. width = Math.round(engine.getRenderWidth() * size.precision);
  9408. height = Math.round(width / engine.getAspectRatio(camera));
  9409. size = { width: width, height: height };
  9410. }
  9411. else if (size.width && size.height) {
  9412. width = size.width;
  9413. height = size.height;
  9414. }
  9415. //If passing only width, computing height to keep display canvas ratio.
  9416. else if (size.width && !size.height) {
  9417. width = size.width;
  9418. height = Math.round(width / engine.getAspectRatio(camera));
  9419. size = { width: width, height: height };
  9420. }
  9421. //If passing only height, computing width to keep display canvas ratio.
  9422. else if (size.height && !size.width) {
  9423. height = size.height;
  9424. width = Math.round(height * engine.getAspectRatio(camera));
  9425. size = { width: width, height: height };
  9426. }
  9427. //Assuming here that "size" parameter is a number
  9428. else if (!isNaN(size)) {
  9429. height = size;
  9430. width = size;
  9431. }
  9432. else {
  9433. Tools.Error("Invalid 'size' parameter !");
  9434. return;
  9435. }
  9436. var scene = camera.getScene();
  9437. var previousCamera = null;
  9438. if (scene.activeCamera !== camera) {
  9439. previousCamera = scene.activeCamera;
  9440. scene.activeCamera = camera;
  9441. }
  9442. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  9443. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  9444. texture.renderList = null;
  9445. texture.samples = samples;
  9446. if (antialiasing) {
  9447. texture.addPostProcess(new BABYLON.FxaaPostProcess('antialiasing', 1.0, scene.activeCamera));
  9448. }
  9449. texture.onAfterRenderObservable.add(function () {
  9450. Tools.DumpFramebuffer(width, height, engine, successCallback, mimeType, fileName);
  9451. });
  9452. scene.incrementRenderId();
  9453. scene.resetCachedMaterial();
  9454. texture.render(true);
  9455. texture.dispose();
  9456. if (previousCamera) {
  9457. scene.activeCamera = previousCamera;
  9458. }
  9459. camera.getProjectionMatrix(true); // Force cache refresh;
  9460. };
  9461. // XHR response validator for local file scenario
  9462. Tools.ValidateXHRData = function (xhr, dataType) {
  9463. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  9464. if (dataType === void 0) { dataType = 7; }
  9465. try {
  9466. if (dataType & 1) {
  9467. if (xhr.responseText && xhr.responseText.length > 0) {
  9468. return true;
  9469. }
  9470. else if (dataType === 1) {
  9471. return false;
  9472. }
  9473. }
  9474. if (dataType & 2) {
  9475. // Check header width and height since there is no "TGA" magic number
  9476. var tgaHeader = BABYLON.TGATools.GetTGAHeader(xhr.response);
  9477. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  9478. return true;
  9479. }
  9480. else if (dataType === 2) {
  9481. return false;
  9482. }
  9483. }
  9484. if (dataType & 4) {
  9485. // Check for the "DDS" magic number
  9486. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  9487. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  9488. return true;
  9489. }
  9490. else {
  9491. return false;
  9492. }
  9493. }
  9494. }
  9495. catch (e) {
  9496. // Global protection
  9497. }
  9498. return false;
  9499. };
  9500. /**
  9501. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  9502. * Be aware Math.random() could cause collisions, but:
  9503. * "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"
  9504. */
  9505. Tools.RandomId = function () {
  9506. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  9507. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  9508. return v.toString(16);
  9509. });
  9510. };
  9511. /**
  9512. * Test if the given uri is a base64 string.
  9513. * @param uri The uri to test
  9514. * @return True if the uri is a base64 string or false otherwise.
  9515. */
  9516. Tools.IsBase64 = function (uri) {
  9517. return uri.length < 5 ? false : uri.substr(0, 5) === "data:";
  9518. };
  9519. /**
  9520. * Decode the given base64 uri.
  9521. * @param uri The uri to decode
  9522. * @return The decoded base64 data.
  9523. */
  9524. Tools.DecodeBase64 = function (uri) {
  9525. var decodedString = atob(uri.split(",")[1]);
  9526. var bufferLength = decodedString.length;
  9527. var bufferView = new Uint8Array(new ArrayBuffer(bufferLength));
  9528. for (var i = 0; i < bufferLength; i++) {
  9529. bufferView[i] = decodedString.charCodeAt(i);
  9530. }
  9531. return bufferView.buffer;
  9532. };
  9533. Object.defineProperty(Tools, "NoneLogLevel", {
  9534. get: function () {
  9535. return Tools._NoneLogLevel;
  9536. },
  9537. enumerable: true,
  9538. configurable: true
  9539. });
  9540. Object.defineProperty(Tools, "MessageLogLevel", {
  9541. get: function () {
  9542. return Tools._MessageLogLevel;
  9543. },
  9544. enumerable: true,
  9545. configurable: true
  9546. });
  9547. Object.defineProperty(Tools, "WarningLogLevel", {
  9548. get: function () {
  9549. return Tools._WarningLogLevel;
  9550. },
  9551. enumerable: true,
  9552. configurable: true
  9553. });
  9554. Object.defineProperty(Tools, "ErrorLogLevel", {
  9555. get: function () {
  9556. return Tools._ErrorLogLevel;
  9557. },
  9558. enumerable: true,
  9559. configurable: true
  9560. });
  9561. Object.defineProperty(Tools, "AllLogLevel", {
  9562. get: function () {
  9563. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  9564. },
  9565. enumerable: true,
  9566. configurable: true
  9567. });
  9568. Tools._AddLogEntry = function (entry) {
  9569. Tools._LogCache = entry + Tools._LogCache;
  9570. if (Tools.OnNewCacheEntry) {
  9571. Tools.OnNewCacheEntry(entry);
  9572. }
  9573. };
  9574. Tools._FormatMessage = function (message) {
  9575. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  9576. var date = new Date();
  9577. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  9578. };
  9579. Tools._LogDisabled = function (message) {
  9580. // nothing to do
  9581. };
  9582. Tools._LogEnabled = function (message) {
  9583. var formattedMessage = Tools._FormatMessage(message);
  9584. console.log("BJS - " + formattedMessage);
  9585. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  9586. Tools._AddLogEntry(entry);
  9587. };
  9588. Tools._WarnDisabled = function (message) {
  9589. // nothing to do
  9590. };
  9591. Tools._WarnEnabled = function (message) {
  9592. var formattedMessage = Tools._FormatMessage(message);
  9593. console.warn("BJS - " + formattedMessage);
  9594. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  9595. Tools._AddLogEntry(entry);
  9596. };
  9597. Tools._ErrorDisabled = function (message) {
  9598. // nothing to do
  9599. };
  9600. Tools._ErrorEnabled = function (message) {
  9601. Tools.errorsCount++;
  9602. var formattedMessage = Tools._FormatMessage(message);
  9603. console.error("BJS - " + formattedMessage);
  9604. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  9605. Tools._AddLogEntry(entry);
  9606. };
  9607. Object.defineProperty(Tools, "LogCache", {
  9608. get: function () {
  9609. return Tools._LogCache;
  9610. },
  9611. enumerable: true,
  9612. configurable: true
  9613. });
  9614. Tools.ClearLogCache = function () {
  9615. Tools._LogCache = "";
  9616. Tools.errorsCount = 0;
  9617. };
  9618. Object.defineProperty(Tools, "LogLevels", {
  9619. set: function (level) {
  9620. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  9621. Tools.Log = Tools._LogEnabled;
  9622. }
  9623. else {
  9624. Tools.Log = Tools._LogDisabled;
  9625. }
  9626. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  9627. Tools.Warn = Tools._WarnEnabled;
  9628. }
  9629. else {
  9630. Tools.Warn = Tools._WarnDisabled;
  9631. }
  9632. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  9633. Tools.Error = Tools._ErrorEnabled;
  9634. }
  9635. else {
  9636. Tools.Error = Tools._ErrorDisabled;
  9637. }
  9638. },
  9639. enumerable: true,
  9640. configurable: true
  9641. });
  9642. Tools.IsWindowObjectExist = function () {
  9643. return (typeof window) !== "undefined";
  9644. };
  9645. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  9646. get: function () {
  9647. return Tools._PerformanceNoneLogLevel;
  9648. },
  9649. enumerable: true,
  9650. configurable: true
  9651. });
  9652. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  9653. get: function () {
  9654. return Tools._PerformanceUserMarkLogLevel;
  9655. },
  9656. enumerable: true,
  9657. configurable: true
  9658. });
  9659. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  9660. get: function () {
  9661. return Tools._PerformanceConsoleLogLevel;
  9662. },
  9663. enumerable: true,
  9664. configurable: true
  9665. });
  9666. Object.defineProperty(Tools, "PerformanceLogLevel", {
  9667. set: function (level) {
  9668. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  9669. Tools.StartPerformanceCounter = Tools._StartUserMark;
  9670. Tools.EndPerformanceCounter = Tools._EndUserMark;
  9671. return;
  9672. }
  9673. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  9674. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  9675. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  9676. return;
  9677. }
  9678. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  9679. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  9680. },
  9681. enumerable: true,
  9682. configurable: true
  9683. });
  9684. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  9685. };
  9686. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  9687. };
  9688. Tools._StartUserMark = function (counterName, condition) {
  9689. if (condition === void 0) { condition = true; }
  9690. if (!Tools._performance) {
  9691. if (!Tools.IsWindowObjectExist()) {
  9692. return;
  9693. }
  9694. Tools._performance = window.performance;
  9695. }
  9696. if (!condition || !Tools._performance.mark) {
  9697. return;
  9698. }
  9699. Tools._performance.mark(counterName + "-Begin");
  9700. };
  9701. Tools._EndUserMark = function (counterName, condition) {
  9702. if (condition === void 0) { condition = true; }
  9703. if (!condition || !Tools._performance.mark) {
  9704. return;
  9705. }
  9706. Tools._performance.mark(counterName + "-End");
  9707. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  9708. };
  9709. Tools._StartPerformanceConsole = function (counterName, condition) {
  9710. if (condition === void 0) { condition = true; }
  9711. if (!condition) {
  9712. return;
  9713. }
  9714. Tools._StartUserMark(counterName, condition);
  9715. if (console.time) {
  9716. console.time(counterName);
  9717. }
  9718. };
  9719. Tools._EndPerformanceConsole = function (counterName, condition) {
  9720. if (condition === void 0) { condition = true; }
  9721. if (!condition) {
  9722. return;
  9723. }
  9724. Tools._EndUserMark(counterName, condition);
  9725. if (console.time) {
  9726. console.timeEnd(counterName);
  9727. }
  9728. };
  9729. Object.defineProperty(Tools, "Now", {
  9730. get: function () {
  9731. if (Tools.IsWindowObjectExist() && window.performance && window.performance.now) {
  9732. return window.performance.now();
  9733. }
  9734. return Date.now();
  9735. },
  9736. enumerable: true,
  9737. configurable: true
  9738. });
  9739. /**
  9740. * This method will return the name of the class used to create the instance of the given object.
  9741. * It will works only on Javascript basic data types (number, string, ...) and instance of class declared with the @className decorator.
  9742. * @param object the object to get the class name from
  9743. * @return the name of the class, will be "object" for a custom data type not using the @className decorator
  9744. */
  9745. Tools.GetClassName = function (object, isType) {
  9746. if (isType === void 0) { isType = false; }
  9747. var name = null;
  9748. if (!isType && object.getClassName) {
  9749. name = object.getClassName();
  9750. }
  9751. else {
  9752. if (object instanceof Object) {
  9753. var classObj = isType ? object : Object.getPrototypeOf(object);
  9754. name = classObj.constructor["__bjsclassName__"];
  9755. }
  9756. if (!name) {
  9757. name = typeof object;
  9758. }
  9759. }
  9760. return name;
  9761. };
  9762. Tools.First = function (array, predicate) {
  9763. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  9764. var el = array_1[_i];
  9765. if (predicate(el)) {
  9766. return el;
  9767. }
  9768. }
  9769. return null;
  9770. };
  9771. /**
  9772. * This method will return the name of the full name of the class, including its owning module (if any).
  9773. * 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).
  9774. * @param object the object to get the class name from
  9775. * @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.
  9776. */
  9777. Tools.getFullClassName = function (object, isType) {
  9778. if (isType === void 0) { isType = false; }
  9779. var className = null;
  9780. var moduleName = null;
  9781. if (!isType && object.getClassName) {
  9782. className = object.getClassName();
  9783. }
  9784. else {
  9785. if (object instanceof Object) {
  9786. var classObj = isType ? object : Object.getPrototypeOf(object);
  9787. className = classObj.constructor["__bjsclassName__"];
  9788. moduleName = classObj.constructor["__bjsmoduleName__"];
  9789. }
  9790. if (!className) {
  9791. className = typeof object;
  9792. }
  9793. }
  9794. if (!className) {
  9795. return null;
  9796. }
  9797. return ((moduleName != null) ? (moduleName + ".") : "") + className;
  9798. };
  9799. /**
  9800. * This method can be used with hashCodeFromStream when your input is an array of values that are either: number, string, boolean or custom type implementing the getHashCode():number method.
  9801. * @param array
  9802. */
  9803. Tools.arrayOrStringFeeder = function (array) {
  9804. return function (index) {
  9805. if (index >= array.length) {
  9806. return null;
  9807. }
  9808. var val = array.charCodeAt ? array.charCodeAt(index) : array[index];
  9809. if (val && val.getHashCode) {
  9810. val = val.getHashCode();
  9811. }
  9812. if (typeof val === "string") {
  9813. return Tools.hashCodeFromStream(Tools.arrayOrStringFeeder(val));
  9814. }
  9815. return val;
  9816. };
  9817. };
  9818. /**
  9819. * Compute the hashCode of a stream of number
  9820. * To compute the HashCode on a string or an Array of data types implementing the getHashCode() method, use the arrayOrStringFeeder method.
  9821. * @param feeder a callback that will be called until it returns null, each valid returned values will be used to compute the hash code.
  9822. * @return the hash code computed
  9823. */
  9824. Tools.hashCodeFromStream = function (feeder) {
  9825. // Based from here: http://stackoverflow.com/a/7616484/802124
  9826. var hash = 0;
  9827. var index = 0;
  9828. var chr = feeder(index++);
  9829. while (chr != null) {
  9830. hash = ((hash << 5) - hash) + chr;
  9831. hash |= 0; // Convert to 32bit integer
  9832. chr = feeder(index++);
  9833. }
  9834. return hash;
  9835. };
  9836. /**
  9837. * Returns a promise that resolves after the given amount of time.
  9838. * @param delay Number of milliseconds to delay
  9839. * @returns Promise that resolves after the given amount of time
  9840. */
  9841. Tools.DelayAsync = function (delay) {
  9842. return new Promise(function (resolve) {
  9843. setTimeout(function () {
  9844. resolve();
  9845. }, delay);
  9846. });
  9847. };
  9848. Tools.BaseUrl = "";
  9849. Tools.DefaultRetryStrategy = RetryStrategy.ExponentialBackoff();
  9850. /**
  9851. * Default behaviour for cors in the application.
  9852. * It can be a string if the expected behavior is identical in the entire app.
  9853. * Or a callback to be able to set it per url or on a group of them (in case of Video source for instance)
  9854. */
  9855. Tools.CorsBehavior = "anonymous";
  9856. Tools.UseFallbackTexture = true;
  9857. /**
  9858. * Use this object to register external classes like custom textures or material
  9859. * to allow the laoders to instantiate them
  9860. */
  9861. Tools.RegisteredExternalClasses = {};
  9862. // Used in case of a texture loading problem
  9863. 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";
  9864. Tools._tmpFloatArray = new Float32Array(1);
  9865. Tools.PreprocessUrl = function (url) {
  9866. return url;
  9867. };
  9868. // Logs
  9869. Tools._NoneLogLevel = 0;
  9870. Tools._MessageLogLevel = 1;
  9871. Tools._WarningLogLevel = 2;
  9872. Tools._ErrorLogLevel = 4;
  9873. Tools._LogCache = "";
  9874. Tools.errorsCount = 0;
  9875. Tools.Log = Tools._LogEnabled;
  9876. Tools.Warn = Tools._WarnEnabled;
  9877. Tools.Error = Tools._ErrorEnabled;
  9878. // Performances
  9879. Tools._PerformanceNoneLogLevel = 0;
  9880. Tools._PerformanceUserMarkLogLevel = 1;
  9881. Tools._PerformanceConsoleLogLevel = 2;
  9882. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  9883. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  9884. return Tools;
  9885. }());
  9886. BABYLON.Tools = Tools;
  9887. /**
  9888. * This class is used to track a performance counter which is number based.
  9889. * The user has access to many properties which give statistics of different nature
  9890. *
  9891. * The implementer can track two kinds of Performance Counter: time and count
  9892. * 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.
  9893. * 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.
  9894. */
  9895. var PerfCounter = /** @class */ (function () {
  9896. function PerfCounter() {
  9897. this._startMonitoringTime = 0;
  9898. this._min = 0;
  9899. this._max = 0;
  9900. this._average = 0;
  9901. this._lastSecAverage = 0;
  9902. this._current = 0;
  9903. this._totalValueCount = 0;
  9904. this._totalAccumulated = 0;
  9905. this._lastSecAccumulated = 0;
  9906. this._lastSecTime = 0;
  9907. this._lastSecValueCount = 0;
  9908. }
  9909. Object.defineProperty(PerfCounter.prototype, "min", {
  9910. /**
  9911. * Returns the smallest value ever
  9912. */
  9913. get: function () {
  9914. return this._min;
  9915. },
  9916. enumerable: true,
  9917. configurable: true
  9918. });
  9919. Object.defineProperty(PerfCounter.prototype, "max", {
  9920. /**
  9921. * Returns the biggest value ever
  9922. */
  9923. get: function () {
  9924. return this._max;
  9925. },
  9926. enumerable: true,
  9927. configurable: true
  9928. });
  9929. Object.defineProperty(PerfCounter.prototype, "average", {
  9930. /**
  9931. * Returns the average value since the performance counter is running
  9932. */
  9933. get: function () {
  9934. return this._average;
  9935. },
  9936. enumerable: true,
  9937. configurable: true
  9938. });
  9939. Object.defineProperty(PerfCounter.prototype, "lastSecAverage", {
  9940. /**
  9941. * Returns the average value of the last second the counter was monitored
  9942. */
  9943. get: function () {
  9944. return this._lastSecAverage;
  9945. },
  9946. enumerable: true,
  9947. configurable: true
  9948. });
  9949. Object.defineProperty(PerfCounter.prototype, "current", {
  9950. /**
  9951. * Returns the current value
  9952. */
  9953. get: function () {
  9954. return this._current;
  9955. },
  9956. enumerable: true,
  9957. configurable: true
  9958. });
  9959. Object.defineProperty(PerfCounter.prototype, "total", {
  9960. get: function () {
  9961. return this._totalAccumulated;
  9962. },
  9963. enumerable: true,
  9964. configurable: true
  9965. });
  9966. Object.defineProperty(PerfCounter.prototype, "count", {
  9967. get: function () {
  9968. return this._totalValueCount;
  9969. },
  9970. enumerable: true,
  9971. configurable: true
  9972. });
  9973. /**
  9974. * Call this method to start monitoring a new frame.
  9975. * 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.
  9976. */
  9977. PerfCounter.prototype.fetchNewFrame = function () {
  9978. this._totalValueCount++;
  9979. this._current = 0;
  9980. this._lastSecValueCount++;
  9981. };
  9982. /**
  9983. * Call this method to monitor a count of something (e.g. mesh drawn in viewport count)
  9984. * @param newCount the count value to add to the monitored count
  9985. * @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.
  9986. */
  9987. PerfCounter.prototype.addCount = function (newCount, fetchResult) {
  9988. if (!PerfCounter.Enabled) {
  9989. return;
  9990. }
  9991. this._current += newCount;
  9992. if (fetchResult) {
  9993. this._fetchResult();
  9994. }
  9995. };
  9996. /**
  9997. * Start monitoring this performance counter
  9998. */
  9999. PerfCounter.prototype.beginMonitoring = function () {
  10000. if (!PerfCounter.Enabled) {
  10001. return;
  10002. }
  10003. this._startMonitoringTime = Tools.Now;
  10004. };
  10005. /**
  10006. * Compute the time lapsed since the previous beginMonitoring() call.
  10007. * @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
  10008. */
  10009. PerfCounter.prototype.endMonitoring = function (newFrame) {
  10010. if (newFrame === void 0) { newFrame = true; }
  10011. if (!PerfCounter.Enabled) {
  10012. return;
  10013. }
  10014. if (newFrame) {
  10015. this.fetchNewFrame();
  10016. }
  10017. var currentTime = Tools.Now;
  10018. this._current = currentTime - this._startMonitoringTime;
  10019. if (newFrame) {
  10020. this._fetchResult();
  10021. }
  10022. };
  10023. PerfCounter.prototype._fetchResult = function () {
  10024. this._totalAccumulated += this._current;
  10025. this._lastSecAccumulated += this._current;
  10026. // Min/Max update
  10027. this._min = Math.min(this._min, this._current);
  10028. this._max = Math.max(this._max, this._current);
  10029. this._average = this._totalAccumulated / this._totalValueCount;
  10030. // Reset last sec?
  10031. var now = Tools.Now;
  10032. if ((now - this._lastSecTime) > 1000) {
  10033. this._lastSecAverage = this._lastSecAccumulated / this._lastSecValueCount;
  10034. this._lastSecTime = now;
  10035. this._lastSecAccumulated = 0;
  10036. this._lastSecValueCount = 0;
  10037. }
  10038. };
  10039. PerfCounter.Enabled = true;
  10040. return PerfCounter;
  10041. }());
  10042. BABYLON.PerfCounter = PerfCounter;
  10043. /**
  10044. * Use this className as a decorator on a given class definition to add it a name and optionally its module.
  10045. * You can then use the Tools.getClassName(obj) on an instance to retrieve its class name.
  10046. * This method is the only way to get it done in all cases, even if the .js file declaring the class is minified
  10047. * @param name The name of the class, case should be preserved
  10048. * @param module The name of the Module hosting the class, optional, but strongly recommended to specify if possible. Case should be preserved.
  10049. */
  10050. function className(name, module) {
  10051. return function (target) {
  10052. target["__bjsclassName__"] = name;
  10053. target["__bjsmoduleName__"] = (module != null) ? module : null;
  10054. };
  10055. }
  10056. BABYLON.className = className;
  10057. /**
  10058. * An implementation of a loop for asynchronous functions.
  10059. */
  10060. var AsyncLoop = /** @class */ (function () {
  10061. /**
  10062. * Constroctor.
  10063. * @param iterations the number of iterations.
  10064. * @param _fn the function to run each iteration
  10065. * @param _successCallback the callback that will be called upon succesful execution
  10066. * @param offset starting offset.
  10067. */
  10068. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  10069. if (offset === void 0) { offset = 0; }
  10070. this.iterations = iterations;
  10071. this._fn = _fn;
  10072. this._successCallback = _successCallback;
  10073. this.index = offset - 1;
  10074. this._done = false;
  10075. }
  10076. /**
  10077. * Execute the next iteration. Must be called after the last iteration was finished.
  10078. */
  10079. AsyncLoop.prototype.executeNext = function () {
  10080. if (!this._done) {
  10081. if (this.index + 1 < this.iterations) {
  10082. ++this.index;
  10083. this._fn(this);
  10084. }
  10085. else {
  10086. this.breakLoop();
  10087. }
  10088. }
  10089. };
  10090. /**
  10091. * Break the loop and run the success callback.
  10092. */
  10093. AsyncLoop.prototype.breakLoop = function () {
  10094. this._done = true;
  10095. this._successCallback();
  10096. };
  10097. /**
  10098. * Helper function
  10099. */
  10100. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  10101. if (offset === void 0) { offset = 0; }
  10102. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  10103. loop.executeNext();
  10104. return loop;
  10105. };
  10106. /**
  10107. * A for-loop that will run a given number of iterations synchronous and the rest async.
  10108. * @param iterations total number of iterations
  10109. * @param syncedIterations number of synchronous iterations in each async iteration.
  10110. * @param fn the function to call each iteration.
  10111. * @param callback a success call back that will be called when iterating stops.
  10112. * @param breakFunction a break condition (optional)
  10113. * @param timeout timeout settings for the setTimeout function. default - 0.
  10114. * @constructor
  10115. */
  10116. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  10117. if (timeout === void 0) { timeout = 0; }
  10118. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  10119. if (breakFunction && breakFunction())
  10120. loop.breakLoop();
  10121. else {
  10122. setTimeout(function () {
  10123. for (var i = 0; i < syncedIterations; ++i) {
  10124. var iteration = (loop.index * syncedIterations) + i;
  10125. if (iteration >= iterations)
  10126. break;
  10127. fn(iteration);
  10128. if (breakFunction && breakFunction()) {
  10129. loop.breakLoop();
  10130. break;
  10131. }
  10132. }
  10133. loop.executeNext();
  10134. }, timeout);
  10135. }
  10136. }, callback);
  10137. };
  10138. return AsyncLoop;
  10139. }());
  10140. BABYLON.AsyncLoop = AsyncLoop;
  10141. })(BABYLON || (BABYLON = {}));
  10142. //# sourceMappingURL=babylon.tools.js.map
  10143. var BABYLON;
  10144. (function (BABYLON) {
  10145. var PromiseStates;
  10146. (function (PromiseStates) {
  10147. PromiseStates[PromiseStates["Pending"] = 0] = "Pending";
  10148. PromiseStates[PromiseStates["Fulfilled"] = 1] = "Fulfilled";
  10149. PromiseStates[PromiseStates["Rejected"] = 2] = "Rejected";
  10150. })(PromiseStates || (PromiseStates = {}));
  10151. var FulFillmentAgregator = /** @class */ (function () {
  10152. function FulFillmentAgregator() {
  10153. this.count = 0;
  10154. this.target = 0;
  10155. this.results = [];
  10156. }
  10157. return FulFillmentAgregator;
  10158. }());
  10159. var InternalPromise = /** @class */ (function () {
  10160. function InternalPromise(resolver) {
  10161. var _this = this;
  10162. this._state = PromiseStates.Pending;
  10163. this._children = new Array();
  10164. this._rejectWasConsumed = false;
  10165. if (!resolver) {
  10166. return;
  10167. }
  10168. try {
  10169. resolver(function (value) {
  10170. _this._resolve(value);
  10171. }, function (reason) {
  10172. _this._reject(reason);
  10173. });
  10174. }
  10175. catch (e) {
  10176. this._reject(e);
  10177. }
  10178. }
  10179. Object.defineProperty(InternalPromise.prototype, "_result", {
  10180. get: function () {
  10181. return this._resultValue;
  10182. },
  10183. set: function (value) {
  10184. this._resultValue = value;
  10185. if (this._parent && this._parent._result === undefined) {
  10186. this._parent._result = value;
  10187. }
  10188. },
  10189. enumerable: true,
  10190. configurable: true
  10191. });
  10192. InternalPromise.prototype.catch = function (onRejected) {
  10193. return this.then(undefined, onRejected);
  10194. };
  10195. InternalPromise.prototype.then = function (onFulfilled, onRejected) {
  10196. var _this = this;
  10197. var newPromise = new InternalPromise();
  10198. newPromise._onFulfilled = onFulfilled;
  10199. newPromise._onRejected = onRejected;
  10200. // Composition
  10201. this._children.push(newPromise);
  10202. newPromise._parent = this;
  10203. if (this._state !== PromiseStates.Pending) {
  10204. BABYLON.Tools.SetImmediate(function () {
  10205. if (_this._state === PromiseStates.Fulfilled || _this._rejectWasConsumed) {
  10206. var returnedValue = newPromise._resolve(_this._result);
  10207. if (returnedValue !== undefined && returnedValue !== null) {
  10208. if (returnedValue._state !== undefined) {
  10209. var returnedPromise = returnedValue;
  10210. newPromise._children.push(returnedPromise);
  10211. returnedPromise._parent = newPromise;
  10212. newPromise = returnedPromise;
  10213. }
  10214. else {
  10215. newPromise._result = returnedValue;
  10216. }
  10217. }
  10218. }
  10219. else {
  10220. newPromise._reject(_this._reason);
  10221. }
  10222. });
  10223. }
  10224. return newPromise;
  10225. };
  10226. InternalPromise.prototype._moveChildren = function (children) {
  10227. var _this = this;
  10228. (_a = this._children).push.apply(_a, children.splice(0, children.length));
  10229. this._children.forEach(function (child) {
  10230. child._parent = _this;
  10231. });
  10232. if (this._state === PromiseStates.Fulfilled) {
  10233. for (var _i = 0, _b = this._children; _i < _b.length; _i++) {
  10234. var child = _b[_i];
  10235. child._resolve(this._result);
  10236. }
  10237. }
  10238. else if (this._state === PromiseStates.Rejected) {
  10239. for (var _c = 0, _d = this._children; _c < _d.length; _c++) {
  10240. var child = _d[_c];
  10241. child._reject(this._reason);
  10242. }
  10243. }
  10244. var _a;
  10245. };
  10246. InternalPromise.prototype._resolve = function (value) {
  10247. try {
  10248. this._state = PromiseStates.Fulfilled;
  10249. var returnedValue = null;
  10250. if (this._onFulfilled) {
  10251. returnedValue = this._onFulfilled(value);
  10252. }
  10253. if (returnedValue !== undefined && returnedValue !== null) {
  10254. if (returnedValue._state !== undefined) {
  10255. // Transmit children
  10256. var returnedPromise = returnedValue;
  10257. returnedPromise._parent = this;
  10258. returnedPromise._moveChildren(this._children);
  10259. value = returnedPromise._result;
  10260. }
  10261. else {
  10262. value = returnedValue;
  10263. }
  10264. }
  10265. this._result = value;
  10266. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  10267. var child = _a[_i];
  10268. child._resolve(value);
  10269. }
  10270. this._children.length = 0;
  10271. delete this._onFulfilled;
  10272. delete this._onRejected;
  10273. }
  10274. catch (e) {
  10275. this._reject(e, true);
  10276. }
  10277. };
  10278. InternalPromise.prototype._reject = function (reason, onLocalThrow) {
  10279. if (onLocalThrow === void 0) { onLocalThrow = false; }
  10280. this._state = PromiseStates.Rejected;
  10281. this._reason = reason;
  10282. if (this._onRejected && !onLocalThrow) {
  10283. try {
  10284. this._onRejected(reason);
  10285. this._rejectWasConsumed = true;
  10286. }
  10287. catch (e) {
  10288. reason = e;
  10289. }
  10290. }
  10291. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  10292. var child = _a[_i];
  10293. if (this._rejectWasConsumed) {
  10294. child._resolve(null);
  10295. }
  10296. else {
  10297. child._reject(reason);
  10298. }
  10299. }
  10300. this._children.length = 0;
  10301. delete this._onFulfilled;
  10302. delete this._onRejected;
  10303. };
  10304. InternalPromise.resolve = function (value) {
  10305. var newPromise = new InternalPromise();
  10306. newPromise._resolve(value);
  10307. return newPromise;
  10308. };
  10309. InternalPromise._RegisterForFulfillment = function (promise, agregator, index) {
  10310. promise.then(function (value) {
  10311. agregator.results[index] = value;
  10312. agregator.count++;
  10313. if (agregator.count === agregator.target) {
  10314. agregator.rootPromise._resolve(agregator.results);
  10315. }
  10316. return null;
  10317. }, function (reason) {
  10318. if (agregator.rootPromise._state !== PromiseStates.Rejected) {
  10319. agregator.rootPromise._reject(reason);
  10320. }
  10321. });
  10322. };
  10323. InternalPromise.all = function (promises) {
  10324. var newPromise = new InternalPromise();
  10325. var agregator = new FulFillmentAgregator();
  10326. agregator.target = promises.length;
  10327. agregator.rootPromise = newPromise;
  10328. if (promises.length) {
  10329. for (var index = 0; index < promises.length; index++) {
  10330. InternalPromise._RegisterForFulfillment(promises[index], agregator, index);
  10331. }
  10332. }
  10333. else {
  10334. newPromise._resolve([]);
  10335. }
  10336. return newPromise;
  10337. };
  10338. InternalPromise.race = function (promises) {
  10339. var newPromise = new InternalPromise();
  10340. if (promises.length) {
  10341. for (var _i = 0, promises_1 = promises; _i < promises_1.length; _i++) {
  10342. var promise = promises_1[_i];
  10343. promise.then(function (value) {
  10344. if (newPromise) {
  10345. newPromise._resolve(value);
  10346. newPromise = null;
  10347. }
  10348. return null;
  10349. }, function (reason) {
  10350. if (newPromise) {
  10351. newPromise._reject(reason);
  10352. newPromise = null;
  10353. }
  10354. });
  10355. }
  10356. }
  10357. return newPromise;
  10358. };
  10359. return InternalPromise;
  10360. }());
  10361. /**
  10362. * Helper class that provides a small promise polyfill
  10363. */
  10364. var PromisePolyfill = /** @class */ (function () {
  10365. function PromisePolyfill() {
  10366. }
  10367. /**
  10368. * Static function used to check if the polyfill is required
  10369. * If this is the case then the function will inject the polyfill to window.Promise
  10370. * @param force defines a boolean used to force the injection (mostly for testing purposes)
  10371. */
  10372. PromisePolyfill.Apply = function (force) {
  10373. if (force === void 0) { force = false; }
  10374. if (force || typeof Promise === 'undefined') {
  10375. var root = window;
  10376. root.Promise = InternalPromise;
  10377. }
  10378. };
  10379. return PromisePolyfill;
  10380. }());
  10381. BABYLON.PromisePolyfill = PromisePolyfill;
  10382. })(BABYLON || (BABYLON = {}));
  10383. //# sourceMappingURL=babylon.promise.js.map
  10384. /// <reference path="../../../dist/preview release/babylon.d.ts" />
  10385. var BABYLON;
  10386. (function (BABYLON) {
  10387. /**
  10388. * Helper class to push actions to a pool of workers.
  10389. */
  10390. var WorkerPool = /** @class */ (function () {
  10391. /**
  10392. * Constructor
  10393. * @param workers Array of workers to use for actions
  10394. */
  10395. function WorkerPool(workers) {
  10396. this._pendingActions = new Array();
  10397. this._workerInfos = workers.map(function (worker) { return ({
  10398. worker: worker,
  10399. active: false
  10400. }); });
  10401. }
  10402. /**
  10403. * Terminates all workers and clears any pending actions.
  10404. */
  10405. WorkerPool.prototype.dispose = function () {
  10406. for (var _i = 0, _a = this._workerInfos; _i < _a.length; _i++) {
  10407. var workerInfo = _a[_i];
  10408. workerInfo.worker.terminate();
  10409. }
  10410. delete this._workerInfos;
  10411. delete this._pendingActions;
  10412. };
  10413. /**
  10414. * Pushes an action to the worker pool. If all the workers are active, the action will be
  10415. * pended until a worker has completed its action.
  10416. * @param action The action to perform. Call onComplete when the action is complete.
  10417. */
  10418. WorkerPool.prototype.push = function (action) {
  10419. for (var _i = 0, _a = this._workerInfos; _i < _a.length; _i++) {
  10420. var workerInfo = _a[_i];
  10421. if (!workerInfo.active) {
  10422. this._execute(workerInfo, action);
  10423. return;
  10424. }
  10425. }
  10426. this._pendingActions.push(action);
  10427. };
  10428. WorkerPool.prototype._execute = function (workerInfo, action) {
  10429. var _this = this;
  10430. workerInfo.active = true;
  10431. action(workerInfo.worker, function () {
  10432. workerInfo.active = false;
  10433. var nextAction = _this._pendingActions.shift();
  10434. if (nextAction) {
  10435. _this._execute(workerInfo, nextAction);
  10436. }
  10437. });
  10438. };
  10439. return WorkerPool;
  10440. }());
  10441. BABYLON.WorkerPool = WorkerPool;
  10442. })(BABYLON || (BABYLON = {}));
  10443. //# sourceMappingURL=babylon.workerPool.js.map
  10444. var BABYLON;
  10445. (function (BABYLON) {
  10446. /**
  10447. * @hidden
  10448. **/
  10449. var _AlphaState = /** @class */ (function () {
  10450. /**
  10451. * Initializes the state.
  10452. */
  10453. function _AlphaState() {
  10454. this._isAlphaBlendDirty = false;
  10455. this._isBlendFunctionParametersDirty = false;
  10456. this._isBlendEquationParametersDirty = false;
  10457. this._isBlendConstantsDirty = false;
  10458. this._alphaBlend = false;
  10459. this._blendFunctionParameters = new Array(4);
  10460. this._blendEquationParameters = new Array(2);
  10461. this._blendConstants = new Array(4);
  10462. this.reset();
  10463. }
  10464. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  10465. get: function () {
  10466. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  10467. },
  10468. enumerable: true,
  10469. configurable: true
  10470. });
  10471. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  10472. get: function () {
  10473. return this._alphaBlend;
  10474. },
  10475. set: function (value) {
  10476. if (this._alphaBlend === value) {
  10477. return;
  10478. }
  10479. this._alphaBlend = value;
  10480. this._isAlphaBlendDirty = true;
  10481. },
  10482. enumerable: true,
  10483. configurable: true
  10484. });
  10485. _AlphaState.prototype.setAlphaBlendConstants = function (r, g, b, a) {
  10486. if (this._blendConstants[0] === r &&
  10487. this._blendConstants[1] === g &&
  10488. this._blendConstants[2] === b &&
  10489. this._blendConstants[3] === a) {
  10490. return;
  10491. }
  10492. this._blendConstants[0] = r;
  10493. this._blendConstants[1] = g;
  10494. this._blendConstants[2] = b;
  10495. this._blendConstants[3] = a;
  10496. this._isBlendConstantsDirty = true;
  10497. };
  10498. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  10499. if (this._blendFunctionParameters[0] === value0 &&
  10500. this._blendFunctionParameters[1] === value1 &&
  10501. this._blendFunctionParameters[2] === value2 &&
  10502. this._blendFunctionParameters[3] === value3) {
  10503. return;
  10504. }
  10505. this._blendFunctionParameters[0] = value0;
  10506. this._blendFunctionParameters[1] = value1;
  10507. this._blendFunctionParameters[2] = value2;
  10508. this._blendFunctionParameters[3] = value3;
  10509. this._isBlendFunctionParametersDirty = true;
  10510. };
  10511. _AlphaState.prototype.setAlphaEquationParameters = function (rgb, alpha) {
  10512. if (this._blendEquationParameters[0] === rgb &&
  10513. this._blendEquationParameters[1] === alpha) {
  10514. return;
  10515. }
  10516. this._blendEquationParameters[0] = rgb;
  10517. this._blendEquationParameters[1] = alpha;
  10518. this._isBlendEquationParametersDirty = true;
  10519. };
  10520. _AlphaState.prototype.reset = function () {
  10521. this._alphaBlend = false;
  10522. this._blendFunctionParameters[0] = null;
  10523. this._blendFunctionParameters[1] = null;
  10524. this._blendFunctionParameters[2] = null;
  10525. this._blendFunctionParameters[3] = null;
  10526. this._blendEquationParameters[0] = null;
  10527. this._blendEquationParameters[1] = null;
  10528. this._blendConstants[0] = null;
  10529. this._blendConstants[1] = null;
  10530. this._blendConstants[2] = null;
  10531. this._blendConstants[3] = null;
  10532. this._isAlphaBlendDirty = true;
  10533. this._isBlendFunctionParametersDirty = false;
  10534. this._isBlendEquationParametersDirty = false;
  10535. this._isBlendConstantsDirty = false;
  10536. };
  10537. _AlphaState.prototype.apply = function (gl) {
  10538. if (!this.isDirty) {
  10539. return;
  10540. }
  10541. // Alpha blend
  10542. if (this._isAlphaBlendDirty) {
  10543. if (this._alphaBlend) {
  10544. gl.enable(gl.BLEND);
  10545. }
  10546. else {
  10547. gl.disable(gl.BLEND);
  10548. }
  10549. this._isAlphaBlendDirty = false;
  10550. }
  10551. // Alpha function
  10552. if (this._isBlendFunctionParametersDirty) {
  10553. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  10554. this._isBlendFunctionParametersDirty = false;
  10555. }
  10556. // Alpha equation
  10557. if (this._isBlendEquationParametersDirty) {
  10558. gl.blendEquationSeparate(this._isBlendEquationParametersDirty[0], this._isBlendEquationParametersDirty[1]);
  10559. this._isBlendEquationParametersDirty = false;
  10560. }
  10561. // Constants
  10562. if (this._isBlendConstantsDirty) {
  10563. gl.blendColor(this._blendConstants[0], this._blendConstants[1], this._blendConstants[2], this._blendConstants[3]);
  10564. this._isBlendConstantsDirty = false;
  10565. }
  10566. };
  10567. return _AlphaState;
  10568. }());
  10569. BABYLON._AlphaState = _AlphaState;
  10570. })(BABYLON || (BABYLON = {}));
  10571. //# sourceMappingURL=babylon.alphaCullingState.js.map
  10572. var BABYLON;
  10573. (function (BABYLON) {
  10574. /**
  10575. * @hidden
  10576. **/
  10577. var _DepthCullingState = /** @class */ (function () {
  10578. /**
  10579. * Initializes the state.
  10580. */
  10581. function _DepthCullingState() {
  10582. this._isDepthTestDirty = false;
  10583. this._isDepthMaskDirty = false;
  10584. this._isDepthFuncDirty = false;
  10585. this._isCullFaceDirty = false;
  10586. this._isCullDirty = false;
  10587. this._isZOffsetDirty = false;
  10588. this._isFrontFaceDirty = false;
  10589. this.reset();
  10590. }
  10591. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  10592. get: function () {
  10593. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty || this._isFrontFaceDirty;
  10594. },
  10595. enumerable: true,
  10596. configurable: true
  10597. });
  10598. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  10599. get: function () {
  10600. return this._zOffset;
  10601. },
  10602. set: function (value) {
  10603. if (this._zOffset === value) {
  10604. return;
  10605. }
  10606. this._zOffset = value;
  10607. this._isZOffsetDirty = true;
  10608. },
  10609. enumerable: true,
  10610. configurable: true
  10611. });
  10612. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  10613. get: function () {
  10614. return this._cullFace;
  10615. },
  10616. set: function (value) {
  10617. if (this._cullFace === value) {
  10618. return;
  10619. }
  10620. this._cullFace = value;
  10621. this._isCullFaceDirty = true;
  10622. },
  10623. enumerable: true,
  10624. configurable: true
  10625. });
  10626. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  10627. get: function () {
  10628. return this._cull;
  10629. },
  10630. set: function (value) {
  10631. if (this._cull === value) {
  10632. return;
  10633. }
  10634. this._cull = value;
  10635. this._isCullDirty = true;
  10636. },
  10637. enumerable: true,
  10638. configurable: true
  10639. });
  10640. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  10641. get: function () {
  10642. return this._depthFunc;
  10643. },
  10644. set: function (value) {
  10645. if (this._depthFunc === value) {
  10646. return;
  10647. }
  10648. this._depthFunc = value;
  10649. this._isDepthFuncDirty = true;
  10650. },
  10651. enumerable: true,
  10652. configurable: true
  10653. });
  10654. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  10655. get: function () {
  10656. return this._depthMask;
  10657. },
  10658. set: function (value) {
  10659. if (this._depthMask === value) {
  10660. return;
  10661. }
  10662. this._depthMask = value;
  10663. this._isDepthMaskDirty = true;
  10664. },
  10665. enumerable: true,
  10666. configurable: true
  10667. });
  10668. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  10669. get: function () {
  10670. return this._depthTest;
  10671. },
  10672. set: function (value) {
  10673. if (this._depthTest === value) {
  10674. return;
  10675. }
  10676. this._depthTest = value;
  10677. this._isDepthTestDirty = true;
  10678. },
  10679. enumerable: true,
  10680. configurable: true
  10681. });
  10682. Object.defineProperty(_DepthCullingState.prototype, "frontFace", {
  10683. get: function () {
  10684. return this._frontFace;
  10685. },
  10686. set: function (value) {
  10687. if (this._frontFace === value) {
  10688. return;
  10689. }
  10690. this._frontFace = value;
  10691. this._isFrontFaceDirty = true;
  10692. },
  10693. enumerable: true,
  10694. configurable: true
  10695. });
  10696. _DepthCullingState.prototype.reset = function () {
  10697. this._depthMask = true;
  10698. this._depthTest = true;
  10699. this._depthFunc = null;
  10700. this._cullFace = null;
  10701. this._cull = null;
  10702. this._zOffset = 0;
  10703. this._frontFace = null;
  10704. this._isDepthTestDirty = true;
  10705. this._isDepthMaskDirty = true;
  10706. this._isDepthFuncDirty = false;
  10707. this._isCullFaceDirty = false;
  10708. this._isCullDirty = false;
  10709. this._isZOffsetDirty = false;
  10710. this._isFrontFaceDirty = false;
  10711. };
  10712. _DepthCullingState.prototype.apply = function (gl) {
  10713. if (!this.isDirty) {
  10714. return;
  10715. }
  10716. // Cull
  10717. if (this._isCullDirty) {
  10718. if (this.cull) {
  10719. gl.enable(gl.CULL_FACE);
  10720. }
  10721. else {
  10722. gl.disable(gl.CULL_FACE);
  10723. }
  10724. this._isCullDirty = false;
  10725. }
  10726. // Cull face
  10727. if (this._isCullFaceDirty) {
  10728. gl.cullFace(this.cullFace);
  10729. this._isCullFaceDirty = false;
  10730. }
  10731. // Depth mask
  10732. if (this._isDepthMaskDirty) {
  10733. gl.depthMask(this.depthMask);
  10734. this._isDepthMaskDirty = false;
  10735. }
  10736. // Depth test
  10737. if (this._isDepthTestDirty) {
  10738. if (this.depthTest) {
  10739. gl.enable(gl.DEPTH_TEST);
  10740. }
  10741. else {
  10742. gl.disable(gl.DEPTH_TEST);
  10743. }
  10744. this._isDepthTestDirty = false;
  10745. }
  10746. // Depth func
  10747. if (this._isDepthFuncDirty) {
  10748. gl.depthFunc(this.depthFunc);
  10749. this._isDepthFuncDirty = false;
  10750. }
  10751. // zOffset
  10752. if (this._isZOffsetDirty) {
  10753. if (this.zOffset) {
  10754. gl.enable(gl.POLYGON_OFFSET_FILL);
  10755. gl.polygonOffset(this.zOffset, 0);
  10756. }
  10757. else {
  10758. gl.disable(gl.POLYGON_OFFSET_FILL);
  10759. }
  10760. this._isZOffsetDirty = false;
  10761. }
  10762. // Front face
  10763. if (this._isFrontFaceDirty) {
  10764. gl.frontFace(this.frontFace);
  10765. this._isFrontFaceDirty = false;
  10766. }
  10767. };
  10768. return _DepthCullingState;
  10769. }());
  10770. BABYLON._DepthCullingState = _DepthCullingState;
  10771. })(BABYLON || (BABYLON = {}));
  10772. //# sourceMappingURL=babylon.depthCullingState.js.map
  10773. var BABYLON;
  10774. (function (BABYLON) {
  10775. /**
  10776. * @hidden
  10777. **/
  10778. var _StencilState = /** @class */ (function () {
  10779. function _StencilState() {
  10780. this._isStencilTestDirty = false;
  10781. this._isStencilMaskDirty = false;
  10782. this._isStencilFuncDirty = false;
  10783. this._isStencilOpDirty = false;
  10784. this.reset();
  10785. }
  10786. Object.defineProperty(_StencilState.prototype, "isDirty", {
  10787. get: function () {
  10788. return this._isStencilTestDirty || this._isStencilMaskDirty || this._isStencilFuncDirty || this._isStencilOpDirty;
  10789. },
  10790. enumerable: true,
  10791. configurable: true
  10792. });
  10793. Object.defineProperty(_StencilState.prototype, "stencilFunc", {
  10794. get: function () {
  10795. return this._stencilFunc;
  10796. },
  10797. set: function (value) {
  10798. if (this._stencilFunc === value) {
  10799. return;
  10800. }
  10801. this._stencilFunc = value;
  10802. this._isStencilFuncDirty = true;
  10803. },
  10804. enumerable: true,
  10805. configurable: true
  10806. });
  10807. Object.defineProperty(_StencilState.prototype, "stencilFuncRef", {
  10808. get: function () {
  10809. return this._stencilFuncRef;
  10810. },
  10811. set: function (value) {
  10812. if (this._stencilFuncRef === value) {
  10813. return;
  10814. }
  10815. this._stencilFuncRef = value;
  10816. this._isStencilFuncDirty = true;
  10817. },
  10818. enumerable: true,
  10819. configurable: true
  10820. });
  10821. Object.defineProperty(_StencilState.prototype, "stencilFuncMask", {
  10822. get: function () {
  10823. return this._stencilFuncMask;
  10824. },
  10825. set: function (value) {
  10826. if (this._stencilFuncMask === value) {
  10827. return;
  10828. }
  10829. this._stencilFuncMask = value;
  10830. this._isStencilFuncDirty = true;
  10831. },
  10832. enumerable: true,
  10833. configurable: true
  10834. });
  10835. Object.defineProperty(_StencilState.prototype, "stencilOpStencilFail", {
  10836. get: function () {
  10837. return this._stencilOpStencilFail;
  10838. },
  10839. set: function (value) {
  10840. if (this._stencilOpStencilFail === value) {
  10841. return;
  10842. }
  10843. this._stencilOpStencilFail = value;
  10844. this._isStencilOpDirty = true;
  10845. },
  10846. enumerable: true,
  10847. configurable: true
  10848. });
  10849. Object.defineProperty(_StencilState.prototype, "stencilOpDepthFail", {
  10850. get: function () {
  10851. return this._stencilOpDepthFail;
  10852. },
  10853. set: function (value) {
  10854. if (this._stencilOpDepthFail === value) {
  10855. return;
  10856. }
  10857. this._stencilOpDepthFail = value;
  10858. this._isStencilOpDirty = true;
  10859. },
  10860. enumerable: true,
  10861. configurable: true
  10862. });
  10863. Object.defineProperty(_StencilState.prototype, "stencilOpStencilDepthPass", {
  10864. get: function () {
  10865. return this._stencilOpStencilDepthPass;
  10866. },
  10867. set: function (value) {
  10868. if (this._stencilOpStencilDepthPass === value) {
  10869. return;
  10870. }
  10871. this._stencilOpStencilDepthPass = value;
  10872. this._isStencilOpDirty = true;
  10873. },
  10874. enumerable: true,
  10875. configurable: true
  10876. });
  10877. Object.defineProperty(_StencilState.prototype, "stencilMask", {
  10878. get: function () {
  10879. return this._stencilMask;
  10880. },
  10881. set: function (value) {
  10882. if (this._stencilMask === value) {
  10883. return;
  10884. }
  10885. this._stencilMask = value;
  10886. this._isStencilMaskDirty = true;
  10887. },
  10888. enumerable: true,
  10889. configurable: true
  10890. });
  10891. Object.defineProperty(_StencilState.prototype, "stencilTest", {
  10892. get: function () {
  10893. return this._stencilTest;
  10894. },
  10895. set: function (value) {
  10896. if (this._stencilTest === value) {
  10897. return;
  10898. }
  10899. this._stencilTest = value;
  10900. this._isStencilTestDirty = true;
  10901. },
  10902. enumerable: true,
  10903. configurable: true
  10904. });
  10905. _StencilState.prototype.reset = function () {
  10906. this._stencilTest = false;
  10907. this._stencilMask = 0xFF;
  10908. this._stencilFunc = BABYLON.Engine.ALWAYS;
  10909. this._stencilFuncRef = 1;
  10910. this._stencilFuncMask = 0xFF;
  10911. this._stencilOpStencilFail = BABYLON.Engine.KEEP;
  10912. this._stencilOpDepthFail = BABYLON.Engine.KEEP;
  10913. this._stencilOpStencilDepthPass = BABYLON.Engine.REPLACE;
  10914. this._isStencilTestDirty = true;
  10915. this._isStencilMaskDirty = true;
  10916. this._isStencilFuncDirty = true;
  10917. this._isStencilOpDirty = true;
  10918. };
  10919. _StencilState.prototype.apply = function (gl) {
  10920. if (!this.isDirty) {
  10921. return;
  10922. }
  10923. // Stencil test
  10924. if (this._isStencilTestDirty) {
  10925. if (this.stencilTest) {
  10926. gl.enable(gl.STENCIL_TEST);
  10927. }
  10928. else {
  10929. gl.disable(gl.STENCIL_TEST);
  10930. }
  10931. this._isStencilTestDirty = false;
  10932. }
  10933. // Stencil mask
  10934. if (this._isStencilMaskDirty) {
  10935. gl.stencilMask(this.stencilMask);
  10936. this._isStencilMaskDirty = false;
  10937. }
  10938. // Stencil func
  10939. if (this._isStencilFuncDirty) {
  10940. gl.stencilFunc(this.stencilFunc, this.stencilFuncRef, this.stencilFuncMask);
  10941. this._isStencilFuncDirty = false;
  10942. }
  10943. // Stencil op
  10944. if (this._isStencilOpDirty) {
  10945. gl.stencilOp(this.stencilOpStencilFail, this.stencilOpDepthFail, this.stencilOpStencilDepthPass);
  10946. this._isStencilOpDirty = false;
  10947. }
  10948. };
  10949. return _StencilState;
  10950. }());
  10951. BABYLON._StencilState = _StencilState;
  10952. })(BABYLON || (BABYLON = {}));
  10953. //# sourceMappingURL=babylon.stencilState.js.map
  10954. var __assign = (this && this.__assign) || Object.assign || function(t) {
  10955. for (var s, i = 1, n = arguments.length; i < n; i++) {
  10956. s = arguments[i];
  10957. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  10958. t[p] = s[p];
  10959. }
  10960. return t;
  10961. };
  10962. var BABYLON;
  10963. (function (BABYLON) {
  10964. var compileShader = function (gl, source, type, defines, shaderVersion) {
  10965. return compileRawShader(gl, shaderVersion + (defines ? defines + "\n" : "") + source, type);
  10966. };
  10967. var compileRawShader = function (gl, source, type) {
  10968. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  10969. gl.shaderSource(shader, source);
  10970. gl.compileShader(shader);
  10971. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  10972. var log = gl.getShaderInfoLog(shader);
  10973. if (log) {
  10974. throw new Error(log);
  10975. }
  10976. }
  10977. if (!shader) {
  10978. throw new Error("Something went wrong while compile the shader.");
  10979. }
  10980. return shader;
  10981. };
  10982. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  10983. var magFilter = gl.NEAREST;
  10984. var minFilter = gl.NEAREST;
  10985. switch (samplingMode) {
  10986. case BABYLON.Texture.BILINEAR_SAMPLINGMODE:
  10987. magFilter = gl.LINEAR;
  10988. if (generateMipMaps) {
  10989. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  10990. }
  10991. else {
  10992. minFilter = gl.LINEAR;
  10993. }
  10994. break;
  10995. case BABYLON.Texture.TRILINEAR_SAMPLINGMODE:
  10996. magFilter = gl.LINEAR;
  10997. if (generateMipMaps) {
  10998. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  10999. }
  11000. else {
  11001. minFilter = gl.LINEAR;
  11002. }
  11003. break;
  11004. case BABYLON.Texture.NEAREST_SAMPLINGMODE:
  11005. magFilter = gl.NEAREST;
  11006. if (generateMipMaps) {
  11007. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  11008. }
  11009. else {
  11010. minFilter = gl.NEAREST;
  11011. }
  11012. break;
  11013. case BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST:
  11014. magFilter = gl.NEAREST;
  11015. if (generateMipMaps) {
  11016. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  11017. }
  11018. else {
  11019. minFilter = gl.NEAREST;
  11020. }
  11021. break;
  11022. case BABYLON.Texture.NEAREST_LINEAR_MIPNEAREST:
  11023. magFilter = gl.NEAREST;
  11024. if (generateMipMaps) {
  11025. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  11026. }
  11027. else {
  11028. minFilter = gl.LINEAR;
  11029. }
  11030. break;
  11031. case BABYLON.Texture.NEAREST_LINEAR_MIPLINEAR:
  11032. magFilter = gl.NEAREST;
  11033. if (generateMipMaps) {
  11034. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  11035. }
  11036. else {
  11037. minFilter = gl.LINEAR;
  11038. }
  11039. break;
  11040. case BABYLON.Texture.NEAREST_LINEAR:
  11041. magFilter = gl.NEAREST;
  11042. minFilter = gl.LINEAR;
  11043. break;
  11044. case BABYLON.Texture.NEAREST_NEAREST:
  11045. magFilter = gl.NEAREST;
  11046. minFilter = gl.NEAREST;
  11047. break;
  11048. case BABYLON.Texture.LINEAR_NEAREST_MIPNEAREST:
  11049. magFilter = gl.LINEAR;
  11050. if (generateMipMaps) {
  11051. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  11052. }
  11053. else {
  11054. minFilter = gl.NEAREST;
  11055. }
  11056. break;
  11057. case BABYLON.Texture.LINEAR_NEAREST_MIPLINEAR:
  11058. magFilter = gl.LINEAR;
  11059. if (generateMipMaps) {
  11060. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  11061. }
  11062. else {
  11063. minFilter = gl.NEAREST;
  11064. }
  11065. break;
  11066. case BABYLON.Texture.LINEAR_LINEAR:
  11067. magFilter = gl.LINEAR;
  11068. minFilter = gl.LINEAR;
  11069. break;
  11070. case BABYLON.Texture.LINEAR_NEAREST:
  11071. magFilter = gl.LINEAR;
  11072. minFilter = gl.NEAREST;
  11073. break;
  11074. }
  11075. return {
  11076. min: minFilter,
  11077. mag: magFilter
  11078. };
  11079. };
  11080. var partialLoadImg = function (url, index, loadedImages, scene, onfinish, onErrorCallBack) {
  11081. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  11082. var img;
  11083. var onload = function () {
  11084. loadedImages[index] = img;
  11085. loadedImages._internalCount++;
  11086. if (scene) {
  11087. scene._removePendingData(img);
  11088. }
  11089. if (loadedImages._internalCount === 6) {
  11090. onfinish(loadedImages);
  11091. }
  11092. };
  11093. var onerror = function (message, exception) {
  11094. if (scene) {
  11095. scene._removePendingData(img);
  11096. }
  11097. if (onErrorCallBack) {
  11098. onErrorCallBack(message, exception);
  11099. }
  11100. };
  11101. img = BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  11102. if (scene) {
  11103. scene._addPendingData(img);
  11104. }
  11105. };
  11106. var cascadeLoadImgs = function (rootUrl, scene, onfinish, files, onError) {
  11107. if (onError === void 0) { onError = null; }
  11108. var loadedImages = [];
  11109. loadedImages._internalCount = 0;
  11110. for (var index = 0; index < 6; index++) {
  11111. partialLoadImg(files[index], index, loadedImages, scene, onfinish, onError);
  11112. }
  11113. };
  11114. var BufferPointer = /** @class */ (function () {
  11115. function BufferPointer() {
  11116. }
  11117. return BufferPointer;
  11118. }());
  11119. /**
  11120. * Interface for attribute information associated with buffer instanciation
  11121. */
  11122. var InstancingAttributeInfo = /** @class */ (function () {
  11123. function InstancingAttributeInfo() {
  11124. }
  11125. return InstancingAttributeInfo;
  11126. }());
  11127. BABYLON.InstancingAttributeInfo = InstancingAttributeInfo;
  11128. /**
  11129. * Define options used to create a render target texture
  11130. */
  11131. var RenderTargetCreationOptions = /** @class */ (function () {
  11132. function RenderTargetCreationOptions() {
  11133. }
  11134. return RenderTargetCreationOptions;
  11135. }());
  11136. BABYLON.RenderTargetCreationOptions = RenderTargetCreationOptions;
  11137. /**
  11138. * Define options used to create a depth texture
  11139. */
  11140. var DepthTextureCreationOptions = /** @class */ (function () {
  11141. function DepthTextureCreationOptions() {
  11142. }
  11143. return DepthTextureCreationOptions;
  11144. }());
  11145. BABYLON.DepthTextureCreationOptions = DepthTextureCreationOptions;
  11146. /**
  11147. * Class used to describe the capabilities of the engine relatively to the current browser
  11148. */
  11149. var EngineCapabilities = /** @class */ (function () {
  11150. function EngineCapabilities() {
  11151. }
  11152. return EngineCapabilities;
  11153. }());
  11154. BABYLON.EngineCapabilities = EngineCapabilities;
  11155. /**
  11156. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio
  11157. */
  11158. var Engine = /** @class */ (function () {
  11159. /**
  11160. * Creates a new engine
  11161. * @param canvasOrContext defines the canvas or WebGL context to use for rendering
  11162. * @param antialias defines enable antialiasing (default: false)
  11163. * @param options defines further options to be sent to the getContext() function
  11164. * @param adaptToDeviceRatio defines whether to adapt to the device's viewport characteristics (default: false)
  11165. */
  11166. function Engine(canvasOrContext, antialias, options, adaptToDeviceRatio) {
  11167. if (adaptToDeviceRatio === void 0) { adaptToDeviceRatio = false; }
  11168. var _this = this;
  11169. // Public members
  11170. /**
  11171. * Gets or sets a boolean that indicates if textures must be forced to power of 2 size even if not required
  11172. */
  11173. this.forcePOTTextures = false;
  11174. /**
  11175. * Gets a boolean indicating if the engine is currently rendering in fullscreen mode
  11176. */
  11177. this.isFullscreen = false;
  11178. /**
  11179. * Gets a boolean indicating if the pointer is currently locked
  11180. */
  11181. this.isPointerLock = false;
  11182. /**
  11183. * Gets or sets a boolean indicating if back faces must be culled (true by default)
  11184. */
  11185. this.cullBackFaces = true;
  11186. /**
  11187. * Gets or sets a boolean indicating if the engine must keep rendering even if the window is not in foregroun
  11188. */
  11189. this.renderEvenInBackground = true;
  11190. /**
  11191. * Gets or sets a boolean indicating that cache can be kept between frames
  11192. */
  11193. this.preventCacheWipeBetweenFrames = false;
  11194. /**
  11195. * Gets or sets a boolean to enable/disable IndexedDB support and avoid XHR on .manifest
  11196. **/
  11197. this.enableOfflineSupport = false;
  11198. /**
  11199. * 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)
  11200. **/
  11201. this.disableManifestCheck = false;
  11202. /**
  11203. * Gets the list of created scenes
  11204. */
  11205. this.scenes = new Array();
  11206. /**
  11207. * Gets the list of created postprocesses
  11208. */
  11209. this.postProcesses = new Array();
  11210. // Observables
  11211. /**
  11212. * Observable event triggered each time the rendering canvas is resized
  11213. */
  11214. this.onResizeObservable = new BABYLON.Observable();
  11215. /**
  11216. * Observable event triggered each time the canvas loses focus
  11217. */
  11218. this.onCanvasBlurObservable = new BABYLON.Observable();
  11219. /**
  11220. * Observable event triggered each time the canvas gains focus
  11221. */
  11222. this.onCanvasFocusObservable = new BABYLON.Observable();
  11223. /**
  11224. * Observable event triggered each time the canvas receives pointerout event
  11225. */
  11226. this.onCanvasPointerOutObservable = new BABYLON.Observable();
  11227. /**
  11228. * Observable event triggered before each texture is initialized
  11229. */
  11230. this.onBeforeTextureInitObservable = new BABYLON.Observable();
  11231. //WebVR
  11232. this._vrDisplay = undefined;
  11233. this._vrSupported = false;
  11234. this._vrExclusivePointerMode = false;
  11235. // Uniform buffers list
  11236. /**
  11237. * Gets or sets a boolean indicating that uniform buffers must be disabled even if they are supported
  11238. */
  11239. this.disableUniformBuffers = false;
  11240. /** @hidden */
  11241. this._uniformBuffers = new Array();
  11242. // Observables
  11243. /**
  11244. * Observable raised when the engine begins a new frame
  11245. */
  11246. this.onBeginFrameObservable = new BABYLON.Observable();
  11247. /**
  11248. * Observable raised when the engine ends the current frame
  11249. */
  11250. this.onEndFrameObservable = new BABYLON.Observable();
  11251. /**
  11252. * Observable raised when the engine is about to compile a shader
  11253. */
  11254. this.onBeforeShaderCompilationObservable = new BABYLON.Observable();
  11255. /**
  11256. * Observable raised when the engine has jsut compiled a shader
  11257. */
  11258. this.onAfterShaderCompilationObservable = new BABYLON.Observable();
  11259. this._windowIsBackground = false;
  11260. this._webGLVersion = 1.0;
  11261. /** @hidden */
  11262. this._badOS = false;
  11263. /** @hidden */
  11264. this._badDesktopOS = false;
  11265. /**
  11266. * Gets or sets a value indicating if we want to disable texture binding optmization.
  11267. * This could be required on some buggy drivers which wants to have textures bound in a progressive order.
  11268. * By default Babylon.js will try to let textures bound where they are and only update the samplers to point where the texture is
  11269. */
  11270. this.disableTextureBindingOptimization = false;
  11271. /**
  11272. * Observable signaled when VR display mode changes
  11273. */
  11274. this.onVRDisplayChangedObservable = new BABYLON.Observable();
  11275. /**
  11276. * Observable signaled when VR request present is complete
  11277. */
  11278. this.onVRRequestPresentComplete = new BABYLON.Observable();
  11279. /**
  11280. * Observable signaled when VR request present starts
  11281. */
  11282. this.onVRRequestPresentStart = new BABYLON.Observable();
  11283. this._colorWrite = true;
  11284. /** @hidden */
  11285. this._drawCalls = new BABYLON.PerfCounter();
  11286. /** @hidden */
  11287. this._textureCollisions = new BABYLON.PerfCounter();
  11288. this._renderingQueueLaunched = false;
  11289. this._activeRenderLoops = new Array();
  11290. // Deterministic lockstepMaxSteps
  11291. this._deterministicLockstep = false;
  11292. this._lockstepMaxSteps = 4;
  11293. // Lost context
  11294. /**
  11295. * Observable signaled when a context lost event is raised
  11296. */
  11297. this.onContextLostObservable = new BABYLON.Observable();
  11298. /**
  11299. * Observable signaled when a context restored event is raised
  11300. */
  11301. this.onContextRestoredObservable = new BABYLON.Observable();
  11302. this._contextWasLost = false;
  11303. this._doNotHandleContextLost = false;
  11304. // FPS
  11305. this._performanceMonitor = new BABYLON.PerformanceMonitor();
  11306. this._fps = 60;
  11307. this._deltaTime = 0;
  11308. /**
  11309. * Turn this value on if you want to pause FPS computation when in background
  11310. */
  11311. this.disablePerformanceMonitorInBackground = false;
  11312. // States
  11313. /** @hidden */
  11314. this._depthCullingState = new BABYLON._DepthCullingState();
  11315. /** @hidden */
  11316. this._stencilState = new BABYLON._StencilState();
  11317. /** @hidden */
  11318. this._alphaState = new BABYLON._AlphaState();
  11319. /** @hidden */
  11320. this._alphaMode = Engine.ALPHA_DISABLE;
  11321. // Cache
  11322. this._internalTexturesCache = new Array();
  11323. /** @hidden */
  11324. this._activeChannel = 0;
  11325. this._currentTextureChannel = -1;
  11326. /** @hidden */
  11327. this._boundTexturesCache = {};
  11328. this._compiledEffects = {};
  11329. this._vertexAttribArraysEnabled = [];
  11330. this._uintIndicesCurrentlySet = false;
  11331. this._currentBoundBuffer = new Array();
  11332. this._currentBufferPointers = new Array();
  11333. this._currentInstanceLocations = new Array();
  11334. this._currentInstanceBuffers = new Array();
  11335. this._firstBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  11336. this._lastBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  11337. this._vaoRecordInProgress = false;
  11338. this._mustWipeVertexAttributes = false;
  11339. this._nextFreeTextureSlots = new Array();
  11340. this._maxSimultaneousTextures = 0;
  11341. this._activeRequests = new Array();
  11342. // Hardware supported Compressed Textures
  11343. this._texturesSupported = new Array();
  11344. this._onVRFullScreenTriggered = function () {
  11345. if (_this._vrDisplay && _this._vrDisplay.isPresenting) {
  11346. //get the old size before we change
  11347. _this._oldSize = new BABYLON.Size(_this.getRenderWidth(), _this.getRenderHeight());
  11348. _this._oldHardwareScaleFactor = _this.getHardwareScalingLevel();
  11349. //get the width and height, change the render size
  11350. var leftEye = _this._vrDisplay.getEyeParameters('left');
  11351. _this.setHardwareScalingLevel(1);
  11352. _this.setSize(leftEye.renderWidth * 2, leftEye.renderHeight);
  11353. }
  11354. else {
  11355. _this.setHardwareScalingLevel(_this._oldHardwareScaleFactor);
  11356. _this.setSize(_this._oldSize.width, _this._oldSize.height);
  11357. }
  11358. };
  11359. this._boundUniforms = {};
  11360. // Register promises
  11361. BABYLON.PromisePolyfill.Apply();
  11362. var canvas = null;
  11363. Engine.Instances.push(this);
  11364. if (!canvasOrContext) {
  11365. return;
  11366. }
  11367. options = options || {};
  11368. if (canvasOrContext.getContext) {
  11369. canvas = canvasOrContext;
  11370. this._renderingCanvas = canvas;
  11371. if (antialias != null) {
  11372. options.antialias = antialias;
  11373. }
  11374. if (options.deterministicLockstep === undefined) {
  11375. options.deterministicLockstep = false;
  11376. }
  11377. if (options.lockstepMaxSteps === undefined) {
  11378. options.lockstepMaxSteps = 4;
  11379. }
  11380. if (options.preserveDrawingBuffer === undefined) {
  11381. options.preserveDrawingBuffer = false;
  11382. }
  11383. if (options.audioEngine === undefined) {
  11384. options.audioEngine = true;
  11385. }
  11386. if (options.stencil === undefined) {
  11387. options.stencil = true;
  11388. }
  11389. this._deterministicLockstep = options.deterministicLockstep;
  11390. this._lockstepMaxSteps = options.lockstepMaxSteps;
  11391. this._doNotHandleContextLost = options.doNotHandleContextLost ? true : false;
  11392. // Exceptions
  11393. if (navigator && navigator.userAgent) {
  11394. var ua = navigator.userAgent;
  11395. for (var _i = 0, _a = Engine.ExceptionList; _i < _a.length; _i++) {
  11396. var exception = _a[_i];
  11397. var key = exception.key;
  11398. var targets = exception.targets;
  11399. if (ua.indexOf(key) > -1) {
  11400. if (exception.capture && exception.captureConstraint) {
  11401. var capture = exception.capture;
  11402. var constraint = exception.captureConstraint;
  11403. var regex = new RegExp(capture);
  11404. var matches = regex.exec(ua);
  11405. if (matches && matches.length > 0) {
  11406. var capturedValue = parseInt(matches[matches.length - 1]);
  11407. if (capturedValue >= constraint) {
  11408. continue;
  11409. }
  11410. }
  11411. }
  11412. for (var _b = 0, targets_1 = targets; _b < targets_1.length; _b++) {
  11413. var target = targets_1[_b];
  11414. switch (target) {
  11415. case "uniformBuffer":
  11416. this.disableUniformBuffers = true;
  11417. break;
  11418. case "textureBindingOptimization":
  11419. this.disableTextureBindingOptimization = true;
  11420. break;
  11421. }
  11422. }
  11423. }
  11424. }
  11425. }
  11426. // GL
  11427. if (!options.disableWebGL2Support) {
  11428. try {
  11429. this._gl = (canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
  11430. if (this._gl) {
  11431. this._webGLVersion = 2.0;
  11432. }
  11433. }
  11434. catch (e) {
  11435. // Do nothing
  11436. }
  11437. }
  11438. if (!this._gl) {
  11439. if (!canvas) {
  11440. throw new Error("The provided canvas is null or undefined.");
  11441. }
  11442. try {
  11443. this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  11444. }
  11445. catch (e) {
  11446. throw new Error("WebGL not supported");
  11447. }
  11448. }
  11449. if (!this._gl) {
  11450. throw new Error("WebGL not supported");
  11451. }
  11452. this._onCanvasFocus = function () {
  11453. _this.onCanvasFocusObservable.notifyObservers(_this);
  11454. };
  11455. this._onCanvasBlur = function () {
  11456. _this.onCanvasBlurObservable.notifyObservers(_this);
  11457. };
  11458. canvas.addEventListener("focus", this._onCanvasFocus);
  11459. canvas.addEventListener("blur", this._onCanvasBlur);
  11460. this._onBlur = function () {
  11461. if (_this.disablePerformanceMonitorInBackground) {
  11462. _this._performanceMonitor.disable();
  11463. }
  11464. _this._windowIsBackground = true;
  11465. };
  11466. this._onFocus = function () {
  11467. if (_this.disablePerformanceMonitorInBackground) {
  11468. _this._performanceMonitor.enable();
  11469. }
  11470. _this._windowIsBackground = false;
  11471. };
  11472. this._onCanvasPointerOut = function (ev) {
  11473. _this.onCanvasPointerOutObservable.notifyObservers(ev);
  11474. };
  11475. window.addEventListener("blur", this._onBlur);
  11476. window.addEventListener("focus", this._onFocus);
  11477. canvas.addEventListener("pointerout", this._onCanvasPointerOut);
  11478. // Context lost
  11479. if (!this._doNotHandleContextLost) {
  11480. this._onContextLost = function (evt) {
  11481. evt.preventDefault();
  11482. _this._contextWasLost = true;
  11483. BABYLON.Tools.Warn("WebGL context lost.");
  11484. _this.onContextLostObservable.notifyObservers(_this);
  11485. };
  11486. this._onContextRestored = function (evt) {
  11487. // Adding a timeout to avoid race condition at browser level
  11488. setTimeout(function () {
  11489. // Rebuild gl context
  11490. _this._initGLContext();
  11491. // Rebuild effects
  11492. _this._rebuildEffects();
  11493. // Rebuild textures
  11494. _this._rebuildInternalTextures();
  11495. // Rebuild buffers
  11496. _this._rebuildBuffers();
  11497. // Cache
  11498. _this.wipeCaches(true);
  11499. BABYLON.Tools.Warn("WebGL context successfully restored.");
  11500. _this.onContextRestoredObservable.notifyObservers(_this);
  11501. _this._contextWasLost = false;
  11502. }, 0);
  11503. };
  11504. canvas.addEventListener("webglcontextlost", this._onContextLost, false);
  11505. canvas.addEventListener("webglcontextrestored", this._onContextRestored, false);
  11506. }
  11507. }
  11508. else {
  11509. this._gl = canvasOrContext;
  11510. this._renderingCanvas = this._gl.canvas;
  11511. if (this._gl.renderbufferStorageMultisample) {
  11512. this._webGLVersion = 2.0;
  11513. }
  11514. options.stencil = this._gl.getContextAttributes().stencil;
  11515. }
  11516. // Viewport
  11517. var limitDeviceRatio = options.limitDeviceRatio || window.devicePixelRatio || 1.0;
  11518. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / Math.min(limitDeviceRatio, window.devicePixelRatio || 1.0) : 1.0;
  11519. this.resize();
  11520. this._isStencilEnable = options.stencil ? true : false;
  11521. this._initGLContext();
  11522. if (canvas) {
  11523. // Fullscreen
  11524. this._onFullscreenChange = function () {
  11525. if (document.fullscreen !== undefined) {
  11526. _this.isFullscreen = document.fullscreen;
  11527. }
  11528. else if (document.mozFullScreen !== undefined) {
  11529. _this.isFullscreen = document.mozFullScreen;
  11530. }
  11531. else if (document.webkitIsFullScreen !== undefined) {
  11532. _this.isFullscreen = document.webkitIsFullScreen;
  11533. }
  11534. else if (document.msIsFullScreen !== undefined) {
  11535. _this.isFullscreen = document.msIsFullScreen;
  11536. }
  11537. // Pointer lock
  11538. if (_this.isFullscreen && _this._pointerLockRequested && canvas) {
  11539. canvas.requestPointerLock = canvas.requestPointerLock ||
  11540. canvas.msRequestPointerLock ||
  11541. canvas.mozRequestPointerLock ||
  11542. canvas.webkitRequestPointerLock;
  11543. if (canvas.requestPointerLock) {
  11544. canvas.requestPointerLock();
  11545. }
  11546. }
  11547. };
  11548. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  11549. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  11550. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  11551. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  11552. // Pointer lock
  11553. this._onPointerLockChange = function () {
  11554. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  11555. document.webkitPointerLockElement === canvas ||
  11556. document.msPointerLockElement === canvas ||
  11557. document.pointerLockElement === canvas);
  11558. };
  11559. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  11560. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  11561. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  11562. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  11563. this._onVRDisplayPointerRestricted = function () {
  11564. if (canvas) {
  11565. canvas.requestPointerLock();
  11566. }
  11567. };
  11568. this._onVRDisplayPointerUnrestricted = function () {
  11569. document.exitPointerLock();
  11570. };
  11571. window.addEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted, false);
  11572. window.addEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted, false);
  11573. }
  11574. if (options.audioEngine && BABYLON.AudioEngine && !Engine.audioEngine) {
  11575. Engine.audioEngine = new BABYLON.AudioEngine();
  11576. }
  11577. // Prepare buffer pointers
  11578. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  11579. this._currentBufferPointers[i] = new BufferPointer();
  11580. }
  11581. this._linkTrackers(this._firstBoundInternalTextureTracker, this._lastBoundInternalTextureTracker);
  11582. // Load WebVR Devices
  11583. if (options.autoEnableWebVR) {
  11584. this.initWebVR();
  11585. }
  11586. // Detect if we are running on a faulty buggy OS.
  11587. this._badOS = /iPad/i.test(navigator.userAgent) || /iPhone/i.test(navigator.userAgent);
  11588. // Detect if we are running on a faulty buggy desktop OS.
  11589. this._badDesktopOS = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
  11590. console.log("Babylon.js engine (v" + Engine.Version + ") launched");
  11591. this.enableOfflineSupport = (BABYLON.Database !== undefined);
  11592. }
  11593. Object.defineProperty(Engine, "LastCreatedEngine", {
  11594. /**
  11595. * Gets the latest created engine
  11596. */
  11597. get: function () {
  11598. if (Engine.Instances.length === 0) {
  11599. return null;
  11600. }
  11601. return Engine.Instances[Engine.Instances.length - 1];
  11602. },
  11603. enumerable: true,
  11604. configurable: true
  11605. });
  11606. Object.defineProperty(Engine, "LastCreatedScene", {
  11607. /**
  11608. * Gets the latest created scene
  11609. */
  11610. get: function () {
  11611. var lastCreatedEngine = Engine.LastCreatedEngine;
  11612. if (!lastCreatedEngine) {
  11613. return null;
  11614. }
  11615. if (lastCreatedEngine.scenes.length === 0) {
  11616. return null;
  11617. }
  11618. return lastCreatedEngine.scenes[lastCreatedEngine.scenes.length - 1];
  11619. },
  11620. enumerable: true,
  11621. configurable: true
  11622. });
  11623. /**
  11624. * Will flag all materials in all scenes in all engines as dirty to trigger new shader compilation
  11625. * @param flag defines which part of the materials must be marked as dirty
  11626. * @param predicate defines a predicate used to filter which materials should be affected
  11627. */
  11628. Engine.MarkAllMaterialsAsDirty = function (flag, predicate) {
  11629. for (var engineIndex = 0; engineIndex < Engine.Instances.length; engineIndex++) {
  11630. var engine = Engine.Instances[engineIndex];
  11631. for (var sceneIndex = 0; sceneIndex < engine.scenes.length; sceneIndex++) {
  11632. engine.scenes[sceneIndex].markAllMaterialsAsDirty(flag, predicate);
  11633. }
  11634. }
  11635. };
  11636. Object.defineProperty(Engine, "NEVER", {
  11637. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn */
  11638. get: function () {
  11639. return Engine._NEVER;
  11640. },
  11641. enumerable: true,
  11642. configurable: true
  11643. });
  11644. Object.defineProperty(Engine, "ALWAYS", {
  11645. /** 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 */
  11646. get: function () {
  11647. return Engine._ALWAYS;
  11648. },
  11649. enumerable: true,
  11650. configurable: true
  11651. });
  11652. Object.defineProperty(Engine, "LESS", {
  11653. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is less than the stored value */
  11654. get: function () {
  11655. return Engine._LESS;
  11656. },
  11657. enumerable: true,
  11658. configurable: true
  11659. });
  11660. Object.defineProperty(Engine, "EQUAL", {
  11661. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is equals to the stored value */
  11662. get: function () {
  11663. return Engine._EQUAL;
  11664. },
  11665. enumerable: true,
  11666. configurable: true
  11667. });
  11668. Object.defineProperty(Engine, "LEQUAL", {
  11669. /** 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 */
  11670. get: function () {
  11671. return Engine._LEQUAL;
  11672. },
  11673. enumerable: true,
  11674. configurable: true
  11675. });
  11676. Object.defineProperty(Engine, "GREATER", {
  11677. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is greater than the stored value */
  11678. get: function () {
  11679. return Engine._GREATER;
  11680. },
  11681. enumerable: true,
  11682. configurable: true
  11683. });
  11684. Object.defineProperty(Engine, "GEQUAL", {
  11685. /** 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 */
  11686. get: function () {
  11687. return Engine._GEQUAL;
  11688. },
  11689. enumerable: true,
  11690. configurable: true
  11691. });
  11692. Object.defineProperty(Engine, "NOTEQUAL", {
  11693. /** 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 */
  11694. get: function () {
  11695. return Engine._NOTEQUAL;
  11696. },
  11697. enumerable: true,
  11698. configurable: true
  11699. });
  11700. Object.defineProperty(Engine, "KEEP", {
  11701. /** Passed to stencilOperation to specify that stencil value must be kept */
  11702. get: function () {
  11703. return Engine._KEEP;
  11704. },
  11705. enumerable: true,
  11706. configurable: true
  11707. });
  11708. Object.defineProperty(Engine, "REPLACE", {
  11709. /** Passed to stencilOperation to specify that stencil value must be replaced */
  11710. get: function () {
  11711. return Engine._REPLACE;
  11712. },
  11713. enumerable: true,
  11714. configurable: true
  11715. });
  11716. Object.defineProperty(Engine, "INCR", {
  11717. /** Passed to stencilOperation to specify that stencil value must be incremented */
  11718. get: function () {
  11719. return Engine._INCR;
  11720. },
  11721. enumerable: true,
  11722. configurable: true
  11723. });
  11724. Object.defineProperty(Engine, "DECR", {
  11725. /** Passed to stencilOperation to specify that stencil value must be decremented */
  11726. get: function () {
  11727. return Engine._DECR;
  11728. },
  11729. enumerable: true,
  11730. configurable: true
  11731. });
  11732. Object.defineProperty(Engine, "INVERT", {
  11733. /** Passed to stencilOperation to specify that stencil value must be inverted */
  11734. get: function () {
  11735. return Engine._INVERT;
  11736. },
  11737. enumerable: true,
  11738. configurable: true
  11739. });
  11740. Object.defineProperty(Engine, "INCR_WRAP", {
  11741. /** Passed to stencilOperation to specify that stencil value must be incremented with wrapping */
  11742. get: function () {
  11743. return Engine._INCR_WRAP;
  11744. },
  11745. enumerable: true,
  11746. configurable: true
  11747. });
  11748. Object.defineProperty(Engine, "DECR_WRAP", {
  11749. /** Passed to stencilOperation to specify that stencil value must be decremented with wrapping */
  11750. get: function () {
  11751. return Engine._DECR_WRAP;
  11752. },
  11753. enumerable: true,
  11754. configurable: true
  11755. });
  11756. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  11757. // Alpha
  11758. /** Defines that alpha blending is disabled */
  11759. get: function () {
  11760. return Engine._ALPHA_DISABLE;
  11761. },
  11762. enumerable: true,
  11763. configurable: true
  11764. });
  11765. Object.defineProperty(Engine, "ALPHA_ONEONE", {
  11766. /** Defines that alpha blending to SRC + DEST */
  11767. get: function () {
  11768. return Engine._ALPHA_ONEONE;
  11769. },
  11770. enumerable: true,
  11771. configurable: true
  11772. });
  11773. Object.defineProperty(Engine, "ALPHA_ADD", {
  11774. /** Defines that alpha blending to SRC ALPHA * SRC + DEST */
  11775. get: function () {
  11776. return Engine._ALPHA_ADD;
  11777. },
  11778. enumerable: true,
  11779. configurable: true
  11780. });
  11781. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  11782. /** Defines that alpha blending to SRC ALPHA * SRC + (1 - SRC ALPHA) * DEST */
  11783. get: function () {
  11784. return Engine._ALPHA_COMBINE;
  11785. },
  11786. enumerable: true,
  11787. configurable: true
  11788. });
  11789. Object.defineProperty(Engine, "ALPHA_SUBTRACT", {
  11790. /** Defines that alpha blending to DEST - SRC * DEST */
  11791. get: function () {
  11792. return Engine._ALPHA_SUBTRACT;
  11793. },
  11794. enumerable: true,
  11795. configurable: true
  11796. });
  11797. Object.defineProperty(Engine, "ALPHA_MULTIPLY", {
  11798. /** Defines that alpha blending to SRC * DEST */
  11799. get: function () {
  11800. return Engine._ALPHA_MULTIPLY;
  11801. },
  11802. enumerable: true,
  11803. configurable: true
  11804. });
  11805. Object.defineProperty(Engine, "ALPHA_MAXIMIZED", {
  11806. /** Defines that alpha blending to SRC ALPHA * SRC + (1 - SRC) * DEST */
  11807. get: function () {
  11808. return Engine._ALPHA_MAXIMIZED;
  11809. },
  11810. enumerable: true,
  11811. configurable: true
  11812. });
  11813. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED", {
  11814. /** Defines that alpha blending to SRC + (1 - SRC ALPHA) * DEST */
  11815. get: function () {
  11816. return Engine._ALPHA_PREMULTIPLIED;
  11817. },
  11818. enumerable: true,
  11819. configurable: true
  11820. });
  11821. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED_PORTERDUFF", {
  11822. /**
  11823. * Defines that alpha blending to SRC + (1 - SRC ALPHA) * DEST
  11824. * Alpha will be set to (1 - SRC ALPHA) * DEST ALPHA
  11825. */
  11826. get: function () {
  11827. return Engine._ALPHA_PREMULTIPLIED_PORTERDUFF;
  11828. },
  11829. enumerable: true,
  11830. configurable: true
  11831. });
  11832. Object.defineProperty(Engine, "ALPHA_INTERPOLATE", {
  11833. /** Defines that alpha blending to CST * SRC + (1 - CST) * DEST */
  11834. get: function () {
  11835. return Engine._ALPHA_INTERPOLATE;
  11836. },
  11837. enumerable: true,
  11838. configurable: true
  11839. });
  11840. Object.defineProperty(Engine, "ALPHA_SCREENMODE", {
  11841. /**
  11842. * Defines that alpha blending to SRC + (1 - SRC) * DEST
  11843. * Alpha will be set to SRC ALPHA + (1 - SRC ALPHA) * DEST ALPHA
  11844. */
  11845. get: function () {
  11846. return Engine._ALPHA_SCREENMODE;
  11847. },
  11848. enumerable: true,
  11849. configurable: true
  11850. });
  11851. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  11852. // Delays
  11853. /** Defines that the ressource is not delayed*/
  11854. get: function () {
  11855. return Engine._DELAYLOADSTATE_NONE;
  11856. },
  11857. enumerable: true,
  11858. configurable: true
  11859. });
  11860. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  11861. /** Defines that the ressource was successfully delay loaded */
  11862. get: function () {
  11863. return Engine._DELAYLOADSTATE_LOADED;
  11864. },
  11865. enumerable: true,
  11866. configurable: true
  11867. });
  11868. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  11869. /** Defines that the ressource is currently delay loading */
  11870. get: function () {
  11871. return Engine._DELAYLOADSTATE_LOADING;
  11872. },
  11873. enumerable: true,
  11874. configurable: true
  11875. });
  11876. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  11877. /** Defines that the ressource is delayed and has not started loading */
  11878. get: function () {
  11879. return Engine._DELAYLOADSTATE_NOTLOADED;
  11880. },
  11881. enumerable: true,
  11882. configurable: true
  11883. });
  11884. Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
  11885. /** ALPHA */
  11886. get: function () {
  11887. return Engine._TEXTUREFORMAT_ALPHA;
  11888. },
  11889. enumerable: true,
  11890. configurable: true
  11891. });
  11892. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
  11893. /** LUMINANCE */
  11894. get: function () {
  11895. return Engine._TEXTUREFORMAT_LUMINANCE;
  11896. },
  11897. enumerable: true,
  11898. configurable: true
  11899. });
  11900. Object.defineProperty(Engine, "TEXTUREFORMAT_R", {
  11901. /**
  11902. * R
  11903. */
  11904. get: function () {
  11905. return Engine._TEXTUREFORMAT_R;
  11906. },
  11907. enumerable: true,
  11908. configurable: true
  11909. });
  11910. Object.defineProperty(Engine, "TEXTUREFORMAT_RG", {
  11911. /**
  11912. * RG
  11913. */
  11914. get: function () {
  11915. return Engine._TEXTUREFORMAT_RG;
  11916. },
  11917. enumerable: true,
  11918. configurable: true
  11919. });
  11920. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
  11921. /** LUMINANCE_ALPHA */
  11922. get: function () {
  11923. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  11924. },
  11925. enumerable: true,
  11926. configurable: true
  11927. });
  11928. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
  11929. /** RGB */
  11930. get: function () {
  11931. return Engine._TEXTUREFORMAT_RGB;
  11932. },
  11933. enumerable: true,
  11934. configurable: true
  11935. });
  11936. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
  11937. /** RGBA */
  11938. get: function () {
  11939. return Engine._TEXTUREFORMAT_RGBA;
  11940. },
  11941. enumerable: true,
  11942. configurable: true
  11943. });
  11944. Object.defineProperty(Engine, "TEXTURETYPE_UNSIGNED_INT", {
  11945. /** UNSIGNED_INT */
  11946. get: function () {
  11947. return Engine._TEXTURETYPE_UNSIGNED_INT;
  11948. },
  11949. enumerable: true,
  11950. configurable: true
  11951. });
  11952. Object.defineProperty(Engine, "TEXTURETYPE_FLOAT", {
  11953. /** FLOAT */
  11954. get: function () {
  11955. return Engine._TEXTURETYPE_FLOAT;
  11956. },
  11957. enumerable: true,
  11958. configurable: true
  11959. });
  11960. Object.defineProperty(Engine, "TEXTURETYPE_HALF_FLOAT", {
  11961. /** HALF_FLOAT */
  11962. get: function () {
  11963. return Engine._TEXTURETYPE_HALF_FLOAT;
  11964. },
  11965. enumerable: true,
  11966. configurable: true
  11967. });
  11968. Object.defineProperty(Engine, "SCALEMODE_FLOOR", {
  11969. /** Defines that texture rescaling will use a floor to find the closer power of 2 size */
  11970. get: function () {
  11971. return Engine._SCALEMODE_FLOOR;
  11972. },
  11973. enumerable: true,
  11974. configurable: true
  11975. });
  11976. Object.defineProperty(Engine, "SCALEMODE_NEAREST", {
  11977. /** Defines that texture rescaling will look for the nearest power of 2 size */
  11978. get: function () {
  11979. return Engine._SCALEMODE_NEAREST;
  11980. },
  11981. enumerable: true,
  11982. configurable: true
  11983. });
  11984. Object.defineProperty(Engine, "SCALEMODE_CEILING", {
  11985. /** Defines that texture rescaling will use a ceil to find the closer power of 2 size */
  11986. get: function () {
  11987. return Engine._SCALEMODE_CEILING;
  11988. },
  11989. enumerable: true,
  11990. configurable: true
  11991. });
  11992. Object.defineProperty(Engine, "Version", {
  11993. /**
  11994. * Returns the current version of the framework
  11995. */
  11996. get: function () {
  11997. return "3.3.0-alpha.2";
  11998. },
  11999. enumerable: true,
  12000. configurable: true
  12001. });
  12002. Object.defineProperty(Engine.prototype, "isInVRExclusivePointerMode", {
  12003. /**
  12004. * Gets a boolean indicating that the engine is currently in VR exclusive mode for the pointers
  12005. * @see https://docs.microsoft.com/en-us/microsoft-edge/webvr/essentials#mouse-input
  12006. */
  12007. get: function () {
  12008. return this._vrExclusivePointerMode;
  12009. },
  12010. enumerable: true,
  12011. configurable: true
  12012. });
  12013. Object.defineProperty(Engine.prototype, "supportsUniformBuffers", {
  12014. /**
  12015. * Gets a boolean indicating that the engine supports uniform buffers
  12016. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  12017. */
  12018. get: function () {
  12019. return this.webGLVersion > 1 && !this.disableUniformBuffers;
  12020. },
  12021. enumerable: true,
  12022. configurable: true
  12023. });
  12024. Object.defineProperty(Engine.prototype, "needPOTTextures", {
  12025. /**
  12026. * Gets a boolean indicating that only power of 2 textures are supported
  12027. * Please note that you can still use non power of 2 textures but in this case the engine will forcefully convert them
  12028. */
  12029. get: function () {
  12030. return this._webGLVersion < 2 || this.forcePOTTextures;
  12031. },
  12032. enumerable: true,
  12033. configurable: true
  12034. });
  12035. Object.defineProperty(Engine.prototype, "doNotHandleContextLost", {
  12036. /**
  12037. * Gets or sets a boolean indicating if resources should be retained to be able to handle context lost events
  12038. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#handling-webgl-context-lost
  12039. */
  12040. get: function () {
  12041. return this._doNotHandleContextLost;
  12042. },
  12043. set: function (value) {
  12044. this._doNotHandleContextLost = value;
  12045. },
  12046. enumerable: true,
  12047. configurable: true
  12048. });
  12049. Object.defineProperty(Engine.prototype, "performanceMonitor", {
  12050. /**
  12051. * Gets the performance monitor attached to this engine
  12052. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#engineinstrumentation
  12053. */
  12054. get: function () {
  12055. return this._performanceMonitor;
  12056. },
  12057. enumerable: true,
  12058. configurable: true
  12059. });
  12060. Object.defineProperty(Engine.prototype, "texturesSupported", {
  12061. /**
  12062. * Gets the list of texture formats supported
  12063. */
  12064. get: function () {
  12065. return this._texturesSupported;
  12066. },
  12067. enumerable: true,
  12068. configurable: true
  12069. });
  12070. Object.defineProperty(Engine.prototype, "textureFormatInUse", {
  12071. /**
  12072. * Gets the list of texture formats in use
  12073. */
  12074. get: function () {
  12075. return this._textureFormatInUse;
  12076. },
  12077. enumerable: true,
  12078. configurable: true
  12079. });
  12080. Object.defineProperty(Engine.prototype, "currentViewport", {
  12081. /**
  12082. * Gets the current viewport
  12083. */
  12084. get: function () {
  12085. return this._cachedViewport;
  12086. },
  12087. enumerable: true,
  12088. configurable: true
  12089. });
  12090. Object.defineProperty(Engine.prototype, "emptyTexture", {
  12091. /**
  12092. * Gets the default empty texture
  12093. */
  12094. get: function () {
  12095. if (!this._emptyTexture) {
  12096. this._emptyTexture = this.createRawTexture(new Uint8Array(4), 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  12097. }
  12098. return this._emptyTexture;
  12099. },
  12100. enumerable: true,
  12101. configurable: true
  12102. });
  12103. Object.defineProperty(Engine.prototype, "emptyTexture3D", {
  12104. /**
  12105. * Gets the default empty 3D texture
  12106. */
  12107. get: function () {
  12108. if (!this._emptyTexture3D) {
  12109. this._emptyTexture3D = this.createRawTexture3D(new Uint8Array(4), 1, 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  12110. }
  12111. return this._emptyTexture3D;
  12112. },
  12113. enumerable: true,
  12114. configurable: true
  12115. });
  12116. Object.defineProperty(Engine.prototype, "emptyCubeTexture", {
  12117. /**
  12118. * Gets the default empty cube texture
  12119. */
  12120. get: function () {
  12121. if (!this._emptyCubeTexture) {
  12122. var faceData = new Uint8Array(4);
  12123. var cubeData = [faceData, faceData, faceData, faceData, faceData, faceData];
  12124. this._emptyCubeTexture = this.createRawCubeTexture(cubeData, 1, Engine.TEXTUREFORMAT_RGBA, Engine.TEXTURETYPE_UNSIGNED_INT, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  12125. }
  12126. return this._emptyCubeTexture;
  12127. },
  12128. enumerable: true,
  12129. configurable: true
  12130. });
  12131. Engine.prototype._rebuildInternalTextures = function () {
  12132. var currentState = this._internalTexturesCache.slice(); // Do a copy because the rebuild will add proxies
  12133. for (var _i = 0, currentState_1 = currentState; _i < currentState_1.length; _i++) {
  12134. var internalTexture = currentState_1[_i];
  12135. internalTexture._rebuild();
  12136. }
  12137. };
  12138. Engine.prototype._rebuildEffects = function () {
  12139. for (var key in this._compiledEffects) {
  12140. var effect = this._compiledEffects[key];
  12141. effect._prepareEffect();
  12142. }
  12143. BABYLON.Effect.ResetCache();
  12144. };
  12145. Engine.prototype._rebuildBuffers = function () {
  12146. // Index / Vertex
  12147. for (var _i = 0, _a = this.scenes; _i < _a.length; _i++) {
  12148. var scene = _a[_i];
  12149. scene.resetCachedMaterial();
  12150. scene._rebuildGeometries();
  12151. scene._rebuildTextures();
  12152. }
  12153. // Uniforms
  12154. for (var _b = 0, _c = this._uniformBuffers; _b < _c.length; _b++) {
  12155. var uniformBuffer = _c[_b];
  12156. uniformBuffer._rebuild();
  12157. }
  12158. };
  12159. Engine.prototype._initGLContext = function () {
  12160. // Caps
  12161. this._caps = new EngineCapabilities();
  12162. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  12163. this._caps.maxCombinedTexturesImageUnits = this._gl.getParameter(this._gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS);
  12164. this._caps.maxVertexTextureImageUnits = this._gl.getParameter(this._gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS);
  12165. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  12166. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  12167. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  12168. this._caps.maxVertexAttribs = this._gl.getParameter(this._gl.MAX_VERTEX_ATTRIBS);
  12169. this._caps.maxVaryingVectors = this._gl.getParameter(this._gl.MAX_VARYING_VECTORS);
  12170. this._caps.maxFragmentUniformVectors = this._gl.getParameter(this._gl.MAX_FRAGMENT_UNIFORM_VECTORS);
  12171. this._caps.maxVertexUniformVectors = this._gl.getParameter(this._gl.MAX_VERTEX_UNIFORM_VECTORS);
  12172. // Infos
  12173. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  12174. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  12175. if (rendererInfo != null) {
  12176. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  12177. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  12178. }
  12179. if (!this._glVendor) {
  12180. this._glVendor = "Unknown vendor";
  12181. }
  12182. if (!this._glRenderer) {
  12183. this._glRenderer = "Unknown renderer";
  12184. }
  12185. // Constants
  12186. this._gl.HALF_FLOAT_OES = 0x8D61; // Half floating-point type (16-bit).
  12187. if (this._gl.RGBA16F !== 0x881A) {
  12188. this._gl.RGBA16F = 0x881A; // RGBA 16-bit floating-point color-renderable internal sized format.
  12189. }
  12190. if (this._gl.RGBA32F !== 0x8814) {
  12191. this._gl.RGBA32F = 0x8814; // RGBA 32-bit floating-point color-renderable internal sized format.
  12192. }
  12193. if (this._gl.DEPTH24_STENCIL8 !== 35056) {
  12194. this._gl.DEPTH24_STENCIL8 = 35056;
  12195. }
  12196. // Extensions
  12197. this._caps.standardDerivatives = this._webGLVersion > 1 || (this._gl.getExtension('OES_standard_derivatives') !== null);
  12198. this._caps.astc = this._gl.getExtension('WEBGL_compressed_texture_astc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_astc');
  12199. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_s3tc');
  12200. this._caps.pvrtc = this._gl.getExtension('WEBGL_compressed_texture_pvrtc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc');
  12201. this._caps.etc1 = this._gl.getExtension('WEBGL_compressed_texture_etc1') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc1');
  12202. this._caps.etc2 = this._gl.getExtension('WEBGL_compressed_texture_etc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc') ||
  12203. this._gl.getExtension('WEBGL_compressed_texture_es3_0'); // also a requirement of OpenGL ES 3
  12204. 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');
  12205. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  12206. this._caps.uintIndices = this._webGLVersion > 1 || this._gl.getExtension('OES_element_index_uint') !== null;
  12207. this._caps.fragmentDepthSupported = this._webGLVersion > 1 || this._gl.getExtension('EXT_frag_depth') !== null;
  12208. this._caps.highPrecisionShaderSupported = true;
  12209. this._caps.timerQuery = this._gl.getExtension('EXT_disjoint_timer_query_webgl2') || this._gl.getExtension("EXT_disjoint_timer_query");
  12210. if (this._caps.timerQuery) {
  12211. if (this._webGLVersion === 1) {
  12212. this._gl.getQuery = this._caps.timerQuery.getQueryEXT.bind(this._caps.timerQuery);
  12213. }
  12214. this._caps.canUseTimestampForTimerQuery = this._gl.getQuery(this._caps.timerQuery.TIMESTAMP_EXT, this._caps.timerQuery.QUERY_COUNTER_BITS_EXT) > 0;
  12215. }
  12216. // Checks if some of the format renders first to allow the use of webgl inspector.
  12217. this._caps.colorBufferFloat = this._webGLVersion > 1 && this._gl.getExtension('EXT_color_buffer_float');
  12218. this._caps.textureFloat = (this._webGLVersion > 1 || this._gl.getExtension('OES_texture_float')) ? true : false;
  12219. this._caps.textureFloatLinearFiltering = this._caps.textureFloat && this._gl.getExtension('OES_texture_float_linear') ? true : false;
  12220. this._caps.textureFloatRender = this._caps.textureFloat && this._canRenderToFloatFramebuffer() ? true : false;
  12221. this._caps.textureHalfFloat = (this._webGLVersion > 1 || this._gl.getExtension('OES_texture_half_float')) ? true : false;
  12222. this._caps.textureHalfFloatLinearFiltering = (this._webGLVersion > 1 || (this._caps.textureHalfFloat && this._gl.getExtension('OES_texture_half_float_linear'))) ? true : false;
  12223. if (this._webGLVersion > 1) {
  12224. this._gl.HALF_FLOAT_OES = 0x140B;
  12225. }
  12226. this._caps.textureHalfFloatRender = this._caps.textureHalfFloat && this._canRenderToHalfFloatFramebuffer();
  12227. this._caps.textureLOD = (this._webGLVersion > 1 || this._gl.getExtension('EXT_shader_texture_lod')) ? true : false;
  12228. // Draw buffers
  12229. if (this._webGLVersion > 1) {
  12230. this._caps.drawBuffersExtension = true;
  12231. }
  12232. else {
  12233. var drawBuffersExtension = this._gl.getExtension('WEBGL_draw_buffers');
  12234. if (drawBuffersExtension !== null) {
  12235. this._caps.drawBuffersExtension = true;
  12236. this._gl.drawBuffers = drawBuffersExtension.drawBuffersWEBGL.bind(drawBuffersExtension);
  12237. this._gl.DRAW_FRAMEBUFFER = this._gl.FRAMEBUFFER;
  12238. for (var i = 0; i < 16; i++) {
  12239. this._gl["COLOR_ATTACHMENT" + i + "_WEBGL"] = drawBuffersExtension["COLOR_ATTACHMENT" + i + "_WEBGL"];
  12240. }
  12241. }
  12242. else {
  12243. this._caps.drawBuffersExtension = false;
  12244. }
  12245. }
  12246. // Depth Texture
  12247. if (this._webGLVersion > 1) {
  12248. this._caps.depthTextureExtension = true;
  12249. }
  12250. else {
  12251. var depthTextureExtension = this._gl.getExtension('WEBGL_depth_texture');
  12252. if (depthTextureExtension != null) {
  12253. this._caps.depthTextureExtension = true;
  12254. this._gl.UNSIGNED_INT_24_8 = depthTextureExtension.UNSIGNED_INT_24_8_WEBGL;
  12255. }
  12256. }
  12257. // Vertex array object
  12258. if (this._webGLVersion > 1) {
  12259. this._caps.vertexArrayObject = true;
  12260. }
  12261. else {
  12262. var vertexArrayObjectExtension = this._gl.getExtension('OES_vertex_array_object');
  12263. if (vertexArrayObjectExtension != null) {
  12264. this._caps.vertexArrayObject = true;
  12265. this._gl.createVertexArray = vertexArrayObjectExtension.createVertexArrayOES.bind(vertexArrayObjectExtension);
  12266. this._gl.bindVertexArray = vertexArrayObjectExtension.bindVertexArrayOES.bind(vertexArrayObjectExtension);
  12267. this._gl.deleteVertexArray = vertexArrayObjectExtension.deleteVertexArrayOES.bind(vertexArrayObjectExtension);
  12268. }
  12269. else {
  12270. this._caps.vertexArrayObject = false;
  12271. }
  12272. }
  12273. // Instances count
  12274. if (this._webGLVersion > 1) {
  12275. this._caps.instancedArrays = true;
  12276. }
  12277. else {
  12278. var instanceExtension = this._gl.getExtension('ANGLE_instanced_arrays');
  12279. if (instanceExtension != null) {
  12280. this._caps.instancedArrays = true;
  12281. this._gl.drawArraysInstanced = instanceExtension.drawArraysInstancedANGLE.bind(instanceExtension);
  12282. this._gl.drawElementsInstanced = instanceExtension.drawElementsInstancedANGLE.bind(instanceExtension);
  12283. this._gl.vertexAttribDivisor = instanceExtension.vertexAttribDivisorANGLE.bind(instanceExtension);
  12284. }
  12285. else {
  12286. this._caps.instancedArrays = false;
  12287. }
  12288. }
  12289. // Intelligently add supported compressed formats in order to check for.
  12290. // Check for ASTC support first as it is most powerful and to be very cross platform.
  12291. // Next PVRTC & DXT, which are probably superior to ETC1/2.
  12292. // Likely no hardware which supports both PVR & DXT, so order matters little.
  12293. // ETC2 is newer and handles ETC1 (no alpha capability), so check for first.
  12294. if (this._caps.astc)
  12295. this.texturesSupported.push('-astc.ktx');
  12296. if (this._caps.s3tc)
  12297. this.texturesSupported.push('-dxt.ktx');
  12298. if (this._caps.pvrtc)
  12299. this.texturesSupported.push('-pvrtc.ktx');
  12300. if (this._caps.etc2)
  12301. this.texturesSupported.push('-etc2.ktx');
  12302. if (this._caps.etc1)
  12303. this.texturesSupported.push('-etc1.ktx');
  12304. if (this._gl.getShaderPrecisionFormat) {
  12305. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  12306. if (highp) {
  12307. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  12308. }
  12309. }
  12310. // Depth buffer
  12311. this.setDepthBuffer(true);
  12312. this.setDepthFunctionToLessOrEqual();
  12313. this.setDepthWrite(true);
  12314. // Texture maps
  12315. this._maxSimultaneousTextures = this._caps.maxCombinedTexturesImageUnits;
  12316. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  12317. this._nextFreeTextureSlots.push(slot);
  12318. }
  12319. };
  12320. Object.defineProperty(Engine.prototype, "webGLVersion", {
  12321. /**
  12322. * Gets version of the current webGL context
  12323. */
  12324. get: function () {
  12325. return this._webGLVersion;
  12326. },
  12327. enumerable: true,
  12328. configurable: true
  12329. });
  12330. Object.defineProperty(Engine.prototype, "isStencilEnable", {
  12331. /**
  12332. * Returns true if the stencil buffer has been enabled through the creation option of the context.
  12333. */
  12334. get: function () {
  12335. return this._isStencilEnable;
  12336. },
  12337. enumerable: true,
  12338. configurable: true
  12339. });
  12340. Engine.prototype._prepareWorkingCanvas = function () {
  12341. if (this._workingCanvas) {
  12342. return;
  12343. }
  12344. this._workingCanvas = document.createElement("canvas");
  12345. var context = this._workingCanvas.getContext("2d");
  12346. if (context) {
  12347. this._workingContext = context;
  12348. }
  12349. };
  12350. /**
  12351. * Reset the texture cache to empty state
  12352. */
  12353. Engine.prototype.resetTextureCache = function () {
  12354. for (var key in this._boundTexturesCache) {
  12355. if (!this._boundTexturesCache.hasOwnProperty(key)) {
  12356. continue;
  12357. }
  12358. var boundTexture = this._boundTexturesCache[key];
  12359. if (boundTexture) {
  12360. this._removeDesignatedSlot(boundTexture);
  12361. }
  12362. this._boundTexturesCache[key] = null;
  12363. }
  12364. if (!this.disableTextureBindingOptimization) {
  12365. this._nextFreeTextureSlots = [];
  12366. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  12367. this._nextFreeTextureSlots.push(slot);
  12368. }
  12369. }
  12370. this._currentTextureChannel = -1;
  12371. };
  12372. /**
  12373. * Gets a boolean indicating that the engine is running in deterministic lock step mode
  12374. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  12375. * @returns true if engine is in deterministic lock step mode
  12376. */
  12377. Engine.prototype.isDeterministicLockStep = function () {
  12378. return this._deterministicLockstep;
  12379. };
  12380. /**
  12381. * Gets the max steps when engine is running in deterministic lock step
  12382. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  12383. * @returns the max steps
  12384. */
  12385. Engine.prototype.getLockstepMaxSteps = function () {
  12386. return this._lockstepMaxSteps;
  12387. };
  12388. /**
  12389. * Gets an object containing information about the current webGL context
  12390. * @returns an object containing the vender, the renderer and the version of the current webGL context
  12391. */
  12392. Engine.prototype.getGlInfo = function () {
  12393. return {
  12394. vendor: this._glVendor,
  12395. renderer: this._glRenderer,
  12396. version: this._glVersion
  12397. };
  12398. };
  12399. /**
  12400. * Gets current aspect ratio
  12401. * @param camera defines the camera to use to get the aspect ratio
  12402. * @param useScreen defines if screen size must be used (or the current render target if any)
  12403. * @returns a number defining the aspect ratio
  12404. */
  12405. Engine.prototype.getAspectRatio = function (camera, useScreen) {
  12406. if (useScreen === void 0) { useScreen = false; }
  12407. var viewport = camera.viewport;
  12408. return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
  12409. };
  12410. /**
  12411. * Gets current screen aspect ratio
  12412. * @returns a number defining the aspect ratio
  12413. */
  12414. Engine.prototype.getScreenAspectRatio = function () {
  12415. return (this.getRenderWidth(true)) / (this.getRenderHeight(true));
  12416. };
  12417. /**
  12418. * Gets the current render width
  12419. * @param useScreen defines if screen size must be used (or the current render target if any)
  12420. * @returns a number defining the current render width
  12421. */
  12422. Engine.prototype.getRenderWidth = function (useScreen) {
  12423. if (useScreen === void 0) { useScreen = false; }
  12424. if (!useScreen && this._currentRenderTarget) {
  12425. return this._currentRenderTarget.width;
  12426. }
  12427. return this._gl.drawingBufferWidth;
  12428. };
  12429. /**
  12430. * Gets the current render height
  12431. * @param useScreen defines if screen size must be used (or the current render target if any)
  12432. * @returns a number defining the current render height
  12433. */
  12434. Engine.prototype.getRenderHeight = function (useScreen) {
  12435. if (useScreen === void 0) { useScreen = false; }
  12436. if (!useScreen && this._currentRenderTarget) {
  12437. return this._currentRenderTarget.height;
  12438. }
  12439. return this._gl.drawingBufferHeight;
  12440. };
  12441. /**
  12442. * Gets the HTML canvas attached with the current webGL context
  12443. * @returns a HTML canvas
  12444. */
  12445. Engine.prototype.getRenderingCanvas = function () {
  12446. return this._renderingCanvas;
  12447. };
  12448. /**
  12449. * Gets the client rect of the HTML canvas attached with the current webGL context
  12450. * @returns a client rectanglee
  12451. */
  12452. Engine.prototype.getRenderingCanvasClientRect = function () {
  12453. if (!this._renderingCanvas) {
  12454. return null;
  12455. }
  12456. return this._renderingCanvas.getBoundingClientRect();
  12457. };
  12458. /**
  12459. * Defines the hardware scaling level.
  12460. * By default the hardware scaling level is computed from the window device ratio.
  12461. * 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.
  12462. * @param level defines the level to use
  12463. */
  12464. Engine.prototype.setHardwareScalingLevel = function (level) {
  12465. this._hardwareScalingLevel = level;
  12466. this.resize();
  12467. };
  12468. /**
  12469. * Gets the current hardware scaling level.
  12470. * By default the hardware scaling level is computed from the window device ratio.
  12471. * 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.
  12472. * @returns a number indicating the current hardware scaling level
  12473. */
  12474. Engine.prototype.getHardwareScalingLevel = function () {
  12475. return this._hardwareScalingLevel;
  12476. };
  12477. /**
  12478. * Gets the list of loaded textures
  12479. * @returns an array containing all loaded textures
  12480. */
  12481. Engine.prototype.getLoadedTexturesCache = function () {
  12482. return this._internalTexturesCache;
  12483. };
  12484. /**
  12485. * Gets the object containing all engine capabilities
  12486. * @returns the EngineCapabilities object
  12487. */
  12488. Engine.prototype.getCaps = function () {
  12489. return this._caps;
  12490. };
  12491. Object.defineProperty(Engine.prototype, "drawCalls", {
  12492. /** @hidden */
  12493. get: function () {
  12494. BABYLON.Tools.Warn("drawCalls is deprecated. Please use SceneInstrumentation class");
  12495. return 0;
  12496. },
  12497. enumerable: true,
  12498. configurable: true
  12499. });
  12500. Object.defineProperty(Engine.prototype, "drawCallsPerfCounter", {
  12501. /** @hidden */
  12502. get: function () {
  12503. BABYLON.Tools.Warn("drawCallsPerfCounter is deprecated. Please use SceneInstrumentation class");
  12504. return null;
  12505. },
  12506. enumerable: true,
  12507. configurable: true
  12508. });
  12509. /**
  12510. * Gets the current depth function
  12511. * @returns a number defining the depth function
  12512. */
  12513. Engine.prototype.getDepthFunction = function () {
  12514. return this._depthCullingState.depthFunc;
  12515. };
  12516. /**
  12517. * Sets the current depth function
  12518. * @param depthFunc defines the function to use
  12519. */
  12520. Engine.prototype.setDepthFunction = function (depthFunc) {
  12521. this._depthCullingState.depthFunc = depthFunc;
  12522. };
  12523. /**
  12524. * Sets the current depth function to GREATER
  12525. */
  12526. Engine.prototype.setDepthFunctionToGreater = function () {
  12527. this._depthCullingState.depthFunc = this._gl.GREATER;
  12528. };
  12529. /**
  12530. * Sets the current depth function to GEQUAL
  12531. */
  12532. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  12533. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  12534. };
  12535. /**
  12536. * Sets the current depth function to LESS
  12537. */
  12538. Engine.prototype.setDepthFunctionToLess = function () {
  12539. this._depthCullingState.depthFunc = this._gl.LESS;
  12540. };
  12541. /**
  12542. * Sets the current depth function to LEQUAL
  12543. */
  12544. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  12545. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  12546. };
  12547. /**
  12548. * Gets a boolean indicating if stencil buffer is enabled
  12549. * @returns the current stencil buffer state
  12550. */
  12551. Engine.prototype.getStencilBuffer = function () {
  12552. return this._stencilState.stencilTest;
  12553. };
  12554. /**
  12555. * Enable or disable the stencil buffer
  12556. * @param enable defines if the stencil buffer must be enabled or disabled
  12557. */
  12558. Engine.prototype.setStencilBuffer = function (enable) {
  12559. this._stencilState.stencilTest = enable;
  12560. };
  12561. /**
  12562. * Gets the current stencil mask
  12563. * @returns a number defining the new stencil mask to use
  12564. */
  12565. Engine.prototype.getStencilMask = function () {
  12566. return this._stencilState.stencilMask;
  12567. };
  12568. /**
  12569. * Sets the current stencil mask
  12570. * @param mask defines the new stencil mask to use
  12571. */
  12572. Engine.prototype.setStencilMask = function (mask) {
  12573. this._stencilState.stencilMask = mask;
  12574. };
  12575. /**
  12576. * Gets the current stencil function
  12577. * @returns a number defining the stencil function to use
  12578. */
  12579. Engine.prototype.getStencilFunction = function () {
  12580. return this._stencilState.stencilFunc;
  12581. };
  12582. /**
  12583. * Gets the current stencil reference value
  12584. * @returns a number defining the stencil reference value to use
  12585. */
  12586. Engine.prototype.getStencilFunctionReference = function () {
  12587. return this._stencilState.stencilFuncRef;
  12588. };
  12589. /**
  12590. * Gets the current stencil mask
  12591. * @returns a number defining the stencil mask to use
  12592. */
  12593. Engine.prototype.getStencilFunctionMask = function () {
  12594. return this._stencilState.stencilFuncMask;
  12595. };
  12596. /**
  12597. * Sets the current stencil function
  12598. * @param stencilFunc defines the new stencil function to use
  12599. */
  12600. Engine.prototype.setStencilFunction = function (stencilFunc) {
  12601. this._stencilState.stencilFunc = stencilFunc;
  12602. };
  12603. /**
  12604. * Sets the current stencil reference
  12605. * @param reference defines the new stencil reference to use
  12606. */
  12607. Engine.prototype.setStencilFunctionReference = function (reference) {
  12608. this._stencilState.stencilFuncRef = reference;
  12609. };
  12610. /**
  12611. * Sets the current stencil mask
  12612. * @param mask defines the new stencil mask to use
  12613. */
  12614. Engine.prototype.setStencilFunctionMask = function (mask) {
  12615. this._stencilState.stencilFuncMask = mask;
  12616. };
  12617. /**
  12618. * Gets the current stencil operation when stencil fails
  12619. * @returns a number defining stencil operation to use when stencil fails
  12620. */
  12621. Engine.prototype.getStencilOperationFail = function () {
  12622. return this._stencilState.stencilOpStencilFail;
  12623. };
  12624. /**
  12625. * Gets the current stencil operation when depth fails
  12626. * @returns a number defining stencil operation to use when depth fails
  12627. */
  12628. Engine.prototype.getStencilOperationDepthFail = function () {
  12629. return this._stencilState.stencilOpDepthFail;
  12630. };
  12631. /**
  12632. * Gets the current stencil operation when stencil passes
  12633. * @returns a number defining stencil operation to use when stencil passes
  12634. */
  12635. Engine.prototype.getStencilOperationPass = function () {
  12636. return this._stencilState.stencilOpStencilDepthPass;
  12637. };
  12638. /**
  12639. * Sets the stencil operation to use when stencil fails
  12640. * @param operation defines the stencil operation to use when stencil fails
  12641. */
  12642. Engine.prototype.setStencilOperationFail = function (operation) {
  12643. this._stencilState.stencilOpStencilFail = operation;
  12644. };
  12645. /**
  12646. * Sets the stencil operation to use when depth fails
  12647. * @param operation defines the stencil operation to use when depth fails
  12648. */
  12649. Engine.prototype.setStencilOperationDepthFail = function (operation) {
  12650. this._stencilState.stencilOpDepthFail = operation;
  12651. };
  12652. /**
  12653. * Sets the stencil operation to use when stencil passes
  12654. * @param operation defines the stencil operation to use when stencil passes
  12655. */
  12656. Engine.prototype.setStencilOperationPass = function (operation) {
  12657. this._stencilState.stencilOpStencilDepthPass = operation;
  12658. };
  12659. /**
  12660. * Sets a boolean indicating if the dithering state is enabled or disabled
  12661. * @param value defines the dithering state
  12662. */
  12663. Engine.prototype.setDitheringState = function (value) {
  12664. if (value) {
  12665. this._gl.enable(this._gl.DITHER);
  12666. }
  12667. else {
  12668. this._gl.disable(this._gl.DITHER);
  12669. }
  12670. };
  12671. /**
  12672. * Sets a boolean indicating if the rasterizer state is enabled or disabled
  12673. * @param value defines the rasterizer state
  12674. */
  12675. Engine.prototype.setRasterizerState = function (value) {
  12676. if (value) {
  12677. this._gl.disable(this._gl.RASTERIZER_DISCARD);
  12678. }
  12679. else {
  12680. this._gl.enable(this._gl.RASTERIZER_DISCARD);
  12681. }
  12682. };
  12683. /**
  12684. * stop executing a render loop function and remove it from the execution array
  12685. * @param renderFunction defines the function to be removed. If not provided all functions will be removed.
  12686. */
  12687. Engine.prototype.stopRenderLoop = function (renderFunction) {
  12688. if (!renderFunction) {
  12689. this._activeRenderLoops = [];
  12690. return;
  12691. }
  12692. var index = this._activeRenderLoops.indexOf(renderFunction);
  12693. if (index >= 0) {
  12694. this._activeRenderLoops.splice(index, 1);
  12695. }
  12696. };
  12697. /** @hidden */
  12698. Engine.prototype._renderLoop = function () {
  12699. if (!this._contextWasLost) {
  12700. var shouldRender = true;
  12701. if (!this.renderEvenInBackground && this._windowIsBackground) {
  12702. shouldRender = false;
  12703. }
  12704. if (shouldRender) {
  12705. // Start new frame
  12706. this.beginFrame();
  12707. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  12708. var renderFunction = this._activeRenderLoops[index];
  12709. renderFunction();
  12710. }
  12711. // Present
  12712. this.endFrame();
  12713. }
  12714. }
  12715. if (this._activeRenderLoops.length > 0) {
  12716. // Register new frame
  12717. var requester = null;
  12718. if (this._vrDisplay && this._vrDisplay.isPresenting)
  12719. requester = this._vrDisplay;
  12720. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction, requester);
  12721. }
  12722. else {
  12723. this._renderingQueueLaunched = false;
  12724. }
  12725. };
  12726. /**
  12727. * Register and execute a render loop. The engine can have more than one render function
  12728. * @param renderFunction defines the function to continuously execute
  12729. */
  12730. Engine.prototype.runRenderLoop = function (renderFunction) {
  12731. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  12732. return;
  12733. }
  12734. this._activeRenderLoops.push(renderFunction);
  12735. if (!this._renderingQueueLaunched) {
  12736. this._renderingQueueLaunched = true;
  12737. this._bindedRenderFunction = this._renderLoop.bind(this);
  12738. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  12739. }
  12740. };
  12741. /**
  12742. * Toggle full screen mode
  12743. * @param requestPointerLock defines if a pointer lock should be requested from the user
  12744. * @param options defines an option object to be sent to the requestFullscreen function
  12745. */
  12746. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  12747. if (this.isFullscreen) {
  12748. BABYLON.Tools.ExitFullscreen();
  12749. }
  12750. else {
  12751. this._pointerLockRequested = requestPointerLock;
  12752. if (this._renderingCanvas) {
  12753. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  12754. }
  12755. }
  12756. };
  12757. /**
  12758. * Clear the current render buffer or the current render target (if any is set up)
  12759. * @param color defines the color to use
  12760. * @param backBuffer defines if the back buffer must be cleared
  12761. * @param depth defines if the depth buffer must be cleared
  12762. * @param stencil defines if the stencil buffer must be cleared
  12763. */
  12764. Engine.prototype.clear = function (color, backBuffer, depth, stencil) {
  12765. if (stencil === void 0) { stencil = false; }
  12766. this.applyStates();
  12767. var mode = 0;
  12768. if (backBuffer && color) {
  12769. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  12770. mode |= this._gl.COLOR_BUFFER_BIT;
  12771. }
  12772. if (depth) {
  12773. this._gl.clearDepth(1.0);
  12774. mode |= this._gl.DEPTH_BUFFER_BIT;
  12775. }
  12776. if (stencil) {
  12777. this._gl.clearStencil(0);
  12778. mode |= this._gl.STENCIL_BUFFER_BIT;
  12779. }
  12780. this._gl.clear(mode);
  12781. };
  12782. /**
  12783. * Executes a scissor clear (ie. a clear on a specific portion of the screen)
  12784. * @param x defines the x-coordinate of the top left corner of the clear rectangle
  12785. * @param y defines the y-coordinate of the corner of the clear rectangle
  12786. * @param width defines the width of the clear rectangle
  12787. * @param height defines the height of the clear rectangle
  12788. * @param clearColor defines the clear color
  12789. */
  12790. Engine.prototype.scissorClear = function (x, y, width, height, clearColor) {
  12791. var gl = this._gl;
  12792. // Save state
  12793. var curScissor = gl.getParameter(gl.SCISSOR_TEST);
  12794. var curScissorBox = gl.getParameter(gl.SCISSOR_BOX);
  12795. // Change state
  12796. gl.enable(gl.SCISSOR_TEST);
  12797. gl.scissor(x, y, width, height);
  12798. // Clear
  12799. this.clear(clearColor, true, true, true);
  12800. // Restore state
  12801. gl.scissor(curScissorBox[0], curScissorBox[1], curScissorBox[2], curScissorBox[3]);
  12802. if (curScissor === true) {
  12803. gl.enable(gl.SCISSOR_TEST);
  12804. }
  12805. else {
  12806. gl.disable(gl.SCISSOR_TEST);
  12807. }
  12808. };
  12809. /**
  12810. * Set the WebGL's viewport
  12811. * @param viewport defines the viewport element to be used
  12812. * @param requiredWidth defines the width required for rendering. If not provided the rendering canvas' width is used
  12813. * @param requiredHeight defines the height required for rendering. If not provided the rendering canvas' height is used
  12814. */
  12815. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  12816. var width = requiredWidth || this.getRenderWidth();
  12817. var height = requiredHeight || this.getRenderHeight();
  12818. var x = viewport.x || 0;
  12819. var y = viewport.y || 0;
  12820. this._cachedViewport = viewport;
  12821. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  12822. };
  12823. /**
  12824. * Directly set the WebGL Viewport
  12825. * @param x defines the x coordinate of the viewport (in screen space)
  12826. * @param y defines the y coordinate of the viewport (in screen space)
  12827. * @param width defines the width of the viewport (in screen space)
  12828. * @param height defines the height of the viewport (in screen space)
  12829. * @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
  12830. */
  12831. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  12832. var currentViewport = this._cachedViewport;
  12833. this._cachedViewport = null;
  12834. this._gl.viewport(x, y, width, height);
  12835. return currentViewport;
  12836. };
  12837. /**
  12838. * Begin a new frame
  12839. */
  12840. Engine.prototype.beginFrame = function () {
  12841. this.onBeginFrameObservable.notifyObservers(this);
  12842. this._measureFps();
  12843. };
  12844. /**
  12845. * Enf the current frame
  12846. */
  12847. Engine.prototype.endFrame = function () {
  12848. // Force a flush in case we are using a bad OS.
  12849. if (this._badOS) {
  12850. this.flushFramebuffer();
  12851. }
  12852. // Submit frame to the vr device, if enabled
  12853. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  12854. // TODO: We should only submit the frame if we read frameData successfully.
  12855. this._vrDisplay.submitFrame();
  12856. }
  12857. this.onEndFrameObservable.notifyObservers(this);
  12858. };
  12859. /**
  12860. * Resize the view according to the canvas' size
  12861. */
  12862. Engine.prototype.resize = function () {
  12863. // We're not resizing the size of the canvas while in VR mode & presenting
  12864. if (!(this._vrDisplay && this._vrDisplay.isPresenting)) {
  12865. var width = this._renderingCanvas ? this._renderingCanvas.clientWidth : window.innerWidth;
  12866. var height = this._renderingCanvas ? this._renderingCanvas.clientHeight : window.innerHeight;
  12867. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  12868. }
  12869. };
  12870. /**
  12871. * Force a specific size of the canvas
  12872. * @param width defines the new canvas' width
  12873. * @param height defines the new canvas' height
  12874. */
  12875. Engine.prototype.setSize = function (width, height) {
  12876. if (!this._renderingCanvas) {
  12877. return;
  12878. }
  12879. if (this._renderingCanvas.width === width && this._renderingCanvas.height === height) {
  12880. return;
  12881. }
  12882. this._renderingCanvas.width = width;
  12883. this._renderingCanvas.height = height;
  12884. for (var index = 0; index < this.scenes.length; index++) {
  12885. var scene = this.scenes[index];
  12886. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  12887. var cam = scene.cameras[camIndex];
  12888. cam._currentRenderId = 0;
  12889. }
  12890. }
  12891. if (this.onResizeObservable.hasObservers) {
  12892. this.onResizeObservable.notifyObservers(this);
  12893. }
  12894. };
  12895. // WebVR functions
  12896. /**
  12897. * Gets a boolean indicating if a webVR device was detected
  12898. * @returns true if a webVR device was detected
  12899. */
  12900. Engine.prototype.isVRDevicePresent = function () {
  12901. return !!this._vrDisplay;
  12902. };
  12903. /**
  12904. * Gets the current webVR device
  12905. * @returns the current webVR device (or null)
  12906. */
  12907. Engine.prototype.getVRDevice = function () {
  12908. return this._vrDisplay;
  12909. };
  12910. /**
  12911. * Initializes a webVR display and starts listening to display change events
  12912. * The onVRDisplayChangedObservable will be notified upon these changes
  12913. * @returns The onVRDisplayChangedObservable
  12914. */
  12915. Engine.prototype.initWebVR = function () {
  12916. this.initWebVRAsync();
  12917. return this.onVRDisplayChangedObservable;
  12918. };
  12919. /**
  12920. * Initializes a webVR display and starts listening to display change events
  12921. * The onVRDisplayChangedObservable will be notified upon these changes
  12922. * @returns A promise containing a VRDisplay and if vr is supported
  12923. */
  12924. Engine.prototype.initWebVRAsync = function () {
  12925. var _this = this;
  12926. var notifyObservers = function () {
  12927. var eventArgs = {
  12928. vrDisplay: _this._vrDisplay,
  12929. vrSupported: _this._vrSupported
  12930. };
  12931. _this.onVRDisplayChangedObservable.notifyObservers(eventArgs);
  12932. _this._webVRInitPromise = new Promise(function (res) { res(eventArgs); });
  12933. };
  12934. if (!this._onVrDisplayConnect) {
  12935. this._onVrDisplayConnect = function (event) {
  12936. _this._vrDisplay = event.display;
  12937. notifyObservers();
  12938. };
  12939. this._onVrDisplayDisconnect = function () {
  12940. _this._vrDisplay.cancelAnimationFrame(_this._frameHandler);
  12941. _this._vrDisplay = undefined;
  12942. _this._frameHandler = BABYLON.Tools.QueueNewFrame(_this._bindedRenderFunction);
  12943. notifyObservers();
  12944. };
  12945. this._onVrDisplayPresentChange = function () {
  12946. _this._vrExclusivePointerMode = _this._vrDisplay && _this._vrDisplay.isPresenting;
  12947. };
  12948. window.addEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  12949. window.addEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  12950. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  12951. }
  12952. this._webVRInitPromise = this._webVRInitPromise || this._getVRDisplaysAsync();
  12953. this._webVRInitPromise.then(notifyObservers);
  12954. return this._webVRInitPromise;
  12955. };
  12956. /**
  12957. * Call this function to switch to webVR mode
  12958. * Will do nothing if webVR is not supported or if there is no webVR device
  12959. * @see http://doc.babylonjs.com/how_to/webvr_camera
  12960. */
  12961. Engine.prototype.enableVR = function () {
  12962. var _this = this;
  12963. if (this._vrDisplay && !this._vrDisplay.isPresenting) {
  12964. var onResolved = function () {
  12965. _this.onVRRequestPresentComplete.notifyObservers(true);
  12966. _this._onVRFullScreenTriggered();
  12967. };
  12968. var onRejected = function () {
  12969. _this.onVRRequestPresentComplete.notifyObservers(false);
  12970. };
  12971. this.onVRRequestPresentStart.notifyObservers(this);
  12972. this._vrDisplay.requestPresent([{ source: this.getRenderingCanvas() }]).then(onResolved).catch(onRejected);
  12973. }
  12974. };
  12975. /**
  12976. * Call this function to leave webVR mode
  12977. * Will do nothing if webVR is not supported or if there is no webVR device
  12978. * @see http://doc.babylonjs.com/how_to/webvr_camera
  12979. */
  12980. Engine.prototype.disableVR = function () {
  12981. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  12982. this._vrDisplay.exitPresent().then(this._onVRFullScreenTriggered).catch(this._onVRFullScreenTriggered);
  12983. }
  12984. };
  12985. Engine.prototype._getVRDisplaysAsync = function () {
  12986. var _this = this;
  12987. return new Promise(function (res, rej) {
  12988. if (navigator.getVRDisplays) {
  12989. navigator.getVRDisplays().then(function (devices) {
  12990. _this._vrSupported = true;
  12991. // note that devices may actually be an empty array. This is fine;
  12992. // we expect this._vrDisplay to be undefined in this case.
  12993. _this._vrDisplay = devices[0];
  12994. res({
  12995. vrDisplay: _this._vrDisplay,
  12996. vrSupported: _this._vrSupported
  12997. });
  12998. });
  12999. }
  13000. else {
  13001. _this._vrDisplay = undefined;
  13002. _this._vrSupported = false;
  13003. res({
  13004. vrDisplay: _this._vrDisplay,
  13005. vrSupported: _this._vrSupported
  13006. });
  13007. }
  13008. });
  13009. };
  13010. /**
  13011. * Binds the frame buffer to the specified texture.
  13012. * @param texture The texture to render to or null for the default canvas
  13013. * @param faceIndex The face of the texture to render to in case of cube texture
  13014. * @param requiredWidth The width of the target to render to
  13015. * @param requiredHeight The height of the target to render to
  13016. * @param forceFullscreenViewport Forces the viewport to be the entire texture/screen if true
  13017. * @param depthStencilTexture The depth stencil texture to use to render
  13018. */
  13019. Engine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport, depthStencilTexture) {
  13020. if (this._currentRenderTarget) {
  13021. this.unBindFramebuffer(this._currentRenderTarget);
  13022. }
  13023. this._currentRenderTarget = texture;
  13024. this.bindUnboundFramebuffer(texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer);
  13025. var gl = this._gl;
  13026. if (texture.isCube) {
  13027. if (faceIndex === undefined) {
  13028. faceIndex = 0;
  13029. }
  13030. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, 0);
  13031. if (depthStencilTexture) {
  13032. if (depthStencilTexture._generateStencilBuffer) {
  13033. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, depthStencilTexture._webGLTexture, 0);
  13034. }
  13035. else {
  13036. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, depthStencilTexture._webGLTexture, 0);
  13037. }
  13038. }
  13039. }
  13040. if (this._cachedViewport && !forceFullscreenViewport) {
  13041. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  13042. }
  13043. else {
  13044. gl.viewport(0, 0, requiredWidth || texture.width, requiredHeight || texture.height);
  13045. }
  13046. this.wipeCaches();
  13047. };
  13048. Engine.prototype.bindUnboundFramebuffer = function (framebuffer) {
  13049. if (this._currentFramebuffer !== framebuffer) {
  13050. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, framebuffer);
  13051. this._currentFramebuffer = framebuffer;
  13052. }
  13053. };
  13054. /**
  13055. * Unbind the current render target texture from the webGL context
  13056. * @param texture defines the render target texture to unbind
  13057. * @param disableGenerateMipMaps defines a boolean indicating that mipmaps must not be generated
  13058. * @param onBeforeUnbind defines a function which will be called before the effective unbind
  13059. */
  13060. Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  13061. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  13062. this._currentRenderTarget = null;
  13063. // If MSAA, we need to bitblt back to main texture
  13064. var gl = this._gl;
  13065. if (texture._MSAAFramebuffer) {
  13066. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, texture._MSAAFramebuffer);
  13067. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, texture._framebuffer);
  13068. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  13069. }
  13070. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  13071. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  13072. gl.generateMipmap(gl.TEXTURE_2D);
  13073. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  13074. }
  13075. if (onBeforeUnbind) {
  13076. if (texture._MSAAFramebuffer) {
  13077. // Bind the correct framebuffer
  13078. this.bindUnboundFramebuffer(texture._framebuffer);
  13079. }
  13080. onBeforeUnbind();
  13081. }
  13082. this.bindUnboundFramebuffer(null);
  13083. };
  13084. /**
  13085. * Unbind a list of render target textures from the webGL context
  13086. * This is used only when drawBuffer extension or webGL2 are active
  13087. * @param textures defines the render target textures to unbind
  13088. * @param disableGenerateMipMaps defines a boolean indicating that mipmaps must not be generated
  13089. * @param onBeforeUnbind defines a function which will be called before the effective unbind
  13090. */
  13091. Engine.prototype.unBindMultiColorAttachmentFramebuffer = function (textures, disableGenerateMipMaps, onBeforeUnbind) {
  13092. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  13093. this._currentRenderTarget = null;
  13094. // If MSAA, we need to bitblt back to main texture
  13095. var gl = this._gl;
  13096. if (textures[0]._MSAAFramebuffer) {
  13097. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, textures[0]._MSAAFramebuffer);
  13098. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, textures[0]._framebuffer);
  13099. var attachments = textures[0]._attachments;
  13100. if (!attachments) {
  13101. attachments = new Array(textures.length);
  13102. textures[0]._attachments = attachments;
  13103. }
  13104. for (var i = 0; i < textures.length; i++) {
  13105. var texture = textures[i];
  13106. for (var j = 0; j < attachments.length; j++) {
  13107. attachments[j] = gl.NONE;
  13108. }
  13109. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  13110. gl.readBuffer(attachments[i]);
  13111. gl.drawBuffers(attachments);
  13112. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  13113. }
  13114. for (var i = 0; i < attachments.length; i++) {
  13115. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  13116. }
  13117. gl.drawBuffers(attachments);
  13118. }
  13119. for (var i = 0; i < textures.length; i++) {
  13120. var texture = textures[i];
  13121. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  13122. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  13123. gl.generateMipmap(gl.TEXTURE_2D);
  13124. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  13125. }
  13126. }
  13127. if (onBeforeUnbind) {
  13128. if (textures[0]._MSAAFramebuffer) {
  13129. // Bind the correct framebuffer
  13130. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  13131. }
  13132. onBeforeUnbind();
  13133. }
  13134. this.bindUnboundFramebuffer(null);
  13135. };
  13136. /**
  13137. * Force the mipmap generation for the given render target texture
  13138. * @param texture defines the render target texture to use
  13139. */
  13140. Engine.prototype.generateMipMapsForCubemap = function (texture) {
  13141. if (texture.generateMipMaps) {
  13142. var gl = this._gl;
  13143. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  13144. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  13145. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  13146. }
  13147. };
  13148. /**
  13149. * Force a webGL flush (ie. a flush of all waiting webGL commands)
  13150. */
  13151. Engine.prototype.flushFramebuffer = function () {
  13152. this._gl.flush();
  13153. };
  13154. /**
  13155. * Unbind the current render target and bind the default framebuffer
  13156. */
  13157. Engine.prototype.restoreDefaultFramebuffer = function () {
  13158. if (this._currentRenderTarget) {
  13159. this.unBindFramebuffer(this._currentRenderTarget);
  13160. }
  13161. else {
  13162. this.bindUnboundFramebuffer(null);
  13163. }
  13164. if (this._cachedViewport) {
  13165. this.setViewport(this._cachedViewport);
  13166. }
  13167. this.wipeCaches();
  13168. };
  13169. // UBOs
  13170. /**
  13171. * Create an uniform buffer
  13172. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  13173. * @param elements defines the content of the uniform buffer
  13174. * @returns the webGL uniform buffer
  13175. */
  13176. Engine.prototype.createUniformBuffer = function (elements) {
  13177. var ubo = this._gl.createBuffer();
  13178. if (!ubo) {
  13179. throw new Error("Unable to create uniform buffer");
  13180. }
  13181. this.bindUniformBuffer(ubo);
  13182. if (elements instanceof Float32Array) {
  13183. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.STATIC_DRAW);
  13184. }
  13185. else {
  13186. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.STATIC_DRAW);
  13187. }
  13188. this.bindUniformBuffer(null);
  13189. ubo.references = 1;
  13190. return ubo;
  13191. };
  13192. /**
  13193. * Create a dynamic uniform buffer
  13194. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  13195. * @param elements defines the content of the uniform buffer
  13196. * @returns the webGL uniform buffer
  13197. */
  13198. Engine.prototype.createDynamicUniformBuffer = function (elements) {
  13199. var ubo = this._gl.createBuffer();
  13200. if (!ubo) {
  13201. throw new Error("Unable to create dynamic uniform buffer");
  13202. }
  13203. this.bindUniformBuffer(ubo);
  13204. if (elements instanceof Float32Array) {
  13205. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.DYNAMIC_DRAW);
  13206. }
  13207. else {
  13208. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.DYNAMIC_DRAW);
  13209. }
  13210. this.bindUniformBuffer(null);
  13211. ubo.references = 1;
  13212. return ubo;
  13213. };
  13214. /**
  13215. * Update an existing uniform buffer
  13216. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  13217. * @param uniformBuffer defines the target uniform buffer
  13218. * @param elements defines the content to update
  13219. * @param offset defines the offset in the uniform buffer where update should start
  13220. * @param count defines the size of the data to update
  13221. */
  13222. Engine.prototype.updateUniformBuffer = function (uniformBuffer, elements, offset, count) {
  13223. this.bindUniformBuffer(uniformBuffer);
  13224. if (offset === undefined) {
  13225. offset = 0;
  13226. }
  13227. if (count === undefined) {
  13228. if (elements instanceof Float32Array) {
  13229. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, elements);
  13230. }
  13231. else {
  13232. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, new Float32Array(elements));
  13233. }
  13234. }
  13235. else {
  13236. if (elements instanceof Float32Array) {
  13237. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, elements.subarray(offset, offset + count));
  13238. }
  13239. else {
  13240. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, new Float32Array(elements).subarray(offset, offset + count));
  13241. }
  13242. }
  13243. this.bindUniformBuffer(null);
  13244. };
  13245. // VBOs
  13246. Engine.prototype._resetVertexBufferBinding = function () {
  13247. this.bindArrayBuffer(null);
  13248. this._cachedVertexBuffers = null;
  13249. };
  13250. /**
  13251. * Creates a vertex buffer
  13252. * @param data the data for the vertex buffer
  13253. * @returns the new WebGL static buffer
  13254. */
  13255. Engine.prototype.createVertexBuffer = function (data) {
  13256. var vbo = this._gl.createBuffer();
  13257. if (!vbo) {
  13258. throw new Error("Unable to create vertex buffer");
  13259. }
  13260. this.bindArrayBuffer(vbo);
  13261. if (data instanceof Array) {
  13262. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(data), this._gl.STATIC_DRAW);
  13263. }
  13264. else {
  13265. this._gl.bufferData(this._gl.ARRAY_BUFFER, data, this._gl.STATIC_DRAW);
  13266. }
  13267. this._resetVertexBufferBinding();
  13268. vbo.references = 1;
  13269. return vbo;
  13270. };
  13271. /**
  13272. * Creates a dynamic vertex buffer
  13273. * @param data the data for the dynamic vertex buffer
  13274. * @returns the new WebGL dynamic buffer
  13275. */
  13276. Engine.prototype.createDynamicVertexBuffer = function (data) {
  13277. var vbo = this._gl.createBuffer();
  13278. if (!vbo) {
  13279. throw new Error("Unable to create dynamic vertex buffer");
  13280. }
  13281. this.bindArrayBuffer(vbo);
  13282. if (data instanceof Array) {
  13283. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(data), this._gl.DYNAMIC_DRAW);
  13284. }
  13285. else {
  13286. this._gl.bufferData(this._gl.ARRAY_BUFFER, data, this._gl.DYNAMIC_DRAW);
  13287. }
  13288. this._resetVertexBufferBinding();
  13289. vbo.references = 1;
  13290. return vbo;
  13291. };
  13292. /**
  13293. * Update a dynamic index buffer
  13294. * @param indexBuffer defines the target index buffer
  13295. * @param indices defines the data to update
  13296. * @param offset defines the offset in the target index buffer where update should start
  13297. */
  13298. Engine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  13299. if (offset === void 0) { offset = 0; }
  13300. // Force cache update
  13301. this._currentBoundBuffer[this._gl.ELEMENT_ARRAY_BUFFER] = null;
  13302. this.bindIndexBuffer(indexBuffer);
  13303. var arrayBuffer;
  13304. if (indices instanceof Uint16Array || indices instanceof Uint32Array) {
  13305. arrayBuffer = indices;
  13306. }
  13307. else {
  13308. arrayBuffer = indexBuffer.is32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  13309. }
  13310. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.DYNAMIC_DRAW);
  13311. this._resetIndexBufferBinding();
  13312. };
  13313. /**
  13314. * Updates a dynamic vertex buffer.
  13315. * @param vertexBuffer the vertex buffer to update
  13316. * @param data the data used to update the vertex buffer
  13317. * @param byteOffset the byte offset of the data
  13318. * @param byteLength the byte length of the data
  13319. */
  13320. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, data, byteOffset, byteLength) {
  13321. this.bindArrayBuffer(vertexBuffer);
  13322. if (byteOffset === undefined) {
  13323. byteOffset = 0;
  13324. }
  13325. if (byteLength === undefined) {
  13326. if (data instanceof Array) {
  13327. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, byteOffset, new Float32Array(data));
  13328. }
  13329. else {
  13330. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, byteOffset, data);
  13331. }
  13332. }
  13333. else {
  13334. if (data instanceof Array) {
  13335. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(data).subarray(byteOffset, byteOffset + byteLength));
  13336. }
  13337. else {
  13338. if (data instanceof ArrayBuffer) {
  13339. data = new Uint8Array(data, byteOffset, byteLength);
  13340. }
  13341. else {
  13342. data = new Uint8Array(data.buffer, data.byteOffset + byteOffset, byteLength);
  13343. }
  13344. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  13345. }
  13346. }
  13347. this._resetVertexBufferBinding();
  13348. };
  13349. Engine.prototype._resetIndexBufferBinding = function () {
  13350. this.bindIndexBuffer(null);
  13351. this._cachedIndexBuffer = null;
  13352. };
  13353. /**
  13354. * Creates a new index buffer
  13355. * @param indices defines the content of the index buffer
  13356. * @param updatable defines if the index buffer must be updatable
  13357. * @returns a new webGL buffer
  13358. */
  13359. Engine.prototype.createIndexBuffer = function (indices, updatable) {
  13360. var vbo = this._gl.createBuffer();
  13361. if (!vbo) {
  13362. throw new Error("Unable to create index buffer");
  13363. }
  13364. this.bindIndexBuffer(vbo);
  13365. // Check for 32 bits indices
  13366. var arrayBuffer;
  13367. var need32Bits = false;
  13368. if (indices instanceof Uint16Array) {
  13369. arrayBuffer = indices;
  13370. }
  13371. else {
  13372. //check 32 bit support
  13373. if (this._caps.uintIndices) {
  13374. if (indices instanceof Uint32Array) {
  13375. arrayBuffer = indices;
  13376. need32Bits = true;
  13377. }
  13378. else {
  13379. //number[] or Int32Array, check if 32 bit is necessary
  13380. for (var index = 0; index < indices.length; index++) {
  13381. if (indices[index] > 65535) {
  13382. need32Bits = true;
  13383. break;
  13384. }
  13385. }
  13386. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  13387. }
  13388. }
  13389. else {
  13390. //no 32 bit support, force conversion to 16 bit (values greater 16 bit are lost)
  13391. arrayBuffer = new Uint16Array(indices);
  13392. }
  13393. }
  13394. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, updatable ? this._gl.DYNAMIC_DRAW : this._gl.STATIC_DRAW);
  13395. this._resetIndexBufferBinding();
  13396. vbo.references = 1;
  13397. vbo.is32Bits = need32Bits;
  13398. return vbo;
  13399. };
  13400. /**
  13401. * Bind a webGL buffer to the webGL context
  13402. * @param buffer defines the buffer to bind
  13403. */
  13404. Engine.prototype.bindArrayBuffer = function (buffer) {
  13405. if (!this._vaoRecordInProgress) {
  13406. this._unbindVertexArrayObject();
  13407. }
  13408. this.bindBuffer(buffer, this._gl.ARRAY_BUFFER);
  13409. };
  13410. /**
  13411. * Bind an uniform buffer to the current webGL context
  13412. * @param buffer defines the buffer to bind
  13413. */
  13414. Engine.prototype.bindUniformBuffer = function (buffer) {
  13415. this._gl.bindBuffer(this._gl.UNIFORM_BUFFER, buffer);
  13416. };
  13417. /**
  13418. * Bind a buffer to the current webGL context at a given location
  13419. * @param buffer defines the buffer to bind
  13420. * @param location defines the index where to bind the buffer
  13421. */
  13422. Engine.prototype.bindUniformBufferBase = function (buffer, location) {
  13423. this._gl.bindBufferBase(this._gl.UNIFORM_BUFFER, location, buffer);
  13424. };
  13425. /**
  13426. * Bind a specific block at a given index in a specific shader program
  13427. * @param shaderProgram defines the shader program
  13428. * @param blockName defines the block name
  13429. * @param index defines the index where to bind the block
  13430. */
  13431. Engine.prototype.bindUniformBlock = function (shaderProgram, blockName, index) {
  13432. var uniformLocation = this._gl.getUniformBlockIndex(shaderProgram, blockName);
  13433. this._gl.uniformBlockBinding(shaderProgram, uniformLocation, index);
  13434. };
  13435. ;
  13436. Engine.prototype.bindIndexBuffer = function (buffer) {
  13437. if (!this._vaoRecordInProgress) {
  13438. this._unbindVertexArrayObject();
  13439. }
  13440. this.bindBuffer(buffer, this._gl.ELEMENT_ARRAY_BUFFER);
  13441. };
  13442. Engine.prototype.bindBuffer = function (buffer, target) {
  13443. if (this._vaoRecordInProgress || this._currentBoundBuffer[target] !== buffer) {
  13444. this._gl.bindBuffer(target, buffer);
  13445. this._currentBoundBuffer[target] = buffer;
  13446. }
  13447. };
  13448. /**
  13449. * update the bound buffer with the given data
  13450. * @param data defines the data to update
  13451. */
  13452. Engine.prototype.updateArrayBuffer = function (data) {
  13453. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  13454. };
  13455. Engine.prototype._vertexAttribPointer = function (buffer, indx, size, type, normalized, stride, offset) {
  13456. var pointer = this._currentBufferPointers[indx];
  13457. var changed = false;
  13458. if (!pointer.active) {
  13459. changed = true;
  13460. pointer.active = true;
  13461. pointer.index = indx;
  13462. pointer.size = size;
  13463. pointer.type = type;
  13464. pointer.normalized = normalized;
  13465. pointer.stride = stride;
  13466. pointer.offset = offset;
  13467. pointer.buffer = buffer;
  13468. }
  13469. else {
  13470. if (pointer.buffer !== buffer) {
  13471. pointer.buffer = buffer;
  13472. changed = true;
  13473. }
  13474. if (pointer.size !== size) {
  13475. pointer.size = size;
  13476. changed = true;
  13477. }
  13478. if (pointer.type !== type) {
  13479. pointer.type = type;
  13480. changed = true;
  13481. }
  13482. if (pointer.normalized !== normalized) {
  13483. pointer.normalized = normalized;
  13484. changed = true;
  13485. }
  13486. if (pointer.stride !== stride) {
  13487. pointer.stride = stride;
  13488. changed = true;
  13489. }
  13490. if (pointer.offset !== offset) {
  13491. pointer.offset = offset;
  13492. changed = true;
  13493. }
  13494. }
  13495. if (changed || this._vaoRecordInProgress) {
  13496. this.bindArrayBuffer(buffer);
  13497. this._gl.vertexAttribPointer(indx, size, type, normalized, stride, offset);
  13498. }
  13499. };
  13500. Engine.prototype._bindIndexBufferWithCache = function (indexBuffer) {
  13501. if (indexBuffer == null) {
  13502. return;
  13503. }
  13504. if (this._cachedIndexBuffer !== indexBuffer) {
  13505. this._cachedIndexBuffer = indexBuffer;
  13506. this.bindIndexBuffer(indexBuffer);
  13507. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  13508. }
  13509. };
  13510. Engine.prototype._bindVertexBuffersAttributes = function (vertexBuffers, effect) {
  13511. var attributes = effect.getAttributesNames();
  13512. if (!this._vaoRecordInProgress) {
  13513. this._unbindVertexArrayObject();
  13514. }
  13515. this.unbindAllAttributes();
  13516. for (var index = 0; index < attributes.length; index++) {
  13517. var order = effect.getAttributeLocation(index);
  13518. if (order >= 0) {
  13519. var vertexBuffer = vertexBuffers[attributes[index]];
  13520. if (!vertexBuffer) {
  13521. continue;
  13522. }
  13523. this._gl.enableVertexAttribArray(order);
  13524. if (!this._vaoRecordInProgress) {
  13525. this._vertexAttribArraysEnabled[order] = true;
  13526. }
  13527. var buffer = vertexBuffer.getBuffer();
  13528. if (buffer) {
  13529. this._vertexAttribPointer(buffer, order, vertexBuffer.getSize(), vertexBuffer.type, vertexBuffer.normalized, vertexBuffer.byteStride, vertexBuffer.byteOffset);
  13530. if (vertexBuffer.getIsInstanced()) {
  13531. this._gl.vertexAttribDivisor(order, vertexBuffer.getInstanceDivisor());
  13532. if (!this._vaoRecordInProgress) {
  13533. this._currentInstanceLocations.push(order);
  13534. this._currentInstanceBuffers.push(buffer);
  13535. }
  13536. }
  13537. }
  13538. }
  13539. }
  13540. };
  13541. /**
  13542. * Records a vertex array object
  13543. * @see http://doc.babylonjs.com/features/webgl2#vertex-array-objects
  13544. * @param vertexBuffers defines the list of vertex buffers to store
  13545. * @param indexBuffer defines the index buffer to store
  13546. * @param effect defines the effect to store
  13547. * @returns the new vertex array object
  13548. */
  13549. Engine.prototype.recordVertexArrayObject = function (vertexBuffers, indexBuffer, effect) {
  13550. var vao = this._gl.createVertexArray();
  13551. this._vaoRecordInProgress = true;
  13552. this._gl.bindVertexArray(vao);
  13553. this._mustWipeVertexAttributes = true;
  13554. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  13555. this.bindIndexBuffer(indexBuffer);
  13556. this._vaoRecordInProgress = false;
  13557. this._gl.bindVertexArray(null);
  13558. return vao;
  13559. };
  13560. /**
  13561. * Bind a specific vertex array object
  13562. * @see http://doc.babylonjs.com/features/webgl2#vertex-array-objects
  13563. * @param vertexArrayObject defines the vertex array object to bind
  13564. * @param indexBuffer defines the index buffer to bind
  13565. */
  13566. Engine.prototype.bindVertexArrayObject = function (vertexArrayObject, indexBuffer) {
  13567. if (this._cachedVertexArrayObject !== vertexArrayObject) {
  13568. this._cachedVertexArrayObject = vertexArrayObject;
  13569. this._gl.bindVertexArray(vertexArrayObject);
  13570. this._cachedVertexBuffers = null;
  13571. this._cachedIndexBuffer = null;
  13572. this._uintIndicesCurrentlySet = indexBuffer != null && indexBuffer.is32Bits;
  13573. this._mustWipeVertexAttributes = true;
  13574. }
  13575. };
  13576. /**
  13577. * Bind webGl buffers directly to the webGL context
  13578. * @param vertexBuffer defines the vertex buffer to bind
  13579. * @param indexBuffer defines the index buffer to bind
  13580. * @param vertexDeclaration defines the vertex declaration to use with the vertex buffer
  13581. * @param vertexStrideSize defines the vertex stride of the vertex buffer
  13582. * @param effect defines the effect associated with the vertex buffer
  13583. */
  13584. Engine.prototype.bindBuffersDirectly = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  13585. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  13586. this._cachedVertexBuffers = vertexBuffer;
  13587. this._cachedEffectForVertexBuffers = effect;
  13588. var attributesCount = effect.getAttributesCount();
  13589. this._unbindVertexArrayObject();
  13590. this.unbindAllAttributes();
  13591. var offset = 0;
  13592. for (var index = 0; index < attributesCount; index++) {
  13593. if (index < vertexDeclaration.length) {
  13594. var order = effect.getAttributeLocation(index);
  13595. if (order >= 0) {
  13596. this._gl.enableVertexAttribArray(order);
  13597. this._vertexAttribArraysEnabled[order] = true;
  13598. this._vertexAttribPointer(vertexBuffer, order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  13599. }
  13600. offset += vertexDeclaration[index] * 4;
  13601. }
  13602. }
  13603. }
  13604. this._bindIndexBufferWithCache(indexBuffer);
  13605. };
  13606. Engine.prototype._unbindVertexArrayObject = function () {
  13607. if (!this._cachedVertexArrayObject) {
  13608. return;
  13609. }
  13610. this._cachedVertexArrayObject = null;
  13611. this._gl.bindVertexArray(null);
  13612. };
  13613. /**
  13614. * Bind a list of vertex buffers to the webGL context
  13615. * @param vertexBuffers defines the list of vertex buffers to bind
  13616. * @param indexBuffer defines the index buffer to bind
  13617. * @param effect defines the effect associated with the vertex buffers
  13618. */
  13619. Engine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  13620. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  13621. this._cachedVertexBuffers = vertexBuffers;
  13622. this._cachedEffectForVertexBuffers = effect;
  13623. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  13624. }
  13625. this._bindIndexBufferWithCache(indexBuffer);
  13626. };
  13627. /**
  13628. * Unbind all instance attributes
  13629. */
  13630. Engine.prototype.unbindInstanceAttributes = function () {
  13631. var boundBuffer;
  13632. for (var i = 0, ul = this._currentInstanceLocations.length; i < ul; i++) {
  13633. var instancesBuffer = this._currentInstanceBuffers[i];
  13634. if (boundBuffer != instancesBuffer && instancesBuffer.references) {
  13635. boundBuffer = instancesBuffer;
  13636. this.bindArrayBuffer(instancesBuffer);
  13637. }
  13638. var offsetLocation = this._currentInstanceLocations[i];
  13639. this._gl.vertexAttribDivisor(offsetLocation, 0);
  13640. }
  13641. this._currentInstanceBuffers.length = 0;
  13642. this._currentInstanceLocations.length = 0;
  13643. };
  13644. /**
  13645. * Release and free the memory of a vertex array object
  13646. * @param vao defines the vertex array object to delete
  13647. */
  13648. Engine.prototype.releaseVertexArrayObject = function (vao) {
  13649. this._gl.deleteVertexArray(vao);
  13650. };
  13651. /** @hidden */
  13652. Engine.prototype._releaseBuffer = function (buffer) {
  13653. buffer.references--;
  13654. if (buffer.references === 0) {
  13655. this._gl.deleteBuffer(buffer);
  13656. return true;
  13657. }
  13658. return false;
  13659. };
  13660. /**
  13661. * Creates a webGL buffer to use with instanciation
  13662. * @param capacity defines the size of the buffer
  13663. * @returns the webGL buffer
  13664. */
  13665. Engine.prototype.createInstancesBuffer = function (capacity) {
  13666. var buffer = this._gl.createBuffer();
  13667. if (!buffer) {
  13668. throw new Error("Unable to create instance buffer");
  13669. }
  13670. buffer.capacity = capacity;
  13671. this.bindArrayBuffer(buffer);
  13672. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  13673. return buffer;
  13674. };
  13675. /**
  13676. * Delete a webGL buffer used with instanciation
  13677. * @param buffer defines the webGL buffer to delete
  13678. */
  13679. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  13680. this._gl.deleteBuffer(buffer);
  13681. };
  13682. /**
  13683. * Update the content of a webGL buffer used with instanciation and bind it to the webGL context
  13684. * @param instancesBuffer defines the webGL buffer to update and bind
  13685. * @param data defines the data to store in the buffer
  13686. * @param offsetLocations defines the offsets or attributes information used to determine where data must be stored in the buffer
  13687. */
  13688. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  13689. this.bindArrayBuffer(instancesBuffer);
  13690. if (data) {
  13691. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  13692. }
  13693. if (offsetLocations[0].index !== undefined) {
  13694. var stride = 0;
  13695. for (var i = 0; i < offsetLocations.length; i++) {
  13696. var ai = offsetLocations[i];
  13697. stride += ai.attributeSize * 4;
  13698. }
  13699. for (var i = 0; i < offsetLocations.length; i++) {
  13700. var ai = offsetLocations[i];
  13701. if (!this._vertexAttribArraysEnabled[ai.index]) {
  13702. this._gl.enableVertexAttribArray(ai.index);
  13703. this._vertexAttribArraysEnabled[ai.index] = true;
  13704. }
  13705. this._vertexAttribPointer(instancesBuffer, ai.index, ai.attributeSize, ai.attribyteType || this._gl.FLOAT, ai.normalized || false, stride, ai.offset);
  13706. this._gl.vertexAttribDivisor(ai.index, 1);
  13707. this._currentInstanceLocations.push(ai.index);
  13708. this._currentInstanceBuffers.push(instancesBuffer);
  13709. }
  13710. }
  13711. else {
  13712. for (var index = 0; index < 4; index++) {
  13713. var offsetLocation = offsetLocations[index];
  13714. if (!this._vertexAttribArraysEnabled[offsetLocation]) {
  13715. this._gl.enableVertexAttribArray(offsetLocation);
  13716. this._vertexAttribArraysEnabled[offsetLocation] = true;
  13717. }
  13718. this._vertexAttribPointer(instancesBuffer, offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  13719. this._gl.vertexAttribDivisor(offsetLocation, 1);
  13720. this._currentInstanceLocations.push(offsetLocation);
  13721. this._currentInstanceBuffers.push(instancesBuffer);
  13722. }
  13723. }
  13724. };
  13725. /**
  13726. * Apply all cached states (depth, culling, stencil and alpha)
  13727. */
  13728. Engine.prototype.applyStates = function () {
  13729. this._depthCullingState.apply(this._gl);
  13730. this._stencilState.apply(this._gl);
  13731. this._alphaState.apply(this._gl);
  13732. };
  13733. /**
  13734. * Send a draw order
  13735. * @param useTriangles defines if triangles must be used to draw (else wireframe will be used)
  13736. * @param indexStart defines the starting index
  13737. * @param indexCount defines the number of index to draw
  13738. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13739. */
  13740. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  13741. this.drawElementsType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, indexStart, indexCount, instancesCount);
  13742. };
  13743. /**
  13744. * Draw a list of points
  13745. * @param verticesStart defines the index of first vertex to draw
  13746. * @param verticesCount defines the count of vertices to draw
  13747. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13748. */
  13749. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  13750. this.drawArraysType(BABYLON.Material.PointFillMode, verticesStart, verticesCount, instancesCount);
  13751. };
  13752. /**
  13753. * Draw a list of unindexed primitives
  13754. * @param useTriangles defines if triangles must be used to draw (else wireframe will be used)
  13755. * @param verticesStart defines the index of first vertex to draw
  13756. * @param verticesCount defines the count of vertices to draw
  13757. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13758. */
  13759. Engine.prototype.drawUnIndexed = function (useTriangles, verticesStart, verticesCount, instancesCount) {
  13760. this.drawArraysType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, verticesStart, verticesCount, instancesCount);
  13761. };
  13762. /**
  13763. * Draw a list of indexed primitives
  13764. * @param fillMode defines the primitive to use
  13765. * @param indexStart defines the starting index
  13766. * @param indexCount defines the number of index to draw
  13767. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13768. */
  13769. Engine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  13770. // Apply states
  13771. this.applyStates();
  13772. this._drawCalls.addCount(1, false);
  13773. // Render
  13774. var drawMode = this._drawMode(fillMode);
  13775. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  13776. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  13777. if (instancesCount) {
  13778. this._gl.drawElementsInstanced(drawMode, indexCount, indexFormat, indexStart * mult, instancesCount);
  13779. }
  13780. else {
  13781. this._gl.drawElements(drawMode, indexCount, indexFormat, indexStart * mult);
  13782. }
  13783. };
  13784. /**
  13785. * Draw a list of unindexed primitives
  13786. * @param fillMode defines the primitive to use
  13787. * @param verticesStart defines the index of first vertex to draw
  13788. * @param verticesCount defines the count of vertices to draw
  13789. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13790. */
  13791. Engine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  13792. // Apply states
  13793. this.applyStates();
  13794. this._drawCalls.addCount(1, false);
  13795. var drawMode = this._drawMode(fillMode);
  13796. if (instancesCount) {
  13797. this._gl.drawArraysInstanced(drawMode, verticesStart, verticesCount, instancesCount);
  13798. }
  13799. else {
  13800. this._gl.drawArrays(drawMode, verticesStart, verticesCount);
  13801. }
  13802. };
  13803. Engine.prototype._drawMode = function (fillMode) {
  13804. switch (fillMode) {
  13805. // Triangle views
  13806. case BABYLON.Material.TriangleFillMode:
  13807. return this._gl.TRIANGLES;
  13808. case BABYLON.Material.PointFillMode:
  13809. return this._gl.POINTS;
  13810. case BABYLON.Material.WireFrameFillMode:
  13811. return this._gl.LINES;
  13812. // Draw modes
  13813. case BABYLON.Material.PointListDrawMode:
  13814. return this._gl.POINTS;
  13815. case BABYLON.Material.LineListDrawMode:
  13816. return this._gl.LINES;
  13817. case BABYLON.Material.LineLoopDrawMode:
  13818. return this._gl.LINE_LOOP;
  13819. case BABYLON.Material.LineStripDrawMode:
  13820. return this._gl.LINE_STRIP;
  13821. case BABYLON.Material.TriangleStripDrawMode:
  13822. return this._gl.TRIANGLE_STRIP;
  13823. case BABYLON.Material.TriangleFanDrawMode:
  13824. return this._gl.TRIANGLE_FAN;
  13825. default:
  13826. return this._gl.TRIANGLES;
  13827. }
  13828. };
  13829. // Shaders
  13830. /** @hidden */
  13831. Engine.prototype._releaseEffect = function (effect) {
  13832. if (this._compiledEffects[effect._key]) {
  13833. delete this._compiledEffects[effect._key];
  13834. this._deleteProgram(effect.getProgram());
  13835. }
  13836. };
  13837. /** @hidden */
  13838. Engine.prototype._deleteProgram = function (program) {
  13839. if (program) {
  13840. program.__SPECTOR_rebuildProgram = null;
  13841. if (program.transformFeedback) {
  13842. this.deleteTransformFeedback(program.transformFeedback);
  13843. program.transformFeedback = null;
  13844. }
  13845. this._gl.deleteProgram(program);
  13846. }
  13847. };
  13848. /**
  13849. * Create a new effect (used to store vertex/fragment shaders)
  13850. * @param baseName defines the base name of the effect (The name of file without .fragment.fx or .vertex.fx)
  13851. * @param attributesNamesOrOptions defines either a list of attribute names or an EffectCreationOptions object
  13852. * @param uniformsNamesOrEngine defines either a list of uniform names or the engine to use
  13853. * @param samplers defines an array of string used to represent textures
  13854. * @param defines defines the string containing the defines to use to compile the shaders
  13855. * @param fallbacks defines the list of potential fallbacks to use if shader conmpilation fails
  13856. * @param onCompiled defines a function to call when the effect creation is successful
  13857. * @param onError defines a function to call when the effect creation has failed
  13858. * @param indexParameters defines an object containing the index values to use to compile shaders (like the maximum number of simultaneous lights)
  13859. * @returns the new Effect
  13860. */
  13861. Engine.prototype.createEffect = function (baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, defines, fallbacks, onCompiled, onError, indexParameters) {
  13862. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  13863. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  13864. var name = vertex + "+" + fragment + "@" + (defines ? defines : attributesNamesOrOptions.defines);
  13865. if (this._compiledEffects[name]) {
  13866. var compiledEffect = this._compiledEffects[name];
  13867. if (onCompiled && compiledEffect.isReady()) {
  13868. onCompiled(compiledEffect);
  13869. }
  13870. return compiledEffect;
  13871. }
  13872. var effect = new BABYLON.Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters);
  13873. effect._key = name;
  13874. this._compiledEffects[name] = effect;
  13875. return effect;
  13876. };
  13877. /**
  13878. * Create an effect to use with particle systems
  13879. * @param fragmentName defines the base name of the effect (The name of file without .fragment.fx)
  13880. * @param uniformsNames defines a list of attribute names
  13881. * @param samplers defines an array of string used to represent textures
  13882. * @param defines defines the string containing the defines to use to compile the shaders
  13883. * @param fallbacks defines the list of potential fallbacks to use if shader conmpilation fails
  13884. * @param onCompiled defines a function to call when the effect creation is successful
  13885. * @param onError defines a function to call when the effect creation has failed
  13886. * @returns the new Effect
  13887. */
  13888. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  13889. if (uniformsNames === void 0) { uniformsNames = []; }
  13890. if (samplers === void 0) { samplers = []; }
  13891. if (defines === void 0) { defines = ""; }
  13892. return this.createEffect({
  13893. vertex: "particles",
  13894. fragmentElement: fragmentName
  13895. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  13896. };
  13897. /**
  13898. * Directly creates a webGL program
  13899. * @param vertexCode defines the vertex shader code to use
  13900. * @param fragmentCode defines the fragment shader code to use
  13901. * @param context defines the webGL context to use (if not set, the current one will be used)
  13902. * @param transformFeedbackVaryings defines the list of transform feedback varyings to use
  13903. * @returns the new webGL program
  13904. */
  13905. Engine.prototype.createRawShaderProgram = function (vertexCode, fragmentCode, context, transformFeedbackVaryings) {
  13906. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  13907. context = context || this._gl;
  13908. var vertexShader = compileRawShader(context, vertexCode, "vertex");
  13909. var fragmentShader = compileRawShader(context, fragmentCode, "fragment");
  13910. return this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  13911. };
  13912. /**
  13913. * Creates a webGL program
  13914. * @param vertexCode defines the vertex shader code to use
  13915. * @param fragmentCode defines the fragment shader code to use
  13916. * @param defines defines the string containing the defines to use to compile the shaders
  13917. * @param context defines the webGL context to use (if not set, the current one will be used)
  13918. * @param transformFeedbackVaryings defines the list of transform feedback varyings to use
  13919. * @returns the new webGL program
  13920. */
  13921. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context, transformFeedbackVaryings) {
  13922. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  13923. context = context || this._gl;
  13924. this.onBeforeShaderCompilationObservable.notifyObservers(this);
  13925. var shaderVersion = (this._webGLVersion > 1) ? "#version 300 es\n#define WEBGL2 \n" : "";
  13926. var vertexShader = compileShader(context, vertexCode, "vertex", defines, shaderVersion);
  13927. var fragmentShader = compileShader(context, fragmentCode, "fragment", defines, shaderVersion);
  13928. var program = this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  13929. this.onAfterShaderCompilationObservable.notifyObservers(this);
  13930. return program;
  13931. };
  13932. Engine.prototype._createShaderProgram = function (vertexShader, fragmentShader, context, transformFeedbackVaryings) {
  13933. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  13934. var shaderProgram = context.createProgram();
  13935. if (!shaderProgram) {
  13936. throw new Error("Unable to create program");
  13937. }
  13938. context.attachShader(shaderProgram, vertexShader);
  13939. context.attachShader(shaderProgram, fragmentShader);
  13940. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  13941. var transformFeedback = this.createTransformFeedback();
  13942. this.bindTransformFeedback(transformFeedback);
  13943. this.setTranformFeedbackVaryings(shaderProgram, transformFeedbackVaryings);
  13944. shaderProgram.transformFeedback = transformFeedback;
  13945. }
  13946. context.linkProgram(shaderProgram);
  13947. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  13948. this.bindTransformFeedback(null);
  13949. }
  13950. var linked = context.getProgramParameter(shaderProgram, context.LINK_STATUS);
  13951. if (!linked) {
  13952. context.validateProgram(shaderProgram);
  13953. var error = context.getProgramInfoLog(shaderProgram);
  13954. if (error) {
  13955. throw new Error(error);
  13956. }
  13957. }
  13958. context.deleteShader(vertexShader);
  13959. context.deleteShader(fragmentShader);
  13960. return shaderProgram;
  13961. };
  13962. /**
  13963. * Gets the list of webGL uniform locations associated with a specific program based on a list of uniform names
  13964. * @param shaderProgram defines the webGL program to use
  13965. * @param uniformsNames defines the list of uniform names
  13966. * @returns an array of webGL uniform locations
  13967. */
  13968. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  13969. var results = new Array();
  13970. for (var index = 0; index < uniformsNames.length; index++) {
  13971. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  13972. }
  13973. return results;
  13974. };
  13975. /**
  13976. * Gets the lsit of active attributes for a given webGL program
  13977. * @param shaderProgram defines the webGL program to use
  13978. * @param attributesNames defines the list of attribute names to get
  13979. * @returns an array of indices indicating the offset of each attribute
  13980. */
  13981. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  13982. var results = [];
  13983. for (var index = 0; index < attributesNames.length; index++) {
  13984. try {
  13985. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  13986. }
  13987. catch (e) {
  13988. results.push(-1);
  13989. }
  13990. }
  13991. return results;
  13992. };
  13993. /**
  13994. * Activates an effect, mkaing it the current one (ie. the one used for rendering)
  13995. * @param effect defines the effect to activate
  13996. */
  13997. Engine.prototype.enableEffect = function (effect) {
  13998. if (!effect) {
  13999. return;
  14000. }
  14001. // Use program
  14002. this.bindSamplers(effect);
  14003. this._currentEffect = effect;
  14004. if (effect.onBind) {
  14005. effect.onBind(effect);
  14006. }
  14007. effect.onBindObservable.notifyObservers(effect);
  14008. };
  14009. /**
  14010. * Set the value of an uniform to an array of int32
  14011. * @param uniform defines the webGL uniform location where to store the value
  14012. * @param array defines the array of int32 to store
  14013. */
  14014. Engine.prototype.setIntArray = function (uniform, array) {
  14015. if (!uniform)
  14016. return;
  14017. this._gl.uniform1iv(uniform, array);
  14018. };
  14019. /**
  14020. * Set the value of an uniform to an array of int32 (stored as vec2)
  14021. * @param uniform defines the webGL uniform location where to store the value
  14022. * @param array defines the array of int32 to store
  14023. */
  14024. Engine.prototype.setIntArray2 = function (uniform, array) {
  14025. if (!uniform || array.length % 2 !== 0)
  14026. return;
  14027. this._gl.uniform2iv(uniform, array);
  14028. };
  14029. /**
  14030. * Set the value of an uniform to an array of int32 (stored as vec3)
  14031. * @param uniform defines the webGL uniform location where to store the value
  14032. * @param array defines the array of int32 to store
  14033. */
  14034. Engine.prototype.setIntArray3 = function (uniform, array) {
  14035. if (!uniform || array.length % 3 !== 0)
  14036. return;
  14037. this._gl.uniform3iv(uniform, array);
  14038. };
  14039. /**
  14040. * Set the value of an uniform to an array of int32 (stored as vec4)
  14041. * @param uniform defines the webGL uniform location where to store the value
  14042. * @param array defines the array of int32 to store
  14043. */
  14044. Engine.prototype.setIntArray4 = function (uniform, array) {
  14045. if (!uniform || array.length % 4 !== 0)
  14046. return;
  14047. this._gl.uniform4iv(uniform, array);
  14048. };
  14049. /**
  14050. * Set the value of an uniform to an array of float32
  14051. * @param uniform defines the webGL uniform location where to store the value
  14052. * @param array defines the array of float32 to store
  14053. */
  14054. Engine.prototype.setFloatArray = function (uniform, array) {
  14055. if (!uniform)
  14056. return;
  14057. this._gl.uniform1fv(uniform, array);
  14058. };
  14059. /**
  14060. * Set the value of an uniform to an array of float32 (stored as vec2)
  14061. * @param uniform defines the webGL uniform location where to store the value
  14062. * @param array defines the array of float32 to store
  14063. */
  14064. Engine.prototype.setFloatArray2 = function (uniform, array) {
  14065. if (!uniform || array.length % 2 !== 0)
  14066. return;
  14067. this._gl.uniform2fv(uniform, array);
  14068. };
  14069. /**
  14070. * Set the value of an uniform to an array of float32 (stored as vec3)
  14071. * @param uniform defines the webGL uniform location where to store the value
  14072. * @param array defines the array of float32 to store
  14073. */
  14074. Engine.prototype.setFloatArray3 = function (uniform, array) {
  14075. if (!uniform || array.length % 3 !== 0)
  14076. return;
  14077. this._gl.uniform3fv(uniform, array);
  14078. };
  14079. /**
  14080. * Set the value of an uniform to an array of float32 (stored as vec4)
  14081. * @param uniform defines the webGL uniform location where to store the value
  14082. * @param array defines the array of float32 to store
  14083. */
  14084. Engine.prototype.setFloatArray4 = function (uniform, array) {
  14085. if (!uniform || array.length % 4 !== 0)
  14086. return;
  14087. this._gl.uniform4fv(uniform, array);
  14088. };
  14089. /**
  14090. * Set the value of an uniform to an array of number
  14091. * @param uniform defines the webGL uniform location where to store the value
  14092. * @param array defines the array of number to store
  14093. */
  14094. Engine.prototype.setArray = function (uniform, array) {
  14095. if (!uniform)
  14096. return;
  14097. this._gl.uniform1fv(uniform, array);
  14098. };
  14099. /**
  14100. * Set the value of an uniform to an array of number (stored as vec2)
  14101. * @param uniform defines the webGL uniform location where to store the value
  14102. * @param array defines the array of number to store
  14103. */
  14104. Engine.prototype.setArray2 = function (uniform, array) {
  14105. if (!uniform || array.length % 2 !== 0)
  14106. return;
  14107. this._gl.uniform2fv(uniform, array);
  14108. };
  14109. /**
  14110. * Set the value of an uniform to an array of number (stored as vec3)
  14111. * @param uniform defines the webGL uniform location where to store the value
  14112. * @param array defines the array of number to store
  14113. */
  14114. Engine.prototype.setArray3 = function (uniform, array) {
  14115. if (!uniform || array.length % 3 !== 0)
  14116. return;
  14117. this._gl.uniform3fv(uniform, array);
  14118. };
  14119. /**
  14120. * Set the value of an uniform to an array of number (stored as vec4)
  14121. * @param uniform defines the webGL uniform location where to store the value
  14122. * @param array defines the array of number to store
  14123. */
  14124. Engine.prototype.setArray4 = function (uniform, array) {
  14125. if (!uniform || array.length % 4 !== 0)
  14126. return;
  14127. this._gl.uniform4fv(uniform, array);
  14128. };
  14129. /**
  14130. * Set the value of an uniform to an array of float32 (stored as matrices)
  14131. * @param uniform defines the webGL uniform location where to store the value
  14132. * @param matrices defines the array of float32 to store
  14133. */
  14134. Engine.prototype.setMatrices = function (uniform, matrices) {
  14135. if (!uniform)
  14136. return;
  14137. this._gl.uniformMatrix4fv(uniform, false, matrices);
  14138. };
  14139. /**
  14140. * Set the value of an uniform to a matrix
  14141. * @param uniform defines the webGL uniform location where to store the value
  14142. * @param matrix defines the matrix to store
  14143. */
  14144. Engine.prototype.setMatrix = function (uniform, matrix) {
  14145. if (!uniform)
  14146. return;
  14147. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  14148. };
  14149. /**
  14150. * Set the value of an uniform to a matrix (3x3)
  14151. * @param uniform defines the webGL uniform location where to store the value
  14152. * @param matrix defines the Float32Array representing the 3x3 matrix to store
  14153. */
  14154. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  14155. if (!uniform)
  14156. return;
  14157. this._gl.uniformMatrix3fv(uniform, false, matrix);
  14158. };
  14159. /**
  14160. * Set the value of an uniform to a matrix (2x2)
  14161. * @param uniform defines the webGL uniform location where to store the value
  14162. * @param matrix defines the Float32Array representing the 2x2 matrix to store
  14163. */
  14164. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  14165. if (!uniform)
  14166. return;
  14167. this._gl.uniformMatrix2fv(uniform, false, matrix);
  14168. };
  14169. /**
  14170. * Set the value of an uniform to a number (int)
  14171. * @param uniform defines the webGL uniform location where to store the value
  14172. * @param value defines the int number to store
  14173. */
  14174. Engine.prototype.setInt = function (uniform, value) {
  14175. if (!uniform)
  14176. return;
  14177. this._gl.uniform1i(uniform, value);
  14178. };
  14179. /**
  14180. * Set the value of an uniform to a number (float)
  14181. * @param uniform defines the webGL uniform location where to store the value
  14182. * @param value defines the float number to store
  14183. */
  14184. Engine.prototype.setFloat = function (uniform, value) {
  14185. if (!uniform)
  14186. return;
  14187. this._gl.uniform1f(uniform, value);
  14188. };
  14189. /**
  14190. * Set the value of an uniform to a vec2
  14191. * @param uniform defines the webGL uniform location where to store the value
  14192. * @param x defines the 1st component of the value
  14193. * @param y defines the 2nd component of the value
  14194. */
  14195. Engine.prototype.setFloat2 = function (uniform, x, y) {
  14196. if (!uniform)
  14197. return;
  14198. this._gl.uniform2f(uniform, x, y);
  14199. };
  14200. /**
  14201. * Set the value of an uniform to a vec3
  14202. * @param uniform defines the webGL uniform location where to store the value
  14203. * @param x defines the 1st component of the value
  14204. * @param y defines the 2nd component of the value
  14205. * @param z defines the 3rd component of the value
  14206. */
  14207. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  14208. if (!uniform)
  14209. return;
  14210. this._gl.uniform3f(uniform, x, y, z);
  14211. };
  14212. /**
  14213. * Set the value of an uniform to a boolean
  14214. * @param uniform defines the webGL uniform location where to store the value
  14215. * @param bool defines the boolean to store
  14216. */
  14217. Engine.prototype.setBool = function (uniform, bool) {
  14218. if (!uniform)
  14219. return;
  14220. this._gl.uniform1i(uniform, bool);
  14221. };
  14222. /**
  14223. * Set the value of an uniform to a vec4
  14224. * @param uniform defines the webGL uniform location where to store the value
  14225. * @param x defines the 1st component of the value
  14226. * @param y defines the 2nd component of the value
  14227. * @param z defines the 3rd component of the value
  14228. * @param w defines the 4th component of the value
  14229. */
  14230. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  14231. if (!uniform)
  14232. return;
  14233. this._gl.uniform4f(uniform, x, y, z, w);
  14234. };
  14235. /**
  14236. * Set the value of an uniform to a Color3
  14237. * @param uniform defines the webGL uniform location where to store the value
  14238. * @param color3 defines the color to store
  14239. */
  14240. Engine.prototype.setColor3 = function (uniform, color3) {
  14241. if (!uniform)
  14242. return;
  14243. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  14244. };
  14245. /**
  14246. * Set the value of an uniform to a Color3 and an alpha value
  14247. * @param uniform defines the webGL uniform location where to store the value
  14248. * @param color3 defines the color to store
  14249. * @param alpha defines the alpha component to store
  14250. */
  14251. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  14252. if (!uniform)
  14253. return;
  14254. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  14255. };
  14256. /**
  14257. * Sets a Color4 on a uniform variable
  14258. * @param uniform defines the uniform location
  14259. * @param color4 defines the value to be set
  14260. */
  14261. Engine.prototype.setDirectColor4 = function (uniform, color4) {
  14262. if (!uniform)
  14263. return;
  14264. this._gl.uniform4f(uniform, color4.r, color4.g, color4.b, color4.a);
  14265. };
  14266. // States
  14267. /**
  14268. * Set various states to the webGL context
  14269. * @param culling defines backface culling state
  14270. * @param zOffset defines the value to apply to zOffset (0 by default)
  14271. * @param force defines if states must be applied even if cache is up to date
  14272. * @param reverseSide defines if culling must be reversed (CCW instead of CW and CW instead of CCW)
  14273. */
  14274. Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  14275. if (zOffset === void 0) { zOffset = 0; }
  14276. if (reverseSide === void 0) { reverseSide = false; }
  14277. // Culling
  14278. if (this._depthCullingState.cull !== culling || force) {
  14279. this._depthCullingState.cull = culling;
  14280. }
  14281. // Cull face
  14282. var cullFace = this.cullBackFaces ? this._gl.BACK : this._gl.FRONT;
  14283. if (this._depthCullingState.cullFace !== cullFace || force) {
  14284. this._depthCullingState.cullFace = cullFace;
  14285. }
  14286. // Z offset
  14287. this.setZOffset(zOffset);
  14288. // Front face
  14289. var frontFace = reverseSide ? this._gl.CW : this._gl.CCW;
  14290. if (this._depthCullingState.frontFace !== frontFace || force) {
  14291. this._depthCullingState.frontFace = frontFace;
  14292. }
  14293. };
  14294. /**
  14295. * Set the z offset to apply to current rendering
  14296. * @param value defines the offset to apply
  14297. */
  14298. Engine.prototype.setZOffset = function (value) {
  14299. this._depthCullingState.zOffset = value;
  14300. };
  14301. /**
  14302. * Gets the current value of the zOffset
  14303. * @returns the current zOffset state
  14304. */
  14305. Engine.prototype.getZOffset = function () {
  14306. return this._depthCullingState.zOffset;
  14307. };
  14308. /**
  14309. * Enable or disable depth buffering
  14310. * @param enable defines the state to set
  14311. */
  14312. Engine.prototype.setDepthBuffer = function (enable) {
  14313. this._depthCullingState.depthTest = enable;
  14314. };
  14315. /**
  14316. * Gets a boolean indicating if depth writing is enabled
  14317. * @returns the current depth writing state
  14318. */
  14319. Engine.prototype.getDepthWrite = function () {
  14320. return this._depthCullingState.depthMask;
  14321. };
  14322. /**
  14323. * Enable or disable depth writing
  14324. * @param enable defines the state to set
  14325. */
  14326. Engine.prototype.setDepthWrite = function (enable) {
  14327. this._depthCullingState.depthMask = enable;
  14328. };
  14329. /**
  14330. * Enable or disable color writing
  14331. * @param enable defines the state to set
  14332. */
  14333. Engine.prototype.setColorWrite = function (enable) {
  14334. this._gl.colorMask(enable, enable, enable, enable);
  14335. this._colorWrite = enable;
  14336. };
  14337. /**
  14338. * Gets a boolean indicating if color writing is enabled
  14339. * @returns the current color writing state
  14340. */
  14341. Engine.prototype.getColorWrite = function () {
  14342. return this._colorWrite;
  14343. };
  14344. /**
  14345. * Sets alpha constants used by some alpha blending modes
  14346. * @param r defines the red component
  14347. * @param g defines the green component
  14348. * @param b defines the blue component
  14349. * @param a defines the alpha component
  14350. */
  14351. Engine.prototype.setAlphaConstants = function (r, g, b, a) {
  14352. this._alphaState.setAlphaBlendConstants(r, g, b, a);
  14353. };
  14354. /**
  14355. * Sets the current alpha mode
  14356. * @param mode defines the mode to use (one of the BABYLON.Engine.ALPHA_XXX)
  14357. * @param noDepthWriteChange defines if depth writing state should remains unchanged (false by default)
  14358. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered
  14359. */
  14360. Engine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  14361. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  14362. if (this._alphaMode === mode) {
  14363. return;
  14364. }
  14365. switch (mode) {
  14366. case Engine.ALPHA_DISABLE:
  14367. this._alphaState.alphaBlend = false;
  14368. break;
  14369. case Engine.ALPHA_PREMULTIPLIED:
  14370. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  14371. this._alphaState.alphaBlend = true;
  14372. break;
  14373. case Engine.ALPHA_PREMULTIPLIED_PORTERDUFF:
  14374. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  14375. this._alphaState.alphaBlend = true;
  14376. break;
  14377. case Engine.ALPHA_COMBINE:
  14378. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  14379. this._alphaState.alphaBlend = true;
  14380. break;
  14381. case Engine.ALPHA_ONEONE:
  14382. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  14383. this._alphaState.alphaBlend = true;
  14384. break;
  14385. case Engine.ALPHA_ADD:
  14386. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  14387. this._alphaState.alphaBlend = true;
  14388. break;
  14389. case Engine.ALPHA_SUBTRACT:
  14390. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  14391. this._alphaState.alphaBlend = true;
  14392. break;
  14393. case Engine.ALPHA_MULTIPLY:
  14394. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  14395. this._alphaState.alphaBlend = true;
  14396. break;
  14397. case Engine.ALPHA_MAXIMIZED:
  14398. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  14399. this._alphaState.alphaBlend = true;
  14400. break;
  14401. case Engine.ALPHA_INTERPOLATE:
  14402. this._alphaState.setAlphaBlendFunctionParameters(this._gl.CONSTANT_COLOR, this._gl.ONE_MINUS_CONSTANT_COLOR, this._gl.CONSTANT_ALPHA, this._gl.ONE_MINUS_CONSTANT_ALPHA);
  14403. this._alphaState.alphaBlend = true;
  14404. break;
  14405. case Engine.ALPHA_SCREENMODE:
  14406. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  14407. this._alphaState.alphaBlend = true;
  14408. break;
  14409. }
  14410. if (!noDepthWriteChange) {
  14411. this.setDepthWrite(mode === Engine.ALPHA_DISABLE);
  14412. }
  14413. this._alphaMode = mode;
  14414. };
  14415. /**
  14416. * Gets the current alpha mode
  14417. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered
  14418. * @returns the current alpha mode
  14419. */
  14420. Engine.prototype.getAlphaMode = function () {
  14421. return this._alphaMode;
  14422. };
  14423. // Textures
  14424. /**
  14425. * Force the entire cache to be cleared
  14426. * You should not have to use this function unless your engine needs to share the webGL context with another engine
  14427. * @param bruteForce defines a boolean to force clearing ALL caches (including stencil, detoh and alpha states)
  14428. */
  14429. Engine.prototype.wipeCaches = function (bruteForce) {
  14430. if (this.preventCacheWipeBetweenFrames && !bruteForce) {
  14431. return;
  14432. }
  14433. this._currentEffect = null;
  14434. if (bruteForce) {
  14435. this.resetTextureCache();
  14436. this._currentProgram = null;
  14437. this._stencilState.reset();
  14438. this._depthCullingState.reset();
  14439. this.setDepthFunctionToLessOrEqual();
  14440. this._alphaState.reset();
  14441. }
  14442. this._resetVertexBufferBinding();
  14443. this._cachedIndexBuffer = null;
  14444. this._cachedEffectForVertexBuffers = null;
  14445. this._unbindVertexArrayObject();
  14446. this.bindIndexBuffer(null);
  14447. };
  14448. /**
  14449. * Set the compressed texture format to use, based on the formats you have, and the formats
  14450. * supported by the hardware / browser.
  14451. *
  14452. * Khronos Texture Container (.ktx) files are used to support this. This format has the
  14453. * advantage of being specifically designed for OpenGL. Header elements directly correspond
  14454. * to API arguments needed to compressed textures. This puts the burden on the container
  14455. * generator to house the arcane code for determining these for current & future formats.
  14456. *
  14457. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  14458. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  14459. *
  14460. * Note: The result of this call is not taken into account when a texture is base64.
  14461. *
  14462. * @param formatsAvailable defines the list of those format families you have created
  14463. * on your server. Syntax: '-' + format family + '.ktx'. (Case and order do not matter.)
  14464. *
  14465. * Current families are astc, dxt, pvrtc, etc2, & etc1.
  14466. * @returns The extension selected.
  14467. */
  14468. Engine.prototype.setTextureFormatToUse = function (formatsAvailable) {
  14469. for (var i = 0, len1 = this.texturesSupported.length; i < len1; i++) {
  14470. for (var j = 0, len2 = formatsAvailable.length; j < len2; j++) {
  14471. if (this._texturesSupported[i] === formatsAvailable[j].toLowerCase()) {
  14472. return this._textureFormatInUse = this._texturesSupported[i];
  14473. }
  14474. }
  14475. }
  14476. // actively set format to nothing, to allow this to be called more than once
  14477. // and possibly fail the 2nd time
  14478. this._textureFormatInUse = null;
  14479. return null;
  14480. };
  14481. /** @hidden */
  14482. Engine.prototype._createTexture = function () {
  14483. var texture = this._gl.createTexture();
  14484. if (!texture) {
  14485. throw new Error("Unable to create texture");
  14486. }
  14487. return texture;
  14488. };
  14489. /**
  14490. * Usually called from BABYLON.Texture.ts.
  14491. * Passed information to create a WebGLTexture
  14492. * @param urlArg defines a value which contains one of the following:
  14493. * * A conventional http URL, e.g. 'http://...' or 'file://...'
  14494. * * A base64 string of in-line texture data, e.g. 'data:image/jpg;base64,/...'
  14495. * * An indicator that data being passed using the buffer parameter, e.g. 'data:mytexture.jpg'
  14496. * @param noMipmap defines a boolean indicating that no mipmaps shall be generated. Ignored for compressed textures. They must be in the file
  14497. * @param invertY when true, image is flipped when loaded. You probably want true. Ignored for compressed textures. Must be flipped in the file
  14498. * @param scene needed for loading to the correct scene
  14499. * @param samplingMode mode with should be used sample / access the texture (Default: BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  14500. * @param onLoad optional callback to be called upon successful completion
  14501. * @param onError optional callback to be called upon failure
  14502. * @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
  14503. * @param fallback an internal argument in case the function must be called again, due to etc1 not having alpha capabilities
  14504. * @param format internal format. Default: RGB when extension is '.jpg' else RGBA. Ignored for compressed textures
  14505. * @returns a InternalTexture for assignment back into BABYLON.Texture
  14506. */
  14507. Engine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallback, format) {
  14508. var _this = this;
  14509. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  14510. if (onLoad === void 0) { onLoad = null; }
  14511. if (onError === void 0) { onError = null; }
  14512. if (buffer === void 0) { buffer = null; }
  14513. if (fallback === void 0) { fallback = null; }
  14514. if (format === void 0) { format = null; }
  14515. var url = String(urlArg); // assign a new string, so that the original is still available in case of fallback
  14516. var fromData = url.substr(0, 5) === "data:";
  14517. var fromBlob = url.substr(0, 5) === "blob:";
  14518. var isBase64 = fromData && url.indexOf("base64") !== -1;
  14519. var texture = fallback ? fallback : new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  14520. // establish the file extension, if possible
  14521. var lastDot = url.lastIndexOf('.');
  14522. var extension = (lastDot > 0) ? url.substring(lastDot).toLowerCase() : "";
  14523. var isDDS = this.getCaps().s3tc && (extension.indexOf(".dds") === 0);
  14524. var isTGA = (extension.indexOf(".tga") === 0);
  14525. // determine if a ktx file should be substituted
  14526. var isKTX = false;
  14527. if (this._textureFormatInUse && !isBase64 && !fallback) {
  14528. url = url.substring(0, lastDot) + this._textureFormatInUse;
  14529. isKTX = true;
  14530. }
  14531. if (scene) {
  14532. scene._addPendingData(texture);
  14533. }
  14534. texture.url = url;
  14535. texture.generateMipMaps = !noMipmap;
  14536. texture.samplingMode = samplingMode;
  14537. texture.invertY = invertY;
  14538. if (!this._doNotHandleContextLost) {
  14539. // Keep a link to the buffer only if we plan to handle context lost
  14540. texture._buffer = buffer;
  14541. }
  14542. var onLoadObserver = null;
  14543. if (onLoad && !fallback) {
  14544. onLoadObserver = texture.onLoadedObservable.add(onLoad);
  14545. }
  14546. if (!fallback)
  14547. this._internalTexturesCache.push(texture);
  14548. var onerror = function (message, exception) {
  14549. if (scene) {
  14550. scene._removePendingData(texture);
  14551. }
  14552. if (onLoadObserver) {
  14553. texture.onLoadedObservable.remove(onLoadObserver);
  14554. }
  14555. // fallback for when compressed file not found to try again. For instance, etc1 does not have an alpha capable type
  14556. if (isKTX) {
  14557. _this.createTexture(urlArg, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  14558. }
  14559. else if (BABYLON.Tools.UseFallbackTexture) {
  14560. _this.createTexture(BABYLON.Tools.fallbackTexture, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  14561. }
  14562. if (onError) {
  14563. onError(message || "Unknown error", exception);
  14564. }
  14565. };
  14566. var callback = null;
  14567. // processing for non-image formats
  14568. if (isKTX || isTGA || isDDS) {
  14569. if (isKTX) {
  14570. callback = function (data) {
  14571. var ktx = new BABYLON.KhronosTextureContainer(data, 1);
  14572. _this._prepareWebGLTexture(texture, scene, ktx.pixelWidth, ktx.pixelHeight, invertY, false, true, function () {
  14573. ktx.uploadLevels(_this._gl, !noMipmap);
  14574. return false;
  14575. }, samplingMode);
  14576. };
  14577. }
  14578. else if (isTGA) {
  14579. callback = function (arrayBuffer) {
  14580. var data = new Uint8Array(arrayBuffer);
  14581. var header = BABYLON.TGATools.GetTGAHeader(data);
  14582. _this._prepareWebGLTexture(texture, scene, header.width, header.height, invertY, noMipmap, false, function () {
  14583. BABYLON.TGATools.UploadContent(_this._gl, data);
  14584. return false;
  14585. }, samplingMode);
  14586. };
  14587. }
  14588. else if (isDDS) {
  14589. callback = function (data) {
  14590. var info = BABYLON.DDSTools.GetDDSInfo(data);
  14591. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  14592. _this._prepareWebGLTexture(texture, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  14593. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 1);
  14594. return false;
  14595. }, samplingMode);
  14596. };
  14597. }
  14598. if (!buffer) {
  14599. this._loadFile(url, function (data) {
  14600. if (callback) {
  14601. callback(data);
  14602. }
  14603. }, undefined, scene ? scene.database : undefined, true, function (request, exception) {
  14604. onerror("Unable to load " + (request ? request.responseURL : url, exception));
  14605. });
  14606. }
  14607. else {
  14608. if (callback) {
  14609. callback(buffer);
  14610. }
  14611. }
  14612. // image format processing
  14613. }
  14614. else {
  14615. var onload = function (img) {
  14616. if (fromBlob && !_this._doNotHandleContextLost) {
  14617. // We need to store the image if we need to rebuild the texture
  14618. // in case of a webgl context lost
  14619. texture._buffer = img;
  14620. }
  14621. _this._prepareWebGLTexture(texture, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight, continuationCallback) {
  14622. var gl = _this._gl;
  14623. var isPot = (img.width === potWidth && img.height === potHeight);
  14624. var internalFormat = format ? _this._getInternalFormat(format) : ((extension === ".jpg") ? gl.RGB : gl.RGBA);
  14625. if (isPot) {
  14626. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  14627. return false;
  14628. }
  14629. // Using shaders to rescale because canvas.drawImage is lossy
  14630. var source = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  14631. _this._bindTextureDirectly(gl.TEXTURE_2D, source, true);
  14632. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  14633. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  14634. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  14635. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  14636. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  14637. _this._rescaleTexture(source, texture, scene, internalFormat, function () {
  14638. _this._releaseTexture(source);
  14639. _this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  14640. continuationCallback();
  14641. });
  14642. return true;
  14643. }, samplingMode);
  14644. };
  14645. if (!fromData || isBase64) {
  14646. if (buffer instanceof HTMLImageElement) {
  14647. onload(buffer);
  14648. }
  14649. else {
  14650. BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  14651. }
  14652. }
  14653. else if (typeof buffer === "string" || buffer instanceof ArrayBuffer || buffer instanceof Blob) {
  14654. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene ? scene.database : null);
  14655. }
  14656. else {
  14657. onload(buffer);
  14658. }
  14659. }
  14660. return texture;
  14661. };
  14662. Engine.prototype._rescaleTexture = function (source, destination, scene, internalFormat, onComplete) {
  14663. var _this = this;
  14664. var rtt = this.createRenderTargetTexture({
  14665. width: destination.width,
  14666. height: destination.height,
  14667. }, {
  14668. generateMipMaps: false,
  14669. type: Engine.TEXTURETYPE_UNSIGNED_INT,
  14670. samplingMode: BABYLON.Texture.BILINEAR_SAMPLINGMODE,
  14671. generateDepthBuffer: false,
  14672. generateStencilBuffer: false
  14673. });
  14674. if (!this._rescalePostProcess) {
  14675. this._rescalePostProcess = new BABYLON.PassPostProcess("rescale", 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this, false, Engine.TEXTURETYPE_UNSIGNED_INT);
  14676. }
  14677. this._rescalePostProcess.getEffect().executeWhenCompiled(function () {
  14678. _this._rescalePostProcess.onApply = function (effect) {
  14679. effect._bindTexture("textureSampler", source);
  14680. };
  14681. var hostingScene = scene;
  14682. if (!hostingScene) {
  14683. hostingScene = _this.scenes[_this.scenes.length - 1];
  14684. }
  14685. hostingScene.postProcessManager.directRender([_this._rescalePostProcess], rtt, true);
  14686. _this._bindTextureDirectly(_this._gl.TEXTURE_2D, destination, true);
  14687. _this._gl.copyTexImage2D(_this._gl.TEXTURE_2D, 0, internalFormat, 0, 0, destination.width, destination.height, 0);
  14688. _this.unBindFramebuffer(rtt);
  14689. _this._releaseTexture(rtt);
  14690. if (onComplete) {
  14691. onComplete();
  14692. }
  14693. });
  14694. };
  14695. /**
  14696. * Update a raw texture
  14697. * @param texture defines the texture to update
  14698. * @param data defines the data to store in the texture
  14699. * @param format defines the format of the data
  14700. * @param invertY defines if data must be stored with Y axis inverted
  14701. * @param compression defines the compression used (null by default)
  14702. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  14703. */
  14704. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression, type) {
  14705. if (compression === void 0) { compression = null; }
  14706. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  14707. if (!texture) {
  14708. return;
  14709. }
  14710. // babylon's internalSizedFomat but gl's texImage2D internalFormat
  14711. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type, format);
  14712. // babylon's internalFormat but gl's texImage2D format
  14713. var internalFormat = this._getInternalFormat(format);
  14714. var textureType = this._getWebGLTextureType(type);
  14715. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14716. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  14717. if (!this._doNotHandleContextLost) {
  14718. texture._bufferView = data;
  14719. texture.format = format;
  14720. texture.type = type;
  14721. texture.invertY = invertY;
  14722. texture._compression = compression;
  14723. }
  14724. if (texture.width % 4 !== 0) {
  14725. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  14726. }
  14727. if (compression && data) {
  14728. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, 0, data);
  14729. }
  14730. else {
  14731. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, data);
  14732. }
  14733. if (texture.generateMipMaps) {
  14734. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14735. }
  14736. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14737. // this.resetTextureCache();
  14738. texture.isReady = true;
  14739. };
  14740. /**
  14741. * Creates a raw texture
  14742. * @param data defines the data to store in the texture
  14743. * @param width defines the width of the texture
  14744. * @param height defines the height of the texture
  14745. * @param format defines the format of the data
  14746. * @param generateMipMaps defines if the engine should generate the mip levels
  14747. * @param invertY defines if data must be stored with Y axis inverted
  14748. * @param samplingMode defines the required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)
  14749. * @param compression defines the compression used (null by default)
  14750. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  14751. * @returns the raw texture inside an InternalTexture
  14752. */
  14753. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression, type) {
  14754. if (compression === void 0) { compression = null; }
  14755. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  14756. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW);
  14757. texture.baseWidth = width;
  14758. texture.baseHeight = height;
  14759. texture.width = width;
  14760. texture.height = height;
  14761. texture.format = format;
  14762. texture.generateMipMaps = generateMipMaps;
  14763. texture.samplingMode = samplingMode;
  14764. texture.invertY = invertY;
  14765. texture._compression = compression;
  14766. texture.type = type;
  14767. if (!this._doNotHandleContextLost) {
  14768. texture._bufferView = data;
  14769. }
  14770. this.updateRawTexture(texture, data, format, invertY, compression, type);
  14771. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14772. // Filters
  14773. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  14774. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  14775. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14776. if (generateMipMaps) {
  14777. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14778. }
  14779. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14780. this._internalTexturesCache.push(texture);
  14781. return texture;
  14782. };
  14783. /**
  14784. * Creates a dynamic texture
  14785. * @param width defines the width of the texture
  14786. * @param height defines the height of the texture
  14787. * @param generateMipMaps defines if the engine should generate the mip levels
  14788. * @param samplingMode defines the required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)
  14789. * @returns the dynamic texture inside an InternalTexture
  14790. */
  14791. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  14792. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DYNAMIC);
  14793. texture.baseWidth = width;
  14794. texture.baseHeight = height;
  14795. if (generateMipMaps) {
  14796. width = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize) : width;
  14797. height = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize) : height;
  14798. }
  14799. // this.resetTextureCache();
  14800. texture.width = width;
  14801. texture.height = height;
  14802. texture.isReady = false;
  14803. texture.generateMipMaps = generateMipMaps;
  14804. texture.samplingMode = samplingMode;
  14805. this.updateTextureSamplingMode(samplingMode, texture);
  14806. this._internalTexturesCache.push(texture);
  14807. return texture;
  14808. };
  14809. /**
  14810. * Update the sampling mode of a given texture
  14811. * @param samplingMode defines the required sampling mode
  14812. * @param texture defines the texture to update
  14813. */
  14814. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  14815. var filters = getSamplingParameters(samplingMode, texture.generateMipMaps, this._gl);
  14816. if (texture.isCube) {
  14817. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  14818. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14819. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  14820. }
  14821. else if (texture.is3D) {
  14822. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  14823. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14824. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  14825. }
  14826. else {
  14827. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  14828. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14829. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14830. }
  14831. texture.samplingMode = samplingMode;
  14832. };
  14833. /**
  14834. * Update the content of a dynamic texture
  14835. * @param texture defines the texture to update
  14836. * @param canvas defines the canvas containing the source
  14837. * @param invertY defines if data must be stored with Y axis inverted
  14838. * @param premulAlpha defines if alpha is stored as premultiplied
  14839. * @param format defines the format of the data
  14840. */
  14841. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha, format) {
  14842. if (premulAlpha === void 0) { premulAlpha = false; }
  14843. if (!texture) {
  14844. return;
  14845. }
  14846. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14847. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  14848. if (premulAlpha) {
  14849. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1);
  14850. }
  14851. var internalFormat = format ? this._getInternalFormat(format) : this._gl.RGBA;
  14852. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, internalFormat, this._gl.UNSIGNED_BYTE, canvas);
  14853. if (texture.generateMipMaps) {
  14854. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14855. }
  14856. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14857. if (premulAlpha) {
  14858. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 0);
  14859. }
  14860. texture.isReady = true;
  14861. };
  14862. /**
  14863. * Update a video texture
  14864. * @param texture defines the texture to update
  14865. * @param video defines the video element to use
  14866. * @param invertY defines if data must be stored with Y axis inverted
  14867. */
  14868. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  14869. if (!texture || texture._isDisabled) {
  14870. return;
  14871. }
  14872. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14873. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  14874. try {
  14875. // Testing video texture support
  14876. if (this._videoTextureSupported === undefined) {
  14877. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  14878. if (this._gl.getError() !== 0) {
  14879. this._videoTextureSupported = false;
  14880. }
  14881. else {
  14882. this._videoTextureSupported = true;
  14883. }
  14884. }
  14885. // Copy video through the current working canvas if video texture is not supported
  14886. if (!this._videoTextureSupported) {
  14887. if (!texture._workingCanvas) {
  14888. texture._workingCanvas = document.createElement("canvas");
  14889. var context = texture._workingCanvas.getContext("2d");
  14890. if (!context) {
  14891. throw new Error("Unable to get 2d context");
  14892. }
  14893. texture._workingContext = context;
  14894. texture._workingCanvas.width = texture.width;
  14895. texture._workingCanvas.height = texture.height;
  14896. }
  14897. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture.width, texture.height);
  14898. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  14899. }
  14900. else {
  14901. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  14902. }
  14903. if (texture.generateMipMaps) {
  14904. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14905. }
  14906. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14907. // this.resetTextureCache();
  14908. texture.isReady = true;
  14909. }
  14910. catch (ex) {
  14911. // Something unexpected
  14912. // Let's disable the texture
  14913. texture._isDisabled = true;
  14914. }
  14915. };
  14916. /**
  14917. * Updates a depth texture Comparison Mode and Function.
  14918. * If the comparison Function is equal to 0, the mode will be set to none.
  14919. * Otherwise, this only works in webgl 2 and requires a shadow sampler in the shader.
  14920. * @param texture The texture to set the comparison function for
  14921. * @param comparisonFunction The comparison function to set, 0 if no comparison required
  14922. */
  14923. Engine.prototype.updateTextureComparisonFunction = function (texture, comparisonFunction) {
  14924. if (this.webGLVersion === 1) {
  14925. BABYLON.Tools.Error("WebGL 1 does not support texture comparison.");
  14926. return;
  14927. }
  14928. var gl = this._gl;
  14929. if (texture.isCube) {
  14930. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  14931. if (comparisonFunction === 0) {
  14932. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  14933. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  14934. }
  14935. else {
  14936. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  14937. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  14938. }
  14939. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  14940. }
  14941. else {
  14942. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14943. if (comparisonFunction === 0) {
  14944. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  14945. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  14946. }
  14947. else {
  14948. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  14949. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  14950. }
  14951. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14952. }
  14953. texture._comparisonFunction = comparisonFunction;
  14954. };
  14955. Engine.prototype._setupDepthStencilTexture = function (internalTexture, size, generateStencil, bilinearFiltering, comparisonFunction) {
  14956. var width = size.width || size;
  14957. var height = size.height || size;
  14958. internalTexture.baseWidth = width;
  14959. internalTexture.baseHeight = height;
  14960. internalTexture.width = width;
  14961. internalTexture.height = height;
  14962. internalTexture.isReady = true;
  14963. internalTexture.samples = 1;
  14964. internalTexture.generateMipMaps = false;
  14965. internalTexture._generateDepthBuffer = true;
  14966. internalTexture._generateStencilBuffer = generateStencil;
  14967. internalTexture.samplingMode = bilinearFiltering ? BABYLON.Texture.BILINEAR_SAMPLINGMODE : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  14968. internalTexture.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  14969. internalTexture._comparisonFunction = comparisonFunction;
  14970. var gl = this._gl;
  14971. var target = internalTexture.isCube ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D;
  14972. var samplingParameters = getSamplingParameters(internalTexture.samplingMode, false, gl);
  14973. gl.texParameteri(target, gl.TEXTURE_MAG_FILTER, samplingParameters.mag);
  14974. gl.texParameteri(target, gl.TEXTURE_MIN_FILTER, samplingParameters.min);
  14975. gl.texParameteri(target, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  14976. gl.texParameteri(target, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  14977. if (comparisonFunction === 0) {
  14978. gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  14979. gl.texParameteri(target, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  14980. }
  14981. else {
  14982. gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  14983. gl.texParameteri(target, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  14984. }
  14985. };
  14986. /**
  14987. * Creates a depth stencil texture.
  14988. * This is only available in WebGL 2 or with the depth texture extension available.
  14989. * @param size The size of face edge in the texture.
  14990. * @param options The options defining the texture.
  14991. * @returns The texture
  14992. */
  14993. Engine.prototype.createDepthStencilTexture = function (size, options) {
  14994. if (options.isCube) {
  14995. var width = size.width || size;
  14996. return this._createDepthStencilCubeTexture(width, options);
  14997. }
  14998. else {
  14999. return this._createDepthStencilTexture(size, options);
  15000. }
  15001. };
  15002. /**
  15003. * Creates a depth stencil texture.
  15004. * This is only available in WebGL 2 or with the depth texture extension available.
  15005. * @param size The size of face edge in the texture.
  15006. * @param options The options defining the texture.
  15007. * @returns The texture
  15008. */
  15009. Engine.prototype._createDepthStencilTexture = function (size, options) {
  15010. var internalTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DEPTHTEXTURE);
  15011. if (!this._caps.depthTextureExtension) {
  15012. BABYLON.Tools.Error("Depth texture is not supported by your browser or hardware.");
  15013. return internalTexture;
  15014. }
  15015. var internalOptions = __assign({ bilinearFiltering: false, comparisonFunction: 0, generateStencil: false }, options);
  15016. var gl = this._gl;
  15017. this._bindTextureDirectly(gl.TEXTURE_2D, internalTexture, true);
  15018. this._setupDepthStencilTexture(internalTexture, size, internalOptions.generateStencil, internalOptions.bilinearFiltering, internalOptions.comparisonFunction);
  15019. if (this.webGLVersion > 1) {
  15020. if (internalOptions.generateStencil) {
  15021. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH24_STENCIL8, internalTexture.width, internalTexture.height, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
  15022. }
  15023. else {
  15024. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT24, internalTexture.width, internalTexture.height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  15025. }
  15026. }
  15027. else {
  15028. if (internalOptions.generateStencil) {
  15029. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_STENCIL, internalTexture.width, internalTexture.height, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
  15030. }
  15031. else {
  15032. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT, internalTexture.width, internalTexture.height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  15033. }
  15034. }
  15035. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  15036. return internalTexture;
  15037. };
  15038. /**
  15039. * Creates a depth stencil cube texture.
  15040. * This is only available in WebGL 2.
  15041. * @param size The size of face edge in the cube texture.
  15042. * @param options The options defining the cube texture.
  15043. * @returns The cube texture
  15044. */
  15045. Engine.prototype._createDepthStencilCubeTexture = function (size, options) {
  15046. var internalTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_UNKNOWN);
  15047. internalTexture.isCube = true;
  15048. if (this.webGLVersion === 1) {
  15049. BABYLON.Tools.Error("Depth cube texture is not supported by WebGL 1.");
  15050. return internalTexture;
  15051. }
  15052. var internalOptions = __assign({ bilinearFiltering: false, comparisonFunction: 0, generateStencil: false }, options);
  15053. var gl = this._gl;
  15054. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, internalTexture, true);
  15055. this._setupDepthStencilTexture(internalTexture, size, internalOptions.generateStencil, internalOptions.bilinearFiltering, internalOptions.comparisonFunction);
  15056. // Create the depth/stencil buffer
  15057. for (var face = 0; face < 6; face++) {
  15058. if (internalOptions.generateStencil) {
  15059. 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);
  15060. }
  15061. else {
  15062. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + face, 0, gl.DEPTH_COMPONENT24, size, size, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  15063. }
  15064. }
  15065. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15066. return internalTexture;
  15067. };
  15068. /**
  15069. * Sets the frame buffer Depth / Stencil attachement of the render target to the defined depth stencil texture.
  15070. * @param renderTarget The render target to set the frame buffer for
  15071. */
  15072. Engine.prototype.setFrameBufferDepthStencilTexture = function (renderTarget) {
  15073. // Create the framebuffer
  15074. var internalTexture = renderTarget.getInternalTexture();
  15075. if (!internalTexture || !internalTexture._framebuffer || !renderTarget.depthStencilTexture) {
  15076. return;
  15077. }
  15078. var gl = this._gl;
  15079. var depthStencilTexture = renderTarget.depthStencilTexture;
  15080. this.bindUnboundFramebuffer(internalTexture._framebuffer);
  15081. if (depthStencilTexture.isCube) {
  15082. if (depthStencilTexture._generateStencilBuffer) {
  15083. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X, depthStencilTexture._webGLTexture, 0);
  15084. }
  15085. else {
  15086. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X, depthStencilTexture._webGLTexture, 0);
  15087. }
  15088. }
  15089. else {
  15090. if (depthStencilTexture._generateStencilBuffer) {
  15091. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_2D, depthStencilTexture._webGLTexture, 0);
  15092. }
  15093. else {
  15094. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthStencilTexture._webGLTexture, 0);
  15095. }
  15096. }
  15097. this.bindUnboundFramebuffer(null);
  15098. };
  15099. /**
  15100. * Creates a new render target texture
  15101. * @param size defines the size of the texture
  15102. * @param options defines the options used to create the texture
  15103. * @returns a new render target texture stored in an InternalTexture
  15104. */
  15105. Engine.prototype.createRenderTargetTexture = function (size, options) {
  15106. var fullOptions = new RenderTargetCreationOptions();
  15107. if (options !== undefined && typeof options === "object") {
  15108. fullOptions.generateMipMaps = options.generateMipMaps;
  15109. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  15110. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  15111. fullOptions.type = options.type === undefined ? Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  15112. fullOptions.samplingMode = options.samplingMode === undefined ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : options.samplingMode;
  15113. fullOptions.format = options.format === undefined ? Engine.TEXTUREFORMAT_RGBA : options.format;
  15114. }
  15115. else {
  15116. fullOptions.generateMipMaps = options;
  15117. fullOptions.generateDepthBuffer = true;
  15118. fullOptions.generateStencilBuffer = false;
  15119. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15120. fullOptions.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  15121. fullOptions.format = Engine.TEXTUREFORMAT_RGBA;
  15122. }
  15123. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  15124. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  15125. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  15126. }
  15127. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  15128. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  15129. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  15130. }
  15131. var gl = this._gl;
  15132. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  15133. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  15134. var width = size.width || size;
  15135. var height = size.height || size;
  15136. var filters = getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps ? true : false, gl);
  15137. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  15138. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15139. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  15140. }
  15141. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  15142. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  15143. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15144. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15145. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(fullOptions.type, fullOptions.format), width, height, 0, this._getInternalFormat(fullOptions.format), this._getWebGLTextureType(fullOptions.type), null);
  15146. // Create the framebuffer
  15147. var currentFrameBuffer = this._currentFramebuffer;
  15148. var framebuffer = gl.createFramebuffer();
  15149. this.bindUnboundFramebuffer(framebuffer);
  15150. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  15151. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer ? true : false, fullOptions.generateDepthBuffer, width, height);
  15152. if (fullOptions.generateMipMaps) {
  15153. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  15154. }
  15155. // Unbind
  15156. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  15157. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15158. this.bindUnboundFramebuffer(currentFrameBuffer);
  15159. texture._framebuffer = framebuffer;
  15160. texture.baseWidth = width;
  15161. texture.baseHeight = height;
  15162. texture.width = width;
  15163. texture.height = height;
  15164. texture.isReady = true;
  15165. texture.samples = 1;
  15166. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  15167. texture.samplingMode = fullOptions.samplingMode;
  15168. texture.type = fullOptions.type;
  15169. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  15170. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  15171. // this.resetTextureCache();
  15172. this._internalTexturesCache.push(texture);
  15173. return texture;
  15174. };
  15175. /**
  15176. * Create a multi render target texture
  15177. * @see http://doc.babylonjs.com/features/webgl2#multiple-render-target
  15178. * @param size defines the size of the texture
  15179. * @param options defines the creation options
  15180. * @returns the cube texture as an InternalTexture
  15181. */
  15182. Engine.prototype.createMultipleRenderTarget = function (size, options) {
  15183. var generateMipMaps = false;
  15184. var generateDepthBuffer = true;
  15185. var generateStencilBuffer = false;
  15186. var generateDepthTexture = false;
  15187. var textureCount = 1;
  15188. var defaultType = Engine.TEXTURETYPE_UNSIGNED_INT;
  15189. var defaultSamplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  15190. var types = new Array();
  15191. var samplingModes = new Array();
  15192. if (options !== undefined) {
  15193. generateMipMaps = options.generateMipMaps === undefined ? false : options.generateMipMaps;
  15194. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  15195. generateStencilBuffer = options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  15196. generateDepthTexture = options.generateDepthTexture === undefined ? false : options.generateDepthTexture;
  15197. textureCount = options.textureCount || 1;
  15198. if (options.types) {
  15199. types = options.types;
  15200. }
  15201. if (options.samplingModes) {
  15202. samplingModes = options.samplingModes;
  15203. }
  15204. }
  15205. var gl = this._gl;
  15206. // Create the framebuffer
  15207. var framebuffer = gl.createFramebuffer();
  15208. this.bindUnboundFramebuffer(framebuffer);
  15209. var width = size.width || size;
  15210. var height = size.height || size;
  15211. var textures = [];
  15212. var attachments = [];
  15213. var depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, width, height);
  15214. for (var i = 0; i < textureCount; i++) {
  15215. var samplingMode = samplingModes[i] || defaultSamplingMode;
  15216. var type = types[i] || defaultType;
  15217. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  15218. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  15219. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  15220. }
  15221. else if (type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  15222. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  15223. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  15224. }
  15225. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  15226. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  15227. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15228. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  15229. }
  15230. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  15231. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  15232. textures.push(texture);
  15233. attachments.push(attachment);
  15234. gl.activeTexture(gl["TEXTURE" + i]);
  15235. gl.bindTexture(gl.TEXTURE_2D, texture._webGLTexture);
  15236. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  15237. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  15238. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15239. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15240. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), width, height, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  15241. gl.framebufferTexture2D(gl.DRAW_FRAMEBUFFER, attachment, gl.TEXTURE_2D, texture._webGLTexture, 0);
  15242. if (generateMipMaps) {
  15243. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  15244. }
  15245. // Unbind
  15246. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  15247. texture._framebuffer = framebuffer;
  15248. texture._depthStencilBuffer = depthStencilBuffer;
  15249. texture.baseWidth = width;
  15250. texture.baseHeight = height;
  15251. texture.width = width;
  15252. texture.height = height;
  15253. texture.isReady = true;
  15254. texture.samples = 1;
  15255. texture.generateMipMaps = generateMipMaps;
  15256. texture.samplingMode = samplingMode;
  15257. texture.type = type;
  15258. texture._generateDepthBuffer = generateDepthBuffer;
  15259. texture._generateStencilBuffer = generateStencilBuffer;
  15260. texture._attachments = attachments;
  15261. this._internalTexturesCache.push(texture);
  15262. }
  15263. if (generateDepthTexture && this._caps.depthTextureExtension) {
  15264. // Depth texture
  15265. var depthTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  15266. gl.activeTexture(gl.TEXTURE0);
  15267. gl.bindTexture(gl.TEXTURE_2D, depthTexture._webGLTexture);
  15268. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  15269. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  15270. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15271. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15272. 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);
  15273. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthTexture._webGLTexture, 0);
  15274. depthTexture._framebuffer = framebuffer;
  15275. depthTexture.baseWidth = width;
  15276. depthTexture.baseHeight = height;
  15277. depthTexture.width = width;
  15278. depthTexture.height = height;
  15279. depthTexture.isReady = true;
  15280. depthTexture.samples = 1;
  15281. depthTexture.generateMipMaps = generateMipMaps;
  15282. depthTexture.samplingMode = gl.NEAREST;
  15283. depthTexture._generateDepthBuffer = generateDepthBuffer;
  15284. depthTexture._generateStencilBuffer = generateStencilBuffer;
  15285. textures.push(depthTexture);
  15286. this._internalTexturesCache.push(depthTexture);
  15287. }
  15288. gl.drawBuffers(attachments);
  15289. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15290. this.bindUnboundFramebuffer(null);
  15291. this.resetTextureCache();
  15292. return textures;
  15293. };
  15294. Engine.prototype._setupFramebufferDepthAttachments = function (generateStencilBuffer, generateDepthBuffer, width, height, samples) {
  15295. if (samples === void 0) { samples = 1; }
  15296. var depthStencilBuffer = null;
  15297. var gl = this._gl;
  15298. // Create the depth/stencil buffer
  15299. if (generateStencilBuffer) {
  15300. depthStencilBuffer = gl.createRenderbuffer();
  15301. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  15302. if (samples > 1) {
  15303. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH24_STENCIL8, width, height);
  15304. }
  15305. else {
  15306. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height);
  15307. }
  15308. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  15309. }
  15310. else if (generateDepthBuffer) {
  15311. depthStencilBuffer = gl.createRenderbuffer();
  15312. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  15313. if (samples > 1) {
  15314. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH_COMPONENT16, width, height);
  15315. }
  15316. else {
  15317. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  15318. }
  15319. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  15320. }
  15321. return depthStencilBuffer;
  15322. };
  15323. /**
  15324. * Updates the sample count of a render target texture
  15325. * @see http://doc.babylonjs.com/features/webgl2#multisample-render-targets
  15326. * @param texture defines the texture to update
  15327. * @param samples defines the sample count to set
  15328. * @returns the effective sample count (could be 0 if multisample render targets are not supported)
  15329. */
  15330. Engine.prototype.updateRenderTargetTextureSampleCount = function (texture, samples) {
  15331. if (this.webGLVersion < 2 || !texture) {
  15332. return 1;
  15333. }
  15334. if (texture.samples === samples) {
  15335. return samples;
  15336. }
  15337. var gl = this._gl;
  15338. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  15339. // Dispose previous render buffers
  15340. if (texture._depthStencilBuffer) {
  15341. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  15342. texture._depthStencilBuffer = null;
  15343. }
  15344. if (texture._MSAAFramebuffer) {
  15345. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  15346. texture._MSAAFramebuffer = null;
  15347. }
  15348. if (texture._MSAARenderBuffer) {
  15349. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  15350. texture._MSAARenderBuffer = null;
  15351. }
  15352. if (samples > 1) {
  15353. var framebuffer = gl.createFramebuffer();
  15354. if (!framebuffer) {
  15355. throw new Error("Unable to create multi sampled framebuffer");
  15356. }
  15357. texture._MSAAFramebuffer = framebuffer;
  15358. this.bindUnboundFramebuffer(texture._MSAAFramebuffer);
  15359. var colorRenderbuffer = gl.createRenderbuffer();
  15360. if (!colorRenderbuffer) {
  15361. throw new Error("Unable to create multi sampled framebuffer");
  15362. }
  15363. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  15364. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  15365. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, colorRenderbuffer);
  15366. texture._MSAARenderBuffer = colorRenderbuffer;
  15367. }
  15368. else {
  15369. this.bindUnboundFramebuffer(texture._framebuffer);
  15370. }
  15371. texture.samples = samples;
  15372. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(texture._generateStencilBuffer, texture._generateDepthBuffer, texture.width, texture.height, samples);
  15373. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15374. this.bindUnboundFramebuffer(null);
  15375. return samples;
  15376. };
  15377. /**
  15378. * Update the sample count for a given multiple render target texture
  15379. * @see http://doc.babylonjs.com/features/webgl2#multisample-render-targets
  15380. * @param textures defines the textures to update
  15381. * @param samples defines the sample count to set
  15382. * @returns the effective sample count (could be 0 if multisample render targets are not supported)
  15383. */
  15384. Engine.prototype.updateMultipleRenderTargetTextureSampleCount = function (textures, samples) {
  15385. if (this.webGLVersion < 2 || !textures || textures.length == 0) {
  15386. return 1;
  15387. }
  15388. if (textures[0].samples === samples) {
  15389. return samples;
  15390. }
  15391. var gl = this._gl;
  15392. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  15393. // Dispose previous render buffers
  15394. if (textures[0]._depthStencilBuffer) {
  15395. gl.deleteRenderbuffer(textures[0]._depthStencilBuffer);
  15396. textures[0]._depthStencilBuffer = null;
  15397. }
  15398. if (textures[0]._MSAAFramebuffer) {
  15399. gl.deleteFramebuffer(textures[0]._MSAAFramebuffer);
  15400. textures[0]._MSAAFramebuffer = null;
  15401. }
  15402. for (var i = 0; i < textures.length; i++) {
  15403. if (textures[i]._MSAARenderBuffer) {
  15404. gl.deleteRenderbuffer(textures[i]._MSAARenderBuffer);
  15405. textures[i]._MSAARenderBuffer = null;
  15406. }
  15407. }
  15408. if (samples > 1) {
  15409. var framebuffer = gl.createFramebuffer();
  15410. if (!framebuffer) {
  15411. throw new Error("Unable to create multi sampled framebuffer");
  15412. }
  15413. this.bindUnboundFramebuffer(framebuffer);
  15414. var depthStencilBuffer = this._setupFramebufferDepthAttachments(textures[0]._generateStencilBuffer, textures[0]._generateDepthBuffer, textures[0].width, textures[0].height, samples);
  15415. var attachments = [];
  15416. for (var i = 0; i < textures.length; i++) {
  15417. var texture = textures[i];
  15418. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  15419. var colorRenderbuffer = gl.createRenderbuffer();
  15420. if (!colorRenderbuffer) {
  15421. throw new Error("Unable to create multi sampled framebuffer");
  15422. }
  15423. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  15424. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  15425. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, attachment, gl.RENDERBUFFER, colorRenderbuffer);
  15426. texture._MSAAFramebuffer = framebuffer;
  15427. texture._MSAARenderBuffer = colorRenderbuffer;
  15428. texture.samples = samples;
  15429. texture._depthStencilBuffer = depthStencilBuffer;
  15430. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15431. attachments.push(attachment);
  15432. }
  15433. gl.drawBuffers(attachments);
  15434. }
  15435. else {
  15436. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  15437. }
  15438. this.bindUnboundFramebuffer(null);
  15439. return samples;
  15440. };
  15441. /** @hidden */
  15442. Engine.prototype._uploadDataToTexture = function (target, lod, internalFormat, width, height, format, type, data) {
  15443. this._gl.texImage2D(target, lod, internalFormat, width, height, 0, format, type, data);
  15444. };
  15445. /** @hidden */
  15446. Engine.prototype._uploadCompressedDataToTexture = function (target, lod, internalFormat, width, height, data) {
  15447. this._gl.compressedTexImage2D(target, lod, internalFormat, width, height, 0, data);
  15448. };
  15449. /**
  15450. * Creates a new render target cube texture
  15451. * @param size defines the size of the texture
  15452. * @param options defines the options used to create the texture
  15453. * @returns a new render target cube texture stored in an InternalTexture
  15454. */
  15455. Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
  15456. var fullOptions = __assign({ generateMipMaps: true, generateDepthBuffer: true, generateStencilBuffer: false, type: Engine.TEXTURETYPE_UNSIGNED_INT, samplingMode: BABYLON.Texture.TRILINEAR_SAMPLINGMODE, format: Engine.TEXTUREFORMAT_RGBA }, options);
  15457. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && fullOptions.generateStencilBuffer;
  15458. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  15459. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  15460. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  15461. }
  15462. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  15463. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  15464. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  15465. }
  15466. var gl = this._gl;
  15467. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  15468. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15469. var filters = getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps, gl);
  15470. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  15471. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15472. BABYLON.Tools.Warn("Float textures are not supported. Cube render target forced to TEXTURETYPE_UNESIGNED_BYTE type");
  15473. }
  15474. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  15475. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  15476. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15477. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15478. for (var face = 0; face < 6; face++) {
  15479. 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);
  15480. }
  15481. // Create the framebuffer
  15482. var framebuffer = gl.createFramebuffer();
  15483. this.bindUnboundFramebuffer(framebuffer);
  15484. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer, fullOptions.generateDepthBuffer, size, size);
  15485. // MipMaps
  15486. if (fullOptions.generateMipMaps) {
  15487. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  15488. }
  15489. // Unbind
  15490. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15491. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15492. this.bindUnboundFramebuffer(null);
  15493. texture._framebuffer = framebuffer;
  15494. texture.width = size;
  15495. texture.height = size;
  15496. texture.isReady = true;
  15497. texture.isCube = true;
  15498. texture.samples = 1;
  15499. texture.generateMipMaps = fullOptions.generateMipMaps;
  15500. texture.samplingMode = fullOptions.samplingMode;
  15501. texture.type = fullOptions.type;
  15502. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  15503. texture._generateStencilBuffer = fullOptions.generateStencilBuffer;
  15504. this._internalTexturesCache.push(texture);
  15505. return texture;
  15506. };
  15507. /**
  15508. * Create a cube texture from prefiltered data (ie. the mipmaps contain ready to use data for PBR reflection)
  15509. * @param rootUrl defines the url where the file to load is located
  15510. * @param scene defines the current scene
  15511. * @param scale defines scale to apply to the mip map selection
  15512. * @param offset defines offset to apply to the mip map selection
  15513. * @param onLoad defines an optional callback raised when the texture is loaded
  15514. * @param onError defines an optional callback raised if there is an issue to load the texture
  15515. * @param format defines the format of the data
  15516. * @param forcedExtension defines the extension to use to pick the right loader
  15517. * @param createPolynomials defines wheter or not to create polynomails harmonics for the texture
  15518. * @returns the cube texture as an InternalTexture
  15519. */
  15520. Engine.prototype.createPrefilteredCubeTexture = function (rootUrl, scene, scale, offset, onLoad, onError, format, forcedExtension, createPolynomials) {
  15521. var _this = this;
  15522. if (onLoad === void 0) { onLoad = null; }
  15523. if (onError === void 0) { onError = null; }
  15524. if (forcedExtension === void 0) { forcedExtension = null; }
  15525. if (createPolynomials === void 0) { createPolynomials = true; }
  15526. var callback = function (loadData) {
  15527. if (!loadData) {
  15528. if (onLoad) {
  15529. onLoad(null);
  15530. }
  15531. return;
  15532. }
  15533. var texture = loadData.texture;
  15534. if (!createPolynomials) {
  15535. texture._sphericalPolynomial = new BABYLON.SphericalPolynomial();
  15536. }
  15537. else if (loadData.info.sphericalPolynomial) {
  15538. texture._sphericalPolynomial = loadData.info.sphericalPolynomial;
  15539. }
  15540. texture._dataSource = BABYLON.InternalTexture.DATASOURCE_CUBEPREFILTERED;
  15541. texture._lodGenerationScale = scale;
  15542. texture._lodGenerationOffset = offset;
  15543. if (_this._caps.textureLOD) {
  15544. // Do not add extra process if texture lod is supported.
  15545. if (onLoad) {
  15546. onLoad(texture);
  15547. }
  15548. return;
  15549. }
  15550. var mipSlices = 3;
  15551. var gl = _this._gl;
  15552. var width = loadData.width;
  15553. if (!width) {
  15554. return;
  15555. }
  15556. var textures = [];
  15557. for (var i = 0; i < mipSlices; i++) {
  15558. //compute LOD from even spacing in smoothness (matching shader calculation)
  15559. var smoothness = i / (mipSlices - 1);
  15560. var roughness = 1 - smoothness;
  15561. var minLODIndex = offset; // roughness = 0
  15562. var maxLODIndex = BABYLON.Scalar.Log2(width) * scale + offset; // roughness = 1
  15563. var lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness;
  15564. var mipmapIndex = Math.round(Math.min(Math.max(lodIndex, 0), maxLODIndex));
  15565. var glTextureFromLod = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  15566. glTextureFromLod.isCube = true;
  15567. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, glTextureFromLod, true);
  15568. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  15569. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  15570. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15571. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15572. if (loadData.isDDS) {
  15573. var info = loadData.info;
  15574. var data = loadData.data;
  15575. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  15576. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, true, 6, mipmapIndex);
  15577. }
  15578. else {
  15579. BABYLON.Tools.Warn("DDS is the only prefiltered cube map supported so far.");
  15580. }
  15581. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15582. // Wrap in a base texture for easy binding.
  15583. var lodTexture = new BABYLON.BaseTexture(scene);
  15584. lodTexture.isCube = true;
  15585. lodTexture._texture = glTextureFromLod;
  15586. glTextureFromLod.isReady = true;
  15587. textures.push(lodTexture);
  15588. }
  15589. texture._lodTextureHigh = textures[2];
  15590. texture._lodTextureMid = textures[1];
  15591. texture._lodTextureLow = textures[0];
  15592. if (onLoad) {
  15593. onLoad(texture);
  15594. }
  15595. };
  15596. return this.createCubeTexture(rootUrl, scene, null, false, callback, onError, format, forcedExtension, createPolynomials);
  15597. };
  15598. /**
  15599. * Creates a cube texture
  15600. * @param rootUrl defines the url where the files to load is located
  15601. * @param scene defines the current scene
  15602. * @param files defines the list of files to load (1 per face)
  15603. * @param noMipmap defines a boolean indicating that no mipmaps shall be generated (false by default)
  15604. * @param onLoad defines an optional callback raised when the texture is loaded
  15605. * @param onError defines an optional callback raised if there is an issue to load the texture
  15606. * @param format defines the format of the data
  15607. * @param forcedExtension defines the extension to use to pick the right loader
  15608. * @param createPolynomials if a polynomial sphere should be created for the cube texture
  15609. * @returns the cube texture as an InternalTexture
  15610. */
  15611. Engine.prototype.createCubeTexture = function (rootUrl, scene, files, noMipmap, onLoad, onError, format, forcedExtension, createPolynomials) {
  15612. var _this = this;
  15613. if (onLoad === void 0) { onLoad = null; }
  15614. if (onError === void 0) { onError = null; }
  15615. if (forcedExtension === void 0) { forcedExtension = null; }
  15616. if (createPolynomials === void 0) { createPolynomials = false; }
  15617. var gl = this._gl;
  15618. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBE);
  15619. texture.isCube = true;
  15620. texture.url = rootUrl;
  15621. texture.generateMipMaps = !noMipmap;
  15622. if (!this._doNotHandleContextLost) {
  15623. texture._extension = forcedExtension;
  15624. texture._files = files;
  15625. }
  15626. var isKTX = false;
  15627. var isDDS = false;
  15628. var lastDot = rootUrl.lastIndexOf('.');
  15629. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  15630. if (this._textureFormatInUse) {
  15631. extension = this._textureFormatInUse;
  15632. rootUrl = (lastDot > -1 ? rootUrl.substring(0, lastDot) : rootUrl) + this._textureFormatInUse;
  15633. isKTX = true;
  15634. }
  15635. else {
  15636. isDDS = (extension === ".dds");
  15637. }
  15638. var onerror = function (request, exception) {
  15639. if (onError && request) {
  15640. onError(request.status + " " + request.statusText, exception);
  15641. }
  15642. };
  15643. if (isKTX) {
  15644. this._loadFile(rootUrl, function (data) {
  15645. var ktx = new BABYLON.KhronosTextureContainer(data, 6);
  15646. var loadMipmap = ktx.numberOfMipmapLevels > 1 && !noMipmap;
  15647. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15648. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  15649. ktx.uploadLevels(_this._gl, !noMipmap);
  15650. _this.setCubeMapTextureParams(gl, loadMipmap);
  15651. texture.width = ktx.pixelWidth;
  15652. texture.height = ktx.pixelHeight;
  15653. texture.isReady = true;
  15654. }, undefined, undefined, true, onerror);
  15655. }
  15656. else if (isDDS) {
  15657. if (files && files.length === 6) {
  15658. this._cascadeLoadFiles(scene, function (imgs) {
  15659. var info;
  15660. var loadMipmap = false;
  15661. var width = 0;
  15662. for (var index = 0; index < imgs.length; index++) {
  15663. var data = imgs[index];
  15664. info = BABYLON.DDSTools.GetDDSInfo(data);
  15665. loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  15666. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15667. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  15668. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 6, -1, index);
  15669. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  15670. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  15671. }
  15672. texture.width = info.width;
  15673. texture.height = info.height;
  15674. texture.type = info.textureType;
  15675. width = info.width;
  15676. }
  15677. _this.setCubeMapTextureParams(gl, loadMipmap);
  15678. texture.isReady = true;
  15679. if (onLoad) {
  15680. onLoad({ isDDS: true, width: width, info: info, imgs: imgs, texture: texture });
  15681. }
  15682. }, files, onError);
  15683. }
  15684. else {
  15685. this._loadFile(rootUrl, function (data) {
  15686. var info = BABYLON.DDSTools.GetDDSInfo(data);
  15687. if (createPolynomials) {
  15688. info.sphericalPolynomial = new BABYLON.SphericalPolynomial();
  15689. }
  15690. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  15691. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15692. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  15693. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 6);
  15694. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  15695. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  15696. }
  15697. _this.setCubeMapTextureParams(gl, loadMipmap);
  15698. texture.width = info.width;
  15699. texture.height = info.height;
  15700. texture.isReady = true;
  15701. texture.type = info.textureType;
  15702. if (onLoad) {
  15703. onLoad({ isDDS: true, width: info.width, info: info, data: data, texture: texture });
  15704. }
  15705. }, undefined, undefined, true, onerror);
  15706. }
  15707. }
  15708. else {
  15709. if (!files) {
  15710. throw new Error("Cannot load cubemap because files were not defined");
  15711. }
  15712. cascadeLoadImgs(rootUrl, scene, function (imgs) {
  15713. var width = _this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize) : imgs[0].width;
  15714. var height = width;
  15715. _this._prepareWorkingCanvas();
  15716. if (!_this._workingCanvas || !_this._workingContext) {
  15717. return;
  15718. }
  15719. _this._workingCanvas.width = width;
  15720. _this._workingCanvas.height = height;
  15721. var faces = [
  15722. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  15723. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  15724. ];
  15725. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15726. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  15727. var internalFormat = format ? _this._getInternalFormat(format) : _this._gl.RGBA;
  15728. for (var index = 0; index < faces.length; index++) {
  15729. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  15730. gl.texImage2D(faces[index], 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, _this._workingCanvas);
  15731. }
  15732. if (!noMipmap) {
  15733. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  15734. }
  15735. _this.setCubeMapTextureParams(gl, !noMipmap);
  15736. texture.width = width;
  15737. texture.height = height;
  15738. texture.isReady = true;
  15739. if (format) {
  15740. texture.format = format;
  15741. }
  15742. texture.onLoadedObservable.notifyObservers(texture);
  15743. texture.onLoadedObservable.clear();
  15744. if (onLoad) {
  15745. onLoad();
  15746. }
  15747. }, files, onError);
  15748. }
  15749. this._internalTexturesCache.push(texture);
  15750. return texture;
  15751. };
  15752. Engine.prototype.setCubeMapTextureParams = function (gl, loadMipmap) {
  15753. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  15754. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  15755. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15756. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15757. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15758. // this.resetTextureCache();
  15759. };
  15760. /**
  15761. * Update a raw cube texture
  15762. * @param texture defines the texture to udpdate
  15763. * @param data defines the data to store
  15764. * @param format defines the data format
  15765. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  15766. * @param invertY defines if data must be stored with Y axis inverted
  15767. * @param compression defines the compression used (null by default)
  15768. * @param level defines which level of the texture to update
  15769. */
  15770. Engine.prototype.updateRawCubeTexture = function (texture, data, format, type, invertY, compression, level) {
  15771. if (compression === void 0) { compression = null; }
  15772. if (level === void 0) { level = 0; }
  15773. texture._bufferViewArray = data;
  15774. texture.format = format;
  15775. texture.type = type;
  15776. texture.invertY = invertY;
  15777. texture._compression = compression;
  15778. var gl = this._gl;
  15779. var textureType = this._getWebGLTextureType(type);
  15780. var internalFormat = this._getInternalFormat(format);
  15781. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  15782. var needConversion = false;
  15783. if (internalFormat === gl.RGB) {
  15784. internalFormat = gl.RGBA;
  15785. needConversion = true;
  15786. }
  15787. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15788. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  15789. if (texture.width % 4 !== 0) {
  15790. gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1);
  15791. }
  15792. // Data are known to be in +X +Y +Z -X -Y -Z
  15793. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  15794. var faceData = data[faceIndex];
  15795. if (compression) {
  15796. gl.compressedTexImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, (this.getCaps().s3tc)[compression], texture.width, texture.height, 0, faceData);
  15797. }
  15798. else {
  15799. if (needConversion) {
  15800. faceData = this._convertRGBtoRGBATextureData(faceData, texture.width, texture.height, type);
  15801. }
  15802. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, faceData);
  15803. }
  15804. }
  15805. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  15806. if (isPot && texture.generateMipMaps && level === 0) {
  15807. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  15808. }
  15809. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  15810. // this.resetTextureCache();
  15811. texture.isReady = true;
  15812. };
  15813. /**
  15814. * Creates a new raw cube texture
  15815. * @param data defines the array of data to use to create each face
  15816. * @param size defines the size of the textures
  15817. * @param format defines the format of the data
  15818. * @param type defines the type fo the data (like BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT)
  15819. * @param generateMipMaps defines if the engine should generate the mip levels
  15820. * @param invertY defines if data must be stored with Y axis inverted
  15821. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  15822. * @param compression defines the compression used (null by default)
  15823. * @returns the cube texture as an InternalTexture
  15824. */
  15825. Engine.prototype.createRawCubeTexture = function (data, size, format, type, generateMipMaps, invertY, samplingMode, compression) {
  15826. if (compression === void 0) { compression = null; }
  15827. var gl = this._gl;
  15828. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBERAW);
  15829. texture.isCube = true;
  15830. texture.generateMipMaps = generateMipMaps;
  15831. texture.format = format;
  15832. texture.type = type;
  15833. if (!this._doNotHandleContextLost) {
  15834. texture._bufferViewArray = data;
  15835. }
  15836. var textureType = this._getWebGLTextureType(type);
  15837. var internalFormat = this._getInternalFormat(format);
  15838. if (internalFormat === gl.RGB) {
  15839. internalFormat = gl.RGBA;
  15840. }
  15841. var width = size;
  15842. var height = width;
  15843. texture.width = width;
  15844. texture.height = height;
  15845. // Double check on POT to generate Mips.
  15846. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  15847. if (!isPot) {
  15848. generateMipMaps = false;
  15849. }
  15850. // Upload data if needed. The texture won't be ready until then.
  15851. if (data) {
  15852. this.updateRawCubeTexture(texture, data, format, type, invertY, compression);
  15853. }
  15854. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  15855. // Filters
  15856. if (data && generateMipMaps) {
  15857. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  15858. }
  15859. if (textureType === gl.FLOAT && !this._caps.textureFloatLinearFiltering) {
  15860. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  15861. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  15862. }
  15863. else if (textureType === this._gl.HALF_FLOAT_OES && !this._caps.textureHalfFloatLinearFiltering) {
  15864. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  15865. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  15866. }
  15867. else {
  15868. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  15869. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  15870. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  15871. }
  15872. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15873. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15874. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15875. return texture;
  15876. };
  15877. /**
  15878. * Creates a new raw cube texture from a specified url
  15879. * @param url defines the url where the data is located
  15880. * @param scene defines the current scene
  15881. * @param size defines the size of the textures
  15882. * @param format defines the format of the data
  15883. * @param type defines the type fo the data (like BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT)
  15884. * @param noMipmap defines if the engine should avoid generating the mip levels
  15885. * @param callback defines a callback used to extract texture data from loaded data
  15886. * @param mipmapGenerator defines to provide an optional tool to generate mip levels
  15887. * @param onLoad defines a callback called when texture is loaded
  15888. * @param onError defines a callback called if there is an error
  15889. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  15890. * @param invertY defines if data must be stored with Y axis inverted
  15891. * @returns the cube texture as an InternalTexture
  15892. */
  15893. Engine.prototype.createRawCubeTextureFromUrl = function (url, scene, size, format, type, noMipmap, callback, mipmapGenerator, onLoad, onError, samplingMode, invertY) {
  15894. var _this = this;
  15895. if (onLoad === void 0) { onLoad = null; }
  15896. if (onError === void 0) { onError = null; }
  15897. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  15898. if (invertY === void 0) { invertY = false; }
  15899. var gl = this._gl;
  15900. var texture = this.createRawCubeTexture(null, size, format, type, !noMipmap, invertY, samplingMode);
  15901. scene._addPendingData(texture);
  15902. texture.url = url;
  15903. this._internalTexturesCache.push(texture);
  15904. var onerror = function (request, exception) {
  15905. scene._removePendingData(texture);
  15906. if (onError && request) {
  15907. onError(request.status + " " + request.statusText, exception);
  15908. }
  15909. };
  15910. var internalCallback = function (data) {
  15911. var width = texture.width;
  15912. var faceDataArrays = callback(data);
  15913. if (!faceDataArrays) {
  15914. return;
  15915. }
  15916. if (mipmapGenerator) {
  15917. var textureType = _this._getWebGLTextureType(type);
  15918. var internalFormat = _this._getInternalFormat(format);
  15919. var internalSizedFomat = _this._getRGBABufferInternalSizedFormat(type);
  15920. var needConversion = false;
  15921. if (internalFormat === gl.RGB) {
  15922. internalFormat = gl.RGBA;
  15923. needConversion = true;
  15924. }
  15925. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15926. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  15927. var mipData = mipmapGenerator(faceDataArrays);
  15928. for (var level = 0; level < mipData.length; level++) {
  15929. var mipSize = width >> level;
  15930. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  15931. var mipFaceData = mipData[level][faceIndex];
  15932. if (needConversion) {
  15933. mipFaceData = _this._convertRGBtoRGBATextureData(mipFaceData, mipSize, mipSize, type);
  15934. }
  15935. gl.texImage2D(faceIndex, level, internalSizedFomat, mipSize, mipSize, 0, internalFormat, textureType, mipFaceData);
  15936. }
  15937. }
  15938. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15939. }
  15940. else {
  15941. texture.generateMipMaps = !noMipmap;
  15942. _this.updateRawCubeTexture(texture, faceDataArrays, format, type, invertY);
  15943. }
  15944. texture.isReady = true;
  15945. // this.resetTextureCache();
  15946. scene._removePendingData(texture);
  15947. if (onLoad) {
  15948. onLoad();
  15949. }
  15950. };
  15951. this._loadFile(url, function (data) {
  15952. internalCallback(data);
  15953. }, undefined, scene.database, true, onerror);
  15954. return texture;
  15955. };
  15956. ;
  15957. /**
  15958. * Update a raw 3D texture
  15959. * @param texture defines the texture to update
  15960. * @param data defines the data to store
  15961. * @param format defines the data format
  15962. * @param invertY defines if data must be stored with Y axis inverted
  15963. * @param compression defines the used compression (can be null)
  15964. * @param textureType defines the texture Type (Engine.TEXTURETYPE_UNSIGNED_INT, Engine.TEXTURETYPE_FLOAT...)
  15965. */
  15966. Engine.prototype.updateRawTexture3D = function (texture, data, format, invertY, compression, textureType) {
  15967. if (compression === void 0) { compression = null; }
  15968. if (textureType === void 0) { textureType = Engine.TEXTURETYPE_UNSIGNED_INT; }
  15969. var internalType = this._getWebGLTextureType(textureType);
  15970. var internalFormat = this._getInternalFormat(format);
  15971. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(textureType, format);
  15972. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  15973. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  15974. if (!this._doNotHandleContextLost) {
  15975. texture._bufferView = data;
  15976. texture.format = format;
  15977. texture.invertY = invertY;
  15978. texture._compression = compression;
  15979. }
  15980. if (texture.width % 4 !== 0) {
  15981. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  15982. }
  15983. if (compression && data) {
  15984. this._gl.compressedTexImage3D(this._gl.TEXTURE_3D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, texture.depth, 0, data);
  15985. }
  15986. else {
  15987. this._gl.texImage3D(this._gl.TEXTURE_3D, 0, internalSizedFomat, texture.width, texture.height, texture.depth, 0, internalFormat, internalType, data);
  15988. }
  15989. if (texture.generateMipMaps) {
  15990. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  15991. }
  15992. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  15993. // this.resetTextureCache();
  15994. texture.isReady = true;
  15995. };
  15996. /**
  15997. * Creates a new raw 3D texture
  15998. * @param data defines the data used to create the texture
  15999. * @param width defines the width of the texture
  16000. * @param height defines the height of the texture
  16001. * @param depth defines the depth of the texture
  16002. * @param format defines the format of the texture
  16003. * @param generateMipMaps defines if the engine must generate mip levels
  16004. * @param invertY defines if data must be stored with Y axis inverted
  16005. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  16006. * @param compression defines the compressed used (can be null)
  16007. * @param textureType defines the compressed used (can be null)
  16008. * @returns a new raw 3D texture (stored in an InternalTexture)
  16009. */
  16010. Engine.prototype.createRawTexture3D = function (data, width, height, depth, format, generateMipMaps, invertY, samplingMode, compression, textureType) {
  16011. if (compression === void 0) { compression = null; }
  16012. if (textureType === void 0) { textureType = Engine.TEXTURETYPE_UNSIGNED_INT; }
  16013. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW3D);
  16014. texture.baseWidth = width;
  16015. texture.baseHeight = height;
  16016. texture.baseDepth = depth;
  16017. texture.width = width;
  16018. texture.height = height;
  16019. texture.depth = depth;
  16020. texture.format = format;
  16021. texture.type = textureType;
  16022. texture.generateMipMaps = generateMipMaps;
  16023. texture.samplingMode = samplingMode;
  16024. texture.is3D = true;
  16025. if (!this._doNotHandleContextLost) {
  16026. texture._bufferView = data;
  16027. }
  16028. this.updateRawTexture3D(texture, data, format, invertY, compression, textureType);
  16029. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  16030. // Filters
  16031. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  16032. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  16033. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  16034. if (generateMipMaps) {
  16035. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  16036. }
  16037. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  16038. this._internalTexturesCache.push(texture);
  16039. return texture;
  16040. };
  16041. Engine.prototype._prepareWebGLTextureContinuation = function (texture, scene, noMipmap, isCompressed, samplingMode) {
  16042. var gl = this._gl;
  16043. if (!gl) {
  16044. return;
  16045. }
  16046. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  16047. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  16048. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  16049. if (!noMipmap && !isCompressed) {
  16050. gl.generateMipmap(gl.TEXTURE_2D);
  16051. }
  16052. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  16053. // this.resetTextureCache();
  16054. if (scene) {
  16055. scene._removePendingData(texture);
  16056. }
  16057. texture.onLoadedObservable.notifyObservers(texture);
  16058. texture.onLoadedObservable.clear();
  16059. };
  16060. Engine.prototype._prepareWebGLTexture = function (texture, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  16061. var _this = this;
  16062. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  16063. var potWidth = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this.getCaps().maxTextureSize) : width;
  16064. var potHeight = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this.getCaps().maxTextureSize) : height;
  16065. var gl = this._gl;
  16066. if (!gl) {
  16067. return;
  16068. }
  16069. if (!texture._webGLTexture) {
  16070. // this.resetTextureCache();
  16071. if (scene) {
  16072. scene._removePendingData(texture);
  16073. }
  16074. return;
  16075. }
  16076. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  16077. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  16078. texture.baseWidth = width;
  16079. texture.baseHeight = height;
  16080. texture.width = potWidth;
  16081. texture.height = potHeight;
  16082. texture.isReady = true;
  16083. if (processFunction(potWidth, potHeight, function () {
  16084. _this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  16085. })) {
  16086. // Returning as texture needs extra async steps
  16087. return;
  16088. }
  16089. this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  16090. };
  16091. Engine.prototype._convertRGBtoRGBATextureData = function (rgbData, width, height, textureType) {
  16092. // Create new RGBA data container.
  16093. var rgbaData;
  16094. if (textureType === Engine.TEXTURETYPE_FLOAT) {
  16095. rgbaData = new Float32Array(width * height * 4);
  16096. }
  16097. else {
  16098. rgbaData = new Uint32Array(width * height * 4);
  16099. }
  16100. // Convert each pixel.
  16101. for (var x = 0; x < width; x++) {
  16102. for (var y = 0; y < height; y++) {
  16103. var index = (y * width + x) * 3;
  16104. var newIndex = (y * width + x) * 4;
  16105. // Map Old Value to new value.
  16106. rgbaData[newIndex + 0] = rgbData[index + 0];
  16107. rgbaData[newIndex + 1] = rgbData[index + 1];
  16108. rgbaData[newIndex + 2] = rgbData[index + 2];
  16109. // Add fully opaque alpha channel.
  16110. rgbaData[newIndex + 3] = 1;
  16111. }
  16112. }
  16113. return rgbaData;
  16114. };
  16115. /** @hidden */
  16116. Engine.prototype._releaseFramebufferObjects = function (texture) {
  16117. var gl = this._gl;
  16118. if (texture._framebuffer) {
  16119. gl.deleteFramebuffer(texture._framebuffer);
  16120. texture._framebuffer = null;
  16121. }
  16122. if (texture._depthStencilBuffer) {
  16123. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  16124. texture._depthStencilBuffer = null;
  16125. }
  16126. if (texture._MSAAFramebuffer) {
  16127. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  16128. texture._MSAAFramebuffer = null;
  16129. }
  16130. if (texture._MSAARenderBuffer) {
  16131. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  16132. texture._MSAARenderBuffer = null;
  16133. }
  16134. };
  16135. /** @hidden */
  16136. Engine.prototype._releaseTexture = function (texture) {
  16137. var gl = this._gl;
  16138. this._releaseFramebufferObjects(texture);
  16139. gl.deleteTexture(texture._webGLTexture);
  16140. // Unbind channels
  16141. this.unbindAllTextures();
  16142. var index = this._internalTexturesCache.indexOf(texture);
  16143. if (index !== -1) {
  16144. this._internalTexturesCache.splice(index, 1);
  16145. }
  16146. // Integrated fixed lod samplers.
  16147. if (texture._lodTextureHigh) {
  16148. texture._lodTextureHigh.dispose();
  16149. }
  16150. if (texture._lodTextureMid) {
  16151. texture._lodTextureMid.dispose();
  16152. }
  16153. if (texture._lodTextureLow) {
  16154. texture._lodTextureLow.dispose();
  16155. }
  16156. // Set output texture of post process to null if the texture has been released/disposed
  16157. this.scenes.forEach(function (scene) {
  16158. scene.postProcesses.forEach(function (postProcess) {
  16159. if (postProcess._outputTexture == texture) {
  16160. postProcess._outputTexture = null;
  16161. }
  16162. });
  16163. scene.cameras.forEach(function (camera) {
  16164. camera._postProcesses.forEach(function (postProcess) {
  16165. if (postProcess) {
  16166. if (postProcess._outputTexture == texture) {
  16167. postProcess._outputTexture = null;
  16168. }
  16169. }
  16170. });
  16171. });
  16172. });
  16173. };
  16174. Engine.prototype.setProgram = function (program) {
  16175. if (this._currentProgram !== program) {
  16176. this._gl.useProgram(program);
  16177. this._currentProgram = program;
  16178. }
  16179. };
  16180. /**
  16181. * Binds an effect to the webGL context
  16182. * @param effect defines the effect to bind
  16183. */
  16184. Engine.prototype.bindSamplers = function (effect) {
  16185. this.setProgram(effect.getProgram());
  16186. var samplers = effect.getSamplers();
  16187. for (var index = 0; index < samplers.length; index++) {
  16188. var uniform = effect.getUniform(samplers[index]);
  16189. if (uniform) {
  16190. this._boundUniforms[index] = uniform;
  16191. }
  16192. }
  16193. this._currentEffect = null;
  16194. };
  16195. Engine.prototype._moveBoundTextureOnTop = function (internalTexture) {
  16196. if (this.disableTextureBindingOptimization || this._lastBoundInternalTextureTracker.previous === internalTexture) {
  16197. return;
  16198. }
  16199. // Remove
  16200. this._linkTrackers(internalTexture.previous, internalTexture.next);
  16201. // Bind last to it
  16202. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, internalTexture);
  16203. // Bind to dummy
  16204. this._linkTrackers(internalTexture, this._lastBoundInternalTextureTracker);
  16205. };
  16206. Engine.prototype._getCorrectTextureChannel = function (channel, internalTexture) {
  16207. if (!internalTexture) {
  16208. return -1;
  16209. }
  16210. internalTexture._initialSlot = channel;
  16211. if (this.disableTextureBindingOptimization) { // We want texture sampler ID === texture channel
  16212. if (channel !== internalTexture._designatedSlot) {
  16213. this._textureCollisions.addCount(1, false);
  16214. }
  16215. }
  16216. else {
  16217. if (channel !== internalTexture._designatedSlot) {
  16218. if (internalTexture._designatedSlot > -1) { // Texture is already assigned to a slot
  16219. return internalTexture._designatedSlot;
  16220. }
  16221. else {
  16222. // No slot for this texture, let's pick a new one (if we find a free slot)
  16223. if (this._nextFreeTextureSlots.length) {
  16224. return this._nextFreeTextureSlots[0];
  16225. }
  16226. // We need to recycle the oldest bound texture, sorry.
  16227. this._textureCollisions.addCount(1, false);
  16228. return this._removeDesignatedSlot(this._firstBoundInternalTextureTracker.next);
  16229. }
  16230. }
  16231. }
  16232. return channel;
  16233. };
  16234. Engine.prototype._linkTrackers = function (previous, next) {
  16235. previous.next = next;
  16236. next.previous = previous;
  16237. };
  16238. Engine.prototype._removeDesignatedSlot = function (internalTexture) {
  16239. var currentSlot = internalTexture._designatedSlot;
  16240. if (currentSlot === -1) {
  16241. return -1;
  16242. }
  16243. internalTexture._designatedSlot = -1;
  16244. if (this.disableTextureBindingOptimization) {
  16245. return -1;
  16246. }
  16247. // Remove from bound list
  16248. this._linkTrackers(internalTexture.previous, internalTexture.next);
  16249. // Free the slot
  16250. this._boundTexturesCache[currentSlot] = null;
  16251. this._nextFreeTextureSlots.push(currentSlot);
  16252. return currentSlot;
  16253. };
  16254. Engine.prototype._activateCurrentTexture = function () {
  16255. if (this._currentTextureChannel !== this._activeChannel) {
  16256. this._gl.activeTexture(this._gl.TEXTURE0 + this._activeChannel);
  16257. this._currentTextureChannel = this._activeChannel;
  16258. }
  16259. };
  16260. /** @hidden */
  16261. Engine.prototype._bindTextureDirectly = function (target, texture, forTextureDataUpdate, force) {
  16262. if (forTextureDataUpdate === void 0) { forTextureDataUpdate = false; }
  16263. if (force === void 0) { force = false; }
  16264. if (forTextureDataUpdate && texture && texture._designatedSlot > -1) {
  16265. this._activeChannel = texture._designatedSlot;
  16266. }
  16267. var currentTextureBound = this._boundTexturesCache[this._activeChannel];
  16268. var isTextureForRendering = texture && texture._initialSlot > -1;
  16269. if (currentTextureBound !== texture || force) {
  16270. if (currentTextureBound) {
  16271. this._removeDesignatedSlot(currentTextureBound);
  16272. }
  16273. this._activateCurrentTexture();
  16274. this._gl.bindTexture(target, texture ? texture._webGLTexture : null);
  16275. this._boundTexturesCache[this._activeChannel] = texture;
  16276. if (texture) {
  16277. if (!this.disableTextureBindingOptimization) {
  16278. var slotIndex = this._nextFreeTextureSlots.indexOf(this._activeChannel);
  16279. if (slotIndex > -1) {
  16280. this._nextFreeTextureSlots.splice(slotIndex, 1);
  16281. }
  16282. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, texture);
  16283. this._linkTrackers(texture, this._lastBoundInternalTextureTracker);
  16284. }
  16285. texture._designatedSlot = this._activeChannel;
  16286. }
  16287. }
  16288. else if (forTextureDataUpdate) {
  16289. this._activateCurrentTexture();
  16290. }
  16291. if (isTextureForRendering && !forTextureDataUpdate) {
  16292. this._bindSamplerUniformToChannel(texture._initialSlot, this._activeChannel);
  16293. }
  16294. };
  16295. /** @hidden */
  16296. Engine.prototype._bindTexture = function (channel, texture) {
  16297. if (channel < 0) {
  16298. return;
  16299. }
  16300. if (texture) {
  16301. channel = this._getCorrectTextureChannel(channel, texture);
  16302. }
  16303. this._activeChannel = channel;
  16304. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  16305. };
  16306. /**
  16307. * Sets a texture to the webGL context from a postprocess
  16308. * @param channel defines the channel to use
  16309. * @param postProcess defines the source postprocess
  16310. */
  16311. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  16312. this._bindTexture(channel, postProcess ? postProcess._textures.data[postProcess._currentRenderTextureInd] : null);
  16313. };
  16314. /**
  16315. * Binds the output of the passed in post process to the texture channel specified
  16316. * @param channel The channel the texture should be bound to
  16317. * @param postProcess The post process which's output should be bound
  16318. */
  16319. Engine.prototype.setTextureFromPostProcessOutput = function (channel, postProcess) {
  16320. this._bindTexture(channel, postProcess ? postProcess._outputTexture : null);
  16321. };
  16322. /**
  16323. * Unbind all textures from the webGL context
  16324. */
  16325. Engine.prototype.unbindAllTextures = function () {
  16326. for (var channel = 0; channel < this._maxSimultaneousTextures; channel++) {
  16327. this._activeChannel = channel;
  16328. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  16329. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  16330. if (this.webGLVersion > 1) {
  16331. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  16332. }
  16333. }
  16334. };
  16335. /**
  16336. * Sets a texture to the according uniform.
  16337. * @param channel The texture channel
  16338. * @param uniform The uniform to set
  16339. * @param texture The texture to apply
  16340. */
  16341. Engine.prototype.setTexture = function (channel, uniform, texture) {
  16342. if (channel < 0) {
  16343. return;
  16344. }
  16345. if (uniform) {
  16346. this._boundUniforms[channel] = uniform;
  16347. }
  16348. this._setTexture(channel, texture);
  16349. };
  16350. /**
  16351. * Sets a depth stencil texture from a render target to the according uniform.
  16352. * @param channel The texture channel
  16353. * @param uniform The uniform to set
  16354. * @param texture The render target texture containing the depth stencil texture to apply
  16355. */
  16356. Engine.prototype.setDepthStencilTexture = function (channel, uniform, texture) {
  16357. if (channel < 0) {
  16358. return;
  16359. }
  16360. if (uniform) {
  16361. this._boundUniforms[channel] = uniform;
  16362. }
  16363. if (!texture || !texture.depthStencilTexture) {
  16364. this._setTexture(channel, null);
  16365. }
  16366. else {
  16367. this._setTexture(channel, texture, false, true);
  16368. }
  16369. };
  16370. Engine.prototype._bindSamplerUniformToChannel = function (sourceSlot, destination) {
  16371. var uniform = this._boundUniforms[sourceSlot];
  16372. if (uniform._currentState === destination) {
  16373. return;
  16374. }
  16375. this._gl.uniform1i(uniform, destination);
  16376. uniform._currentState = destination;
  16377. };
  16378. Engine.prototype._getTextureWrapMode = function (mode) {
  16379. switch (mode) {
  16380. case BABYLON.Texture.WRAP_ADDRESSMODE:
  16381. return this._gl.REPEAT;
  16382. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  16383. return this._gl.CLAMP_TO_EDGE;
  16384. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  16385. return this._gl.MIRRORED_REPEAT;
  16386. }
  16387. return this._gl.REPEAT;
  16388. };
  16389. Engine.prototype._setTexture = function (channel, texture, isPartOfTextureArray, depthStencilTexture) {
  16390. if (isPartOfTextureArray === void 0) { isPartOfTextureArray = false; }
  16391. if (depthStencilTexture === void 0) { depthStencilTexture = false; }
  16392. // Not ready?
  16393. if (!texture) {
  16394. if (this._boundTexturesCache[channel] != null) {
  16395. this._activeChannel = channel;
  16396. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  16397. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  16398. if (this.webGLVersion > 1) {
  16399. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  16400. }
  16401. }
  16402. return false;
  16403. }
  16404. // Video
  16405. if (texture.video) {
  16406. this._activeChannel = channel;
  16407. texture.update();
  16408. }
  16409. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) { // Delay loading
  16410. texture.delayLoad();
  16411. return false;
  16412. }
  16413. var internalTexture;
  16414. if (depthStencilTexture) {
  16415. internalTexture = texture.depthStencilTexture;
  16416. }
  16417. else if (texture.isReady()) {
  16418. internalTexture = texture.getInternalTexture();
  16419. }
  16420. else if (texture.isCube) {
  16421. internalTexture = this.emptyCubeTexture;
  16422. }
  16423. else if (texture.is3D) {
  16424. internalTexture = this.emptyTexture3D;
  16425. }
  16426. else {
  16427. internalTexture = this.emptyTexture;
  16428. }
  16429. if (!isPartOfTextureArray) {
  16430. channel = this._getCorrectTextureChannel(channel, internalTexture);
  16431. }
  16432. var needToBind = true;
  16433. if (this._boundTexturesCache[channel] === internalTexture) {
  16434. this._moveBoundTextureOnTop(internalTexture);
  16435. if (!isPartOfTextureArray) {
  16436. this._bindSamplerUniformToChannel(internalTexture._initialSlot, channel);
  16437. }
  16438. needToBind = false;
  16439. }
  16440. this._activeChannel = channel;
  16441. if (internalTexture && internalTexture.is3D) {
  16442. if (needToBind) {
  16443. this._bindTextureDirectly(this._gl.TEXTURE_3D, internalTexture, isPartOfTextureArray);
  16444. }
  16445. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  16446. internalTexture._cachedWrapU = texture.wrapU;
  16447. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._getTextureWrapMode(texture.wrapU), internalTexture);
  16448. }
  16449. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  16450. internalTexture._cachedWrapV = texture.wrapV;
  16451. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._getTextureWrapMode(texture.wrapV), internalTexture);
  16452. }
  16453. if (internalTexture && internalTexture._cachedWrapR !== texture.wrapR) {
  16454. internalTexture._cachedWrapR = texture.wrapR;
  16455. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._getTextureWrapMode(texture.wrapR), internalTexture);
  16456. }
  16457. this._setAnisotropicLevel(this._gl.TEXTURE_3D, texture);
  16458. }
  16459. else if (internalTexture && internalTexture.isCube) {
  16460. if (needToBind) {
  16461. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, internalTexture, isPartOfTextureArray);
  16462. }
  16463. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  16464. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  16465. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  16466. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  16467. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode, internalTexture);
  16468. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  16469. }
  16470. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  16471. }
  16472. else {
  16473. if (needToBind) {
  16474. this._bindTextureDirectly(this._gl.TEXTURE_2D, internalTexture, isPartOfTextureArray);
  16475. }
  16476. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  16477. internalTexture._cachedWrapU = texture.wrapU;
  16478. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._getTextureWrapMode(texture.wrapU), internalTexture);
  16479. }
  16480. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  16481. internalTexture._cachedWrapV = texture.wrapV;
  16482. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._getTextureWrapMode(texture.wrapV), internalTexture);
  16483. }
  16484. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  16485. }
  16486. return true;
  16487. };
  16488. /**
  16489. * Sets an array of texture to the webGL context
  16490. * @param channel defines the channel where the texture array must be set
  16491. * @param uniform defines the associated uniform location
  16492. * @param textures defines the array of textures to bind
  16493. */
  16494. Engine.prototype.setTextureArray = function (channel, uniform, textures) {
  16495. if (channel < 0 || !uniform) {
  16496. return;
  16497. }
  16498. if (!this._textureUnits || this._textureUnits.length !== textures.length) {
  16499. this._textureUnits = new Int32Array(textures.length);
  16500. }
  16501. for (var i = 0; i < textures.length; i++) {
  16502. this._textureUnits[i] = this._getCorrectTextureChannel(channel + i, textures[i].getInternalTexture());
  16503. }
  16504. this._gl.uniform1iv(uniform, this._textureUnits);
  16505. for (var index = 0; index < textures.length; index++) {
  16506. this._setTexture(this._textureUnits[index], textures[index], true);
  16507. }
  16508. };
  16509. /** @hidden */
  16510. Engine.prototype._setAnisotropicLevel = function (target, texture) {
  16511. var internalTexture = texture.getInternalTexture();
  16512. if (!internalTexture) {
  16513. return;
  16514. }
  16515. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  16516. var value = texture.anisotropicFilteringLevel;
  16517. if (internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR_MIPNEAREST
  16518. && internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR
  16519. && internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR) {
  16520. value = 1; // Forcing the anisotropic to 1 because else webgl will force filters to linear
  16521. }
  16522. if (anisotropicFilterExtension && internalTexture._cachedAnisotropicFilteringLevel !== value) {
  16523. this._setTextureParameterFloat(target, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy), internalTexture);
  16524. internalTexture._cachedAnisotropicFilteringLevel = value;
  16525. }
  16526. };
  16527. Engine.prototype._setTextureParameterFloat = function (target, parameter, value, texture) {
  16528. this._bindTextureDirectly(target, texture, true, true);
  16529. this._gl.texParameterf(target, parameter, value);
  16530. };
  16531. Engine.prototype._setTextureParameterInteger = function (target, parameter, value, texture) {
  16532. if (texture) {
  16533. this._bindTextureDirectly(target, texture, true, true);
  16534. }
  16535. this._gl.texParameteri(target, parameter, value);
  16536. };
  16537. /**
  16538. * Reads pixels from the current frame buffer. Please note that this function can be slow
  16539. * @param x defines the x coordinate of the rectangle where pixels must be read
  16540. * @param y defines the y coordinate of the rectangle where pixels must be read
  16541. * @param width defines the width of the rectangle where pixels must be read
  16542. * @param height defines the height of the rectangle where pixels must be read
  16543. * @returns a Uint8Array containing RGBA colors
  16544. */
  16545. Engine.prototype.readPixels = function (x, y, width, height) {
  16546. var data = new Uint8Array(height * width * 4);
  16547. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  16548. return data;
  16549. };
  16550. /**
  16551. * Add an externaly attached data from its key.
  16552. * This method call will fail and return false, if such key already exists.
  16553. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  16554. * @param key the unique key that identifies the data
  16555. * @param data the data object to associate to the key for this Engine instance
  16556. * @return true if no such key were already present and the data was added successfully, false otherwise
  16557. */
  16558. Engine.prototype.addExternalData = function (key, data) {
  16559. if (!this._externalData) {
  16560. this._externalData = new BABYLON.StringDictionary();
  16561. }
  16562. return this._externalData.add(key, data);
  16563. };
  16564. /**
  16565. * Get an externaly attached data from its key
  16566. * @param key the unique key that identifies the data
  16567. * @return the associated data, if present (can be null), or undefined if not present
  16568. */
  16569. Engine.prototype.getExternalData = function (key) {
  16570. if (!this._externalData) {
  16571. this._externalData = new BABYLON.StringDictionary();
  16572. }
  16573. return this._externalData.get(key);
  16574. };
  16575. /**
  16576. * Get an externaly attached data from its key, create it using a factory if it's not already present
  16577. * @param key the unique key that identifies the data
  16578. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  16579. * @return the associated data, can be null if the factory returned null.
  16580. */
  16581. Engine.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  16582. if (!this._externalData) {
  16583. this._externalData = new BABYLON.StringDictionary();
  16584. }
  16585. return this._externalData.getOrAddWithFactory(key, factory);
  16586. };
  16587. /**
  16588. * Remove an externaly attached data from the Engine instance
  16589. * @param key the unique key that identifies the data
  16590. * @return true if the data was successfully removed, false if it doesn't exist
  16591. */
  16592. Engine.prototype.removeExternalData = function (key) {
  16593. if (!this._externalData) {
  16594. this._externalData = new BABYLON.StringDictionary();
  16595. }
  16596. return this._externalData.remove(key);
  16597. };
  16598. /**
  16599. * Unbind all vertex attributes from the webGL context
  16600. */
  16601. Engine.prototype.unbindAllAttributes = function () {
  16602. if (this._mustWipeVertexAttributes) {
  16603. this._mustWipeVertexAttributes = false;
  16604. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  16605. this._gl.disableVertexAttribArray(i);
  16606. this._vertexAttribArraysEnabled[i] = false;
  16607. this._currentBufferPointers[i].active = false;
  16608. }
  16609. return;
  16610. }
  16611. for (var i = 0, ul = this._vertexAttribArraysEnabled.length; i < ul; i++) {
  16612. if (i >= this._caps.maxVertexAttribs || !this._vertexAttribArraysEnabled[i]) {
  16613. continue;
  16614. }
  16615. this._gl.disableVertexAttribArray(i);
  16616. this._vertexAttribArraysEnabled[i] = false;
  16617. this._currentBufferPointers[i].active = false;
  16618. }
  16619. };
  16620. /**
  16621. * 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
  16622. */
  16623. Engine.prototype.releaseEffects = function () {
  16624. for (var name in this._compiledEffects) {
  16625. this._deleteProgram(this._compiledEffects[name]._program);
  16626. }
  16627. this._compiledEffects = {};
  16628. };
  16629. /**
  16630. * Dispose and release all associated resources
  16631. */
  16632. Engine.prototype.dispose = function () {
  16633. this.hideLoadingUI();
  16634. this.stopRenderLoop();
  16635. // Release postProcesses
  16636. while (this.postProcesses.length) {
  16637. this.postProcesses[0].dispose();
  16638. }
  16639. // Empty texture
  16640. if (this._emptyTexture) {
  16641. this._releaseTexture(this._emptyTexture);
  16642. this._emptyTexture = null;
  16643. }
  16644. if (this._emptyCubeTexture) {
  16645. this._releaseTexture(this._emptyCubeTexture);
  16646. this._emptyCubeTexture = null;
  16647. }
  16648. // Rescale PP
  16649. if (this._rescalePostProcess) {
  16650. this._rescalePostProcess.dispose();
  16651. }
  16652. // Release scenes
  16653. while (this.scenes.length) {
  16654. this.scenes[0].dispose();
  16655. }
  16656. // Release audio engine
  16657. if (Engine.audioEngine) {
  16658. Engine.audioEngine.dispose();
  16659. }
  16660. // Release effects
  16661. this.releaseEffects();
  16662. // Unbind
  16663. this.unbindAllAttributes();
  16664. this._boundUniforms = [];
  16665. if (this._dummyFramebuffer) {
  16666. this._gl.deleteFramebuffer(this._dummyFramebuffer);
  16667. }
  16668. //WebVR
  16669. this.disableVR();
  16670. // Events
  16671. if (BABYLON.Tools.IsWindowObjectExist()) {
  16672. window.removeEventListener("blur", this._onBlur);
  16673. window.removeEventListener("focus", this._onFocus);
  16674. window.removeEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted);
  16675. window.removeEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted);
  16676. if (this._renderingCanvas) {
  16677. this._renderingCanvas.removeEventListener("focus", this._onCanvasFocus);
  16678. this._renderingCanvas.removeEventListener("blur", this._onCanvasBlur);
  16679. this._renderingCanvas.removeEventListener("pointerout", this._onCanvasPointerOut);
  16680. if (!this._doNotHandleContextLost) {
  16681. this._renderingCanvas.removeEventListener("webglcontextlost", this._onContextLost);
  16682. this._renderingCanvas.removeEventListener("webglcontextrestored", this._onContextRestored);
  16683. }
  16684. }
  16685. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  16686. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  16687. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  16688. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  16689. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  16690. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  16691. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  16692. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  16693. if (this._onVrDisplayConnect) {
  16694. window.removeEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  16695. if (this._onVrDisplayDisconnect) {
  16696. window.removeEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  16697. }
  16698. if (this._onVrDisplayPresentChange) {
  16699. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  16700. }
  16701. this._onVrDisplayConnect = null;
  16702. this._onVrDisplayDisconnect = null;
  16703. }
  16704. }
  16705. // Remove from Instances
  16706. var index = Engine.Instances.indexOf(this);
  16707. if (index >= 0) {
  16708. Engine.Instances.splice(index, 1);
  16709. }
  16710. this._workingCanvas = null;
  16711. this._workingContext = null;
  16712. this._currentBufferPointers = [];
  16713. this._renderingCanvas = null;
  16714. this._currentProgram = null;
  16715. this._bindedRenderFunction = null;
  16716. this.onResizeObservable.clear();
  16717. this.onCanvasBlurObservable.clear();
  16718. this.onCanvasFocusObservable.clear();
  16719. this.onCanvasPointerOutObservable.clear();
  16720. this.onBeginFrameObservable.clear();
  16721. this.onEndFrameObservable.clear();
  16722. BABYLON.Effect.ResetCache();
  16723. // Abort active requests
  16724. for (var _i = 0, _a = this._activeRequests; _i < _a.length; _i++) {
  16725. var request = _a[_i];
  16726. request.abort();
  16727. }
  16728. };
  16729. // Loading screen
  16730. /**
  16731. * Display the loading screen
  16732. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16733. */
  16734. Engine.prototype.displayLoadingUI = function () {
  16735. if (!BABYLON.Tools.IsWindowObjectExist()) {
  16736. return;
  16737. }
  16738. var loadingScreen = this.loadingScreen;
  16739. if (loadingScreen) {
  16740. loadingScreen.displayLoadingUI();
  16741. }
  16742. };
  16743. /**
  16744. * Hide the loading screen
  16745. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16746. */
  16747. Engine.prototype.hideLoadingUI = function () {
  16748. if (!BABYLON.Tools.IsWindowObjectExist()) {
  16749. return;
  16750. }
  16751. var loadingScreen = this.loadingScreen;
  16752. if (loadingScreen) {
  16753. loadingScreen.hideLoadingUI();
  16754. }
  16755. };
  16756. Object.defineProperty(Engine.prototype, "loadingScreen", {
  16757. /**
  16758. * Gets the current loading screen object
  16759. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16760. */
  16761. get: function () {
  16762. if (!this._loadingScreen && BABYLON.DefaultLoadingScreen && this._renderingCanvas)
  16763. this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
  16764. return this._loadingScreen;
  16765. },
  16766. /**
  16767. * Sets the current loading screen object
  16768. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16769. */
  16770. set: function (loadingScreen) {
  16771. this._loadingScreen = loadingScreen;
  16772. },
  16773. enumerable: true,
  16774. configurable: true
  16775. });
  16776. Object.defineProperty(Engine.prototype, "loadingUIText", {
  16777. /**
  16778. * Sets the current loading screen text
  16779. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16780. */
  16781. set: function (text) {
  16782. this.loadingScreen.loadingUIText = text;
  16783. },
  16784. enumerable: true,
  16785. configurable: true
  16786. });
  16787. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  16788. /**
  16789. * Sets the current loading screen background color
  16790. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16791. */
  16792. set: function (color) {
  16793. this.loadingScreen.loadingUIBackgroundColor = color;
  16794. },
  16795. enumerable: true,
  16796. configurable: true
  16797. });
  16798. /**
  16799. * Attach a new callback raised when context lost event is fired
  16800. * @param callback defines the callback to call
  16801. */
  16802. Engine.prototype.attachContextLostEvent = function (callback) {
  16803. if (this._renderingCanvas) {
  16804. this._renderingCanvas.addEventListener("webglcontextlost", callback, false);
  16805. }
  16806. };
  16807. /**
  16808. * Attach a new callback raised when context restored event is fired
  16809. * @param callback defines the callback to call
  16810. */
  16811. Engine.prototype.attachContextRestoredEvent = function (callback) {
  16812. if (this._renderingCanvas) {
  16813. this._renderingCanvas.addEventListener("webglcontextrestored", callback, false);
  16814. }
  16815. };
  16816. /**
  16817. * Gets the source code of the vertex shader associated with a specific webGL program
  16818. * @param program defines the program to use
  16819. * @returns a string containing the source code of the vertex shader associated with the program
  16820. */
  16821. Engine.prototype.getVertexShaderSource = function (program) {
  16822. var shaders = this._gl.getAttachedShaders(program);
  16823. if (!shaders) {
  16824. return null;
  16825. }
  16826. return this._gl.getShaderSource(shaders[0]);
  16827. };
  16828. /**
  16829. * Gets the source code of the fragment shader associated with a specific webGL program
  16830. * @param program defines the program to use
  16831. * @returns a string containing the source code of the fragment shader associated with the program
  16832. */
  16833. Engine.prototype.getFragmentShaderSource = function (program) {
  16834. var shaders = this._gl.getAttachedShaders(program);
  16835. if (!shaders) {
  16836. return null;
  16837. }
  16838. return this._gl.getShaderSource(shaders[1]);
  16839. };
  16840. /**
  16841. * Get the current error code of the webGL context
  16842. * @returns the error code
  16843. * @see https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/getError
  16844. */
  16845. Engine.prototype.getError = function () {
  16846. return this._gl.getError();
  16847. };
  16848. // FPS
  16849. /**
  16850. * Gets the current framerate
  16851. * @returns a number representing the framerate
  16852. */
  16853. Engine.prototype.getFps = function () {
  16854. return this._fps;
  16855. };
  16856. /**
  16857. * Gets the time spent between current and previous frame
  16858. * @returns a number representing the delta time in ms
  16859. */
  16860. Engine.prototype.getDeltaTime = function () {
  16861. return this._deltaTime;
  16862. };
  16863. Engine.prototype._measureFps = function () {
  16864. this._performanceMonitor.sampleFrame();
  16865. this._fps = this._performanceMonitor.averageFPS;
  16866. this._deltaTime = this._performanceMonitor.instantaneousFrameTime || 0;
  16867. };
  16868. /** @hidden */
  16869. Engine.prototype._readTexturePixels = function (texture, width, height, faceIndex) {
  16870. if (faceIndex === void 0) { faceIndex = -1; }
  16871. var gl = this._gl;
  16872. if (!this._dummyFramebuffer) {
  16873. var dummy = gl.createFramebuffer();
  16874. if (!dummy) {
  16875. throw new Error("Unable to create dummy framebuffer");
  16876. }
  16877. this._dummyFramebuffer = dummy;
  16878. }
  16879. gl.bindFramebuffer(gl.FRAMEBUFFER, this._dummyFramebuffer);
  16880. if (faceIndex > -1) {
  16881. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, 0);
  16882. }
  16883. else {
  16884. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  16885. }
  16886. var readType = (texture.type !== undefined) ? this._getWebGLTextureType(texture.type) : gl.UNSIGNED_BYTE;
  16887. var buffer;
  16888. switch (readType) {
  16889. case gl.UNSIGNED_BYTE:
  16890. buffer = new Uint8Array(4 * width * height);
  16891. readType = gl.UNSIGNED_BYTE;
  16892. break;
  16893. default:
  16894. buffer = new Float32Array(4 * width * height);
  16895. readType = gl.FLOAT;
  16896. break;
  16897. }
  16898. gl.readPixels(0, 0, width, height, gl.RGBA, readType, buffer);
  16899. gl.bindFramebuffer(gl.FRAMEBUFFER, this._currentFramebuffer);
  16900. return buffer;
  16901. };
  16902. Engine.prototype._canRenderToFloatFramebuffer = function () {
  16903. if (this._webGLVersion > 1) {
  16904. return this._caps.colorBufferFloat;
  16905. }
  16906. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_FLOAT);
  16907. };
  16908. Engine.prototype._canRenderToHalfFloatFramebuffer = function () {
  16909. if (this._webGLVersion > 1) {
  16910. return this._caps.colorBufferFloat;
  16911. }
  16912. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_HALF_FLOAT);
  16913. };
  16914. // Thank you : http://stackoverflow.com/questions/28827511/webgl-ios-render-to-floating-point-texture
  16915. Engine.prototype._canRenderToFramebuffer = function (type) {
  16916. var gl = this._gl;
  16917. //clear existing errors
  16918. while (gl.getError() !== gl.NO_ERROR) { }
  16919. var successful = true;
  16920. var texture = gl.createTexture();
  16921. gl.bindTexture(gl.TEXTURE_2D, texture);
  16922. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), 1, 1, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  16923. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  16924. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  16925. var fb = gl.createFramebuffer();
  16926. gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
  16927. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  16928. var status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
  16929. successful = successful && (status === gl.FRAMEBUFFER_COMPLETE);
  16930. successful = successful && (gl.getError() === gl.NO_ERROR);
  16931. //try render by clearing frame buffer's color buffer
  16932. if (successful) {
  16933. gl.clear(gl.COLOR_BUFFER_BIT);
  16934. successful = successful && (gl.getError() === gl.NO_ERROR);
  16935. }
  16936. //try reading from frame to ensure render occurs (just creating the FBO is not sufficient to determine if rendering is supported)
  16937. if (successful) {
  16938. //in practice it's sufficient to just read from the backbuffer rather than handle potentially issues reading from the texture
  16939. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  16940. var readFormat = gl.RGBA;
  16941. var readType = gl.UNSIGNED_BYTE;
  16942. var buffer = new Uint8Array(4);
  16943. gl.readPixels(0, 0, 1, 1, readFormat, readType, buffer);
  16944. successful = successful && (gl.getError() === gl.NO_ERROR);
  16945. }
  16946. //clean up
  16947. gl.deleteTexture(texture);
  16948. gl.deleteFramebuffer(fb);
  16949. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  16950. //clear accumulated errors
  16951. while (!successful && (gl.getError() !== gl.NO_ERROR)) { }
  16952. return successful;
  16953. };
  16954. /** @hidden */
  16955. Engine.prototype._getWebGLTextureType = function (type) {
  16956. if (type === Engine.TEXTURETYPE_FLOAT) {
  16957. return this._gl.FLOAT;
  16958. }
  16959. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  16960. // Add Half Float Constant.
  16961. return this._gl.HALF_FLOAT_OES;
  16962. }
  16963. return this._gl.UNSIGNED_BYTE;
  16964. };
  16965. ;
  16966. Engine.prototype._getInternalFormat = function (format) {
  16967. var internalFormat = this._gl.RGBA;
  16968. switch (format) {
  16969. case Engine.TEXTUREFORMAT_ALPHA:
  16970. internalFormat = this._gl.ALPHA;
  16971. break;
  16972. case Engine.TEXTUREFORMAT_LUMINANCE:
  16973. internalFormat = this._gl.LUMINANCE;
  16974. break;
  16975. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  16976. internalFormat = this._gl.LUMINANCE_ALPHA;
  16977. break;
  16978. case Engine.TEXTUREFORMAT_RGB:
  16979. internalFormat = this._gl.RGB;
  16980. break;
  16981. case Engine.TEXTUREFORMAT_RGBA:
  16982. internalFormat = this._gl.RGBA;
  16983. break;
  16984. case Engine.TEXTUREFORMAT_R:
  16985. internalFormat = this._gl.RED;
  16986. break;
  16987. case Engine.TEXTUREFORMAT_RG:
  16988. internalFormat = this._gl.RG;
  16989. break;
  16990. }
  16991. return internalFormat;
  16992. };
  16993. /** @hidden */
  16994. Engine.prototype._getRGBABufferInternalSizedFormat = function (type, format) {
  16995. if (this._webGLVersion === 1) {
  16996. if (format !== undefined) {
  16997. switch (format) {
  16998. case Engine.TEXTUREFORMAT_LUMINANCE:
  16999. return this._gl.LUMINANCE;
  17000. case Engine.TEXTUREFORMAT_ALPHA:
  17001. return this._gl.ALPHA;
  17002. }
  17003. }
  17004. return this._gl.RGBA;
  17005. }
  17006. if (type === Engine.TEXTURETYPE_FLOAT) {
  17007. if (format !== undefined) {
  17008. switch (format) {
  17009. case Engine.TEXTUREFORMAT_R:
  17010. return this._gl.R32F;
  17011. case Engine.TEXTUREFORMAT_RG:
  17012. return this._gl.RG32F;
  17013. case Engine.TEXTUREFORMAT_RGB:
  17014. return this._gl.RGB32F;
  17015. }
  17016. }
  17017. return this._gl.RGBA32F;
  17018. }
  17019. if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  17020. if (format) {
  17021. switch (format) {
  17022. case Engine.TEXTUREFORMAT_R:
  17023. return this._gl.R16F;
  17024. case Engine.TEXTUREFORMAT_RG:
  17025. return this._gl.RG16F;
  17026. case Engine.TEXTUREFORMAT_RGB:
  17027. return this._gl.RGB16F;
  17028. }
  17029. }
  17030. return this._gl.RGBA16F;
  17031. }
  17032. if (format !== undefined) {
  17033. switch (format) {
  17034. case Engine.TEXTUREFORMAT_LUMINANCE:
  17035. return this._gl.LUMINANCE;
  17036. case Engine.TEXTUREFORMAT_RGB:
  17037. return this._gl.RGB;
  17038. case Engine.TEXTUREFORMAT_R:
  17039. return this._gl.R8;
  17040. case Engine.TEXTUREFORMAT_RG:
  17041. return this._gl.RG8;
  17042. case Engine.TEXTUREFORMAT_ALPHA:
  17043. return this._gl.ALPHA;
  17044. }
  17045. }
  17046. return this._gl.RGBA;
  17047. };
  17048. ;
  17049. /** @hidden */
  17050. Engine.prototype._getRGBAMultiSampleBufferFormat = function (type) {
  17051. if (type === Engine.TEXTURETYPE_FLOAT) {
  17052. return this._gl.RGBA32F;
  17053. }
  17054. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  17055. return this._gl.RGBA16F;
  17056. }
  17057. return this._gl.RGBA8;
  17058. };
  17059. ;
  17060. /**
  17061. * Create a new webGL query (you must be sure that queries are supported by checking getCaps() function)
  17062. * @return the new query
  17063. */
  17064. Engine.prototype.createQuery = function () {
  17065. return this._gl.createQuery();
  17066. };
  17067. /**
  17068. * Delete and release a webGL query
  17069. * @param query defines the query to delete
  17070. * @return the current engine
  17071. */
  17072. Engine.prototype.deleteQuery = function (query) {
  17073. this._gl.deleteQuery(query);
  17074. return this;
  17075. };
  17076. /**
  17077. * Check if a given query has resolved and got its value
  17078. * @param query defines the query to check
  17079. * @returns true if the query got its value
  17080. */
  17081. Engine.prototype.isQueryResultAvailable = function (query) {
  17082. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT_AVAILABLE);
  17083. };
  17084. /**
  17085. * Gets the value of a given query
  17086. * @param query defines the query to check
  17087. * @returns the value of the query
  17088. */
  17089. Engine.prototype.getQueryResult = function (query) {
  17090. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT);
  17091. };
  17092. /**
  17093. * Initiates an occlusion query
  17094. * @param algorithmType defines the algorithm to use
  17095. * @param query defines the query to use
  17096. * @returns the current engine
  17097. * @see http://doc.babylonjs.com/features/occlusionquery
  17098. */
  17099. Engine.prototype.beginOcclusionQuery = function (algorithmType, query) {
  17100. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  17101. this._gl.beginQuery(glAlgorithm, query);
  17102. return this;
  17103. };
  17104. /**
  17105. * Ends an occlusion query
  17106. * @see http://doc.babylonjs.com/features/occlusionquery
  17107. * @param algorithmType defines the algorithm to use
  17108. * @returns the current engine
  17109. */
  17110. Engine.prototype.endOcclusionQuery = function (algorithmType) {
  17111. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  17112. this._gl.endQuery(glAlgorithm);
  17113. return this;
  17114. };
  17115. /* Time queries */
  17116. Engine.prototype._createTimeQuery = function () {
  17117. var timerQuery = this._caps.timerQuery;
  17118. if (timerQuery.createQueryEXT) {
  17119. return timerQuery.createQueryEXT();
  17120. }
  17121. return this.createQuery();
  17122. };
  17123. Engine.prototype._deleteTimeQuery = function (query) {
  17124. var timerQuery = this._caps.timerQuery;
  17125. if (timerQuery.deleteQueryEXT) {
  17126. timerQuery.deleteQueryEXT(query);
  17127. return;
  17128. }
  17129. this.deleteQuery(query);
  17130. };
  17131. Engine.prototype._getTimeQueryResult = function (query) {
  17132. var timerQuery = this._caps.timerQuery;
  17133. if (timerQuery.getQueryObjectEXT) {
  17134. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_EXT);
  17135. }
  17136. return this.getQueryResult(query);
  17137. };
  17138. Engine.prototype._getTimeQueryAvailability = function (query) {
  17139. var timerQuery = this._caps.timerQuery;
  17140. if (timerQuery.getQueryObjectEXT) {
  17141. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_AVAILABLE_EXT);
  17142. }
  17143. return this.isQueryResultAvailable(query);
  17144. };
  17145. /**
  17146. * Starts a time query (used to measure time spent by the GPU on a specific frame)
  17147. * Please note that only one query can be issued at a time
  17148. * @returns a time token used to track the time span
  17149. */
  17150. Engine.prototype.startTimeQuery = function () {
  17151. var timerQuery = this._caps.timerQuery;
  17152. if (!timerQuery) {
  17153. return null;
  17154. }
  17155. var token = new BABYLON._TimeToken();
  17156. this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  17157. if (this._caps.canUseTimestampForTimerQuery) {
  17158. token._startTimeQuery = this._createTimeQuery();
  17159. timerQuery.queryCounterEXT(token._startTimeQuery, timerQuery.TIMESTAMP_EXT);
  17160. }
  17161. else {
  17162. if (this._currentNonTimestampToken) {
  17163. return this._currentNonTimestampToken;
  17164. }
  17165. token._timeElapsedQuery = this._createTimeQuery();
  17166. if (timerQuery.beginQueryEXT) {
  17167. timerQuery.beginQueryEXT(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  17168. }
  17169. else {
  17170. this._gl.beginQuery(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  17171. }
  17172. this._currentNonTimestampToken = token;
  17173. }
  17174. return token;
  17175. };
  17176. /**
  17177. * Ends a time query
  17178. * @param token defines the token used to measure the time span
  17179. * @returns the time spent (in ns)
  17180. */
  17181. Engine.prototype.endTimeQuery = function (token) {
  17182. var timerQuery = this._caps.timerQuery;
  17183. if (!timerQuery || !token) {
  17184. return -1;
  17185. }
  17186. if (this._caps.canUseTimestampForTimerQuery) {
  17187. if (!token._startTimeQuery) {
  17188. return -1;
  17189. }
  17190. if (!token._endTimeQuery) {
  17191. token._endTimeQuery = this._createTimeQuery();
  17192. timerQuery.queryCounterEXT(token._endTimeQuery, timerQuery.TIMESTAMP_EXT);
  17193. }
  17194. }
  17195. else if (!token._timeElapsedQueryEnded) {
  17196. if (!token._timeElapsedQuery) {
  17197. return -1;
  17198. }
  17199. if (timerQuery.endQueryEXT) {
  17200. timerQuery.endQueryEXT(timerQuery.TIME_ELAPSED_EXT);
  17201. }
  17202. else {
  17203. this._gl.endQuery(timerQuery.TIME_ELAPSED_EXT);
  17204. }
  17205. token._timeElapsedQueryEnded = true;
  17206. }
  17207. var disjoint = this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  17208. var available = false;
  17209. if (token._endTimeQuery) {
  17210. available = this._getTimeQueryAvailability(token._endTimeQuery);
  17211. }
  17212. else if (token._timeElapsedQuery) {
  17213. available = this._getTimeQueryAvailability(token._timeElapsedQuery);
  17214. }
  17215. if (available && !disjoint) {
  17216. var result = 0;
  17217. if (this._caps.canUseTimestampForTimerQuery) {
  17218. if (!token._startTimeQuery || !token._endTimeQuery) {
  17219. return -1;
  17220. }
  17221. var timeStart = this._getTimeQueryResult(token._startTimeQuery);
  17222. var timeEnd = this._getTimeQueryResult(token._endTimeQuery);
  17223. result = timeEnd - timeStart;
  17224. this._deleteTimeQuery(token._startTimeQuery);
  17225. this._deleteTimeQuery(token._endTimeQuery);
  17226. token._startTimeQuery = null;
  17227. token._endTimeQuery = null;
  17228. }
  17229. else {
  17230. if (!token._timeElapsedQuery) {
  17231. return -1;
  17232. }
  17233. result = this._getTimeQueryResult(token._timeElapsedQuery);
  17234. this._deleteTimeQuery(token._timeElapsedQuery);
  17235. token._timeElapsedQuery = null;
  17236. token._timeElapsedQueryEnded = false;
  17237. this._currentNonTimestampToken = null;
  17238. }
  17239. return result;
  17240. }
  17241. return -1;
  17242. };
  17243. Engine.prototype.getGlAlgorithmType = function (algorithmType) {
  17244. return algorithmType === BABYLON.AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE ? this._gl.ANY_SAMPLES_PASSED_CONSERVATIVE : this._gl.ANY_SAMPLES_PASSED;
  17245. };
  17246. // Transform feedback
  17247. /**
  17248. * Creates a webGL transform feedback object
  17249. * Please makes sure to check webGLVersion property to check if you are running webGL 2+
  17250. * @returns the webGL transform feedback object
  17251. */
  17252. Engine.prototype.createTransformFeedback = function () {
  17253. return this._gl.createTransformFeedback();
  17254. };
  17255. /**
  17256. * Delete a webGL transform feedback object
  17257. * @param value defines the webGL transform feedback object to delete
  17258. */
  17259. Engine.prototype.deleteTransformFeedback = function (value) {
  17260. this._gl.deleteTransformFeedback(value);
  17261. };
  17262. /**
  17263. * Bind a webGL transform feedback object to the webgl context
  17264. * @param value defines the webGL transform feedback object to bind
  17265. */
  17266. Engine.prototype.bindTransformFeedback = function (value) {
  17267. this._gl.bindTransformFeedback(this._gl.TRANSFORM_FEEDBACK, value);
  17268. };
  17269. /**
  17270. * Begins a transform feedback operation
  17271. * @param usePoints defines if points or triangles must be used
  17272. */
  17273. Engine.prototype.beginTransformFeedback = function (usePoints) {
  17274. if (usePoints === void 0) { usePoints = true; }
  17275. this._gl.beginTransformFeedback(usePoints ? this._gl.POINTS : this._gl.TRIANGLES);
  17276. };
  17277. /**
  17278. * Ends a transform feedback operation
  17279. */
  17280. Engine.prototype.endTransformFeedback = function () {
  17281. this._gl.endTransformFeedback();
  17282. };
  17283. /**
  17284. * Specify the varyings to use with transform feedback
  17285. * @param program defines the associated webGL program
  17286. * @param value defines the list of strings representing the varying names
  17287. */
  17288. Engine.prototype.setTranformFeedbackVaryings = function (program, value) {
  17289. this._gl.transformFeedbackVaryings(program, value, this._gl.INTERLEAVED_ATTRIBS);
  17290. };
  17291. /**
  17292. * Bind a webGL buffer for a transform feedback operation
  17293. * @param value defines the webGL buffer to bind
  17294. */
  17295. Engine.prototype.bindTransformFeedbackBuffer = function (value) {
  17296. this._gl.bindBufferBase(this._gl.TRANSFORM_FEEDBACK_BUFFER, 0, value);
  17297. };
  17298. /** @hidden */
  17299. Engine.prototype._loadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  17300. var _this = this;
  17301. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, database, useArrayBuffer, onError);
  17302. this._activeRequests.push(request);
  17303. request.onCompleteObservable.add(function (request) {
  17304. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  17305. });
  17306. return request;
  17307. };
  17308. /** @hidden */
  17309. Engine.prototype._loadFileAsync = function (url, database, useArrayBuffer) {
  17310. var _this = this;
  17311. return new Promise(function (resolve, reject) {
  17312. _this._loadFile(url, function (data) {
  17313. resolve(data);
  17314. }, undefined, database, useArrayBuffer, function (request, exception) {
  17315. reject(exception);
  17316. });
  17317. });
  17318. };
  17319. Engine.prototype._partialLoadFile = function (url, index, loadedFiles, scene, onfinish, onErrorCallBack) {
  17320. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  17321. var onload = function (data) {
  17322. loadedFiles[index] = data;
  17323. loadedFiles._internalCount++;
  17324. if (loadedFiles._internalCount === 6) {
  17325. onfinish(loadedFiles);
  17326. }
  17327. };
  17328. var onerror = function (request, exception) {
  17329. if (onErrorCallBack && request) {
  17330. onErrorCallBack(request.status + " " + request.statusText, exception);
  17331. }
  17332. };
  17333. this._loadFile(url, onload, undefined, undefined, true, onerror);
  17334. };
  17335. Engine.prototype._cascadeLoadFiles = function (scene, onfinish, files, onError) {
  17336. if (onError === void 0) { onError = null; }
  17337. var loadedFiles = [];
  17338. loadedFiles._internalCount = 0;
  17339. for (var index = 0; index < 6; index++) {
  17340. this._partialLoadFile(files[index], index, loadedFiles, scene, onfinish, onError);
  17341. }
  17342. };
  17343. // Statics
  17344. /**
  17345. * Gets a boolean indicating if the engine can be instanciated (ie. if a webGL context can be found)
  17346. * @returns true if the engine can be created
  17347. * @ignorenaming
  17348. */
  17349. Engine.isSupported = function () {
  17350. try {
  17351. var tempcanvas = document.createElement("canvas");
  17352. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  17353. return gl != null && !!window.WebGLRenderingContext;
  17354. }
  17355. catch (e) {
  17356. return false;
  17357. }
  17358. };
  17359. /** Use this array to turn off some WebGL2 features on known buggy browsers version */
  17360. Engine.ExceptionList = [
  17361. { key: "Chrome/63.0", capture: "63\\.0\\.3239\\.(\\d+)", captureConstraint: 108, targets: ["uniformBuffer"] },
  17362. { key: "Firefox/58", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  17363. { key: "Firefox/59", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  17364. { key: "Macintosh", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  17365. { key: "iPhone", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  17366. { key: "iPad", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] }
  17367. ];
  17368. /** Gets the list of created engines */
  17369. Engine.Instances = new Array();
  17370. // Const statics
  17371. Engine._ALPHA_DISABLE = 0;
  17372. Engine._ALPHA_ADD = 1;
  17373. Engine._ALPHA_COMBINE = 2;
  17374. Engine._ALPHA_SUBTRACT = 3;
  17375. Engine._ALPHA_MULTIPLY = 4;
  17376. Engine._ALPHA_MAXIMIZED = 5;
  17377. Engine._ALPHA_ONEONE = 6;
  17378. Engine._ALPHA_PREMULTIPLIED = 7;
  17379. Engine._ALPHA_PREMULTIPLIED_PORTERDUFF = 8;
  17380. Engine._ALPHA_INTERPOLATE = 9;
  17381. Engine._ALPHA_SCREENMODE = 10;
  17382. Engine._DELAYLOADSTATE_NONE = 0;
  17383. Engine._DELAYLOADSTATE_LOADED = 1;
  17384. Engine._DELAYLOADSTATE_LOADING = 2;
  17385. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  17386. Engine._TEXTUREFORMAT_ALPHA = 0;
  17387. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  17388. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  17389. Engine._TEXTUREFORMAT_RGB = 4;
  17390. Engine._TEXTUREFORMAT_RGBA = 5;
  17391. Engine._TEXTUREFORMAT_R = 6;
  17392. Engine._TEXTUREFORMAT_RG = 7;
  17393. Engine._TEXTURETYPE_UNSIGNED_INT = 0;
  17394. Engine._TEXTURETYPE_FLOAT = 1;
  17395. Engine._TEXTURETYPE_HALF_FLOAT = 2;
  17396. // Depht or Stencil test Constants.
  17397. Engine._NEVER = 0x0200; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn.
  17398. Engine._ALWAYS = 0x0207; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will always pass. i.e. Pixels will be drawn in the order they are drawn.
  17399. Engine._LESS = 0x0201; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is less than the stored value.
  17400. Engine._EQUAL = 0x0202; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is equals to the stored value.
  17401. Engine._LEQUAL = 0x0203; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is less than or equal to the stored value.
  17402. Engine._GREATER = 0x0204; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is greater than the stored value.
  17403. Engine._GEQUAL = 0x0206; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is greater than or equal to the stored value.
  17404. Engine._NOTEQUAL = 0x0205; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is not equal to the stored value.
  17405. // Stencil Actions Constants.
  17406. Engine._KEEP = 0x1E00;
  17407. Engine._REPLACE = 0x1E01;
  17408. Engine._INCR = 0x1E02;
  17409. Engine._DECR = 0x1E03;
  17410. Engine._INVERT = 0x150A;
  17411. Engine._INCR_WRAP = 0x8507;
  17412. Engine._DECR_WRAP = 0x8508;
  17413. // Texture rescaling mode
  17414. Engine._SCALEMODE_FLOOR = 1;
  17415. Engine._SCALEMODE_NEAREST = 2;
  17416. Engine._SCALEMODE_CEILING = 3;
  17417. // Updatable statics so stick with vars here
  17418. /**
  17419. * Gets or sets the epsilon value used by collision engine
  17420. */
  17421. Engine.CollisionsEpsilon = 0.001;
  17422. /**
  17423. * Gets or sets the relative url used to load code if using the engine in non-minified mode
  17424. */
  17425. Engine.CodeRepository = "src/";
  17426. /**
  17427. * Gets or sets the relative url used to load shaders if using the engine in non-minified mode
  17428. */
  17429. Engine.ShadersRepository = "src/Shaders/";
  17430. return Engine;
  17431. }());
  17432. BABYLON.Engine = Engine;
  17433. })(BABYLON || (BABYLON = {}));
  17434. //# sourceMappingURL=babylon.engine.js.map
  17435. var BABYLON;
  17436. (function (BABYLON) {
  17437. /**
  17438. * Node is the basic class for all scene objects (Mesh, Light Camera).
  17439. */
  17440. var Node = /** @class */ (function () {
  17441. /**
  17442. * Creates a new Node
  17443. * @param {string} name - the name and id to be given to this node
  17444. * @param {BABYLON.Scene} the scene this node will be added to
  17445. */
  17446. function Node(name, scene) {
  17447. if (scene === void 0) { scene = null; }
  17448. /**
  17449. * Gets or sets a string used to store user defined state for the node
  17450. */
  17451. this.state = "";
  17452. /**
  17453. * Gets or sets an object used to store user defined information for the node
  17454. */
  17455. this.metadata = null;
  17456. /**
  17457. * Gets or sets a boolean used to define if the node must be serialized
  17458. */
  17459. this.doNotSerialize = false;
  17460. /** @hidden */
  17461. this._isDisposed = false;
  17462. /**
  17463. * Gets a list of Animations associated with the node
  17464. */
  17465. this.animations = new Array();
  17466. this._ranges = {};
  17467. this._isEnabled = true;
  17468. this._isReady = true;
  17469. /** @hidden */
  17470. this._currentRenderId = -1;
  17471. this._parentRenderId = -1;
  17472. this._childRenderId = -1;
  17473. this._animationPropertiesOverride = null;
  17474. /**
  17475. * An event triggered when the mesh is disposed
  17476. */
  17477. this.onDisposeObservable = new BABYLON.Observable();
  17478. // Behaviors
  17479. this._behaviors = new Array();
  17480. this.name = name;
  17481. this.id = name;
  17482. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  17483. this.uniqueId = this._scene.getUniqueId();
  17484. this._initCache();
  17485. }
  17486. /**
  17487. * Gets a boolean indicating if the node has been disposed
  17488. * @returns true if the node was disposed
  17489. */
  17490. Node.prototype.isDisposed = function () {
  17491. return this._isDisposed;
  17492. };
  17493. Object.defineProperty(Node.prototype, "parent", {
  17494. get: function () {
  17495. return this._parentNode;
  17496. },
  17497. /**
  17498. * Gets or sets the parent of the node
  17499. */
  17500. set: function (parent) {
  17501. if (this._parentNode === parent) {
  17502. return;
  17503. }
  17504. // Remove self from list of children of parent
  17505. if (this._parentNode && this._parentNode._children !== undefined && this._parentNode._children !== null) {
  17506. var index = this._parentNode._children.indexOf(this);
  17507. if (index !== -1) {
  17508. this._parentNode._children.splice(index, 1);
  17509. }
  17510. }
  17511. // Store new parent
  17512. this._parentNode = parent;
  17513. // Add as child to new parent
  17514. if (this._parentNode) {
  17515. if (this._parentNode._children === undefined || this._parentNode._children === null) {
  17516. this._parentNode._children = new Array();
  17517. }
  17518. this._parentNode._children.push(this);
  17519. }
  17520. },
  17521. enumerable: true,
  17522. configurable: true
  17523. });
  17524. Object.defineProperty(Node.prototype, "animationPropertiesOverride", {
  17525. /**
  17526. * Gets or sets the animation properties override
  17527. */
  17528. get: function () {
  17529. if (!this._animationPropertiesOverride) {
  17530. return this._scene.animationPropertiesOverride;
  17531. }
  17532. return this._animationPropertiesOverride;
  17533. },
  17534. set: function (value) {
  17535. this._animationPropertiesOverride = value;
  17536. },
  17537. enumerable: true,
  17538. configurable: true
  17539. });
  17540. /**
  17541. * Gets a string idenfifying the name of the class
  17542. * @returns "Node" string
  17543. */
  17544. Node.prototype.getClassName = function () {
  17545. return "Node";
  17546. };
  17547. Object.defineProperty(Node.prototype, "onDispose", {
  17548. /**
  17549. * Sets a callback that will be raised when the node will be disposed
  17550. */
  17551. set: function (callback) {
  17552. if (this._onDisposeObserver) {
  17553. this.onDisposeObservable.remove(this._onDisposeObserver);
  17554. }
  17555. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  17556. },
  17557. enumerable: true,
  17558. configurable: true
  17559. });
  17560. /**
  17561. * Gets the scene of the node
  17562. * @returns a {BABYLON.Scene}
  17563. */
  17564. Node.prototype.getScene = function () {
  17565. return this._scene;
  17566. };
  17567. /**
  17568. * Gets the engine of the node
  17569. * @returns a {BABYLON.Engine}
  17570. */
  17571. Node.prototype.getEngine = function () {
  17572. return this._scene.getEngine();
  17573. };
  17574. /**
  17575. * Attach a behavior to the node
  17576. * @see http://doc.babylonjs.com/features/behaviour
  17577. * @param behavior defines the behavior to attach
  17578. * @returns the current Node
  17579. */
  17580. Node.prototype.addBehavior = function (behavior) {
  17581. var _this = this;
  17582. var index = this._behaviors.indexOf(behavior);
  17583. if (index !== -1) {
  17584. return this;
  17585. }
  17586. behavior.init();
  17587. if (this._scene.isLoading) {
  17588. // We defer the attach when the scene will be loaded
  17589. this._scene.onDataLoadedObservable.addOnce(function () {
  17590. behavior.attach(_this);
  17591. });
  17592. }
  17593. else {
  17594. behavior.attach(this);
  17595. }
  17596. this._behaviors.push(behavior);
  17597. return this;
  17598. };
  17599. /**
  17600. * Remove an attached behavior
  17601. * @see http://doc.babylonjs.com/features/behaviour
  17602. * @param behavior defines the behavior to attach
  17603. * @returns the current Node
  17604. */
  17605. Node.prototype.removeBehavior = function (behavior) {
  17606. var index = this._behaviors.indexOf(behavior);
  17607. if (index === -1) {
  17608. return this;
  17609. }
  17610. this._behaviors[index].detach();
  17611. this._behaviors.splice(index, 1);
  17612. return this;
  17613. };
  17614. Object.defineProperty(Node.prototype, "behaviors", {
  17615. /**
  17616. * Gets the list of attached behaviors
  17617. * @see http://doc.babylonjs.com/features/behaviour
  17618. */
  17619. get: function () {
  17620. return this._behaviors;
  17621. },
  17622. enumerable: true,
  17623. configurable: true
  17624. });
  17625. /**
  17626. * Gets an attached behavior by name
  17627. * @param name defines the name of the behavior to look for
  17628. * @see http://doc.babylonjs.com/features/behaviour
  17629. * @returns null if behavior was not found else the requested behavior
  17630. */
  17631. Node.prototype.getBehaviorByName = function (name) {
  17632. for (var _i = 0, _a = this._behaviors; _i < _a.length; _i++) {
  17633. var behavior = _a[_i];
  17634. if (behavior.name === name) {
  17635. return behavior;
  17636. }
  17637. }
  17638. return null;
  17639. };
  17640. /**
  17641. * Returns the world matrix of the node
  17642. * @returns a matrix containing the node's world matrix
  17643. */
  17644. Node.prototype.getWorldMatrix = function () {
  17645. return BABYLON.Matrix.Identity();
  17646. };
  17647. /** @hidden */
  17648. Node.prototype._getWorldMatrixDeterminant = function () {
  17649. return 1;
  17650. };
  17651. // override it in derived class if you add new variables to the cache
  17652. // and call the parent class method
  17653. /** @hidden */
  17654. Node.prototype._initCache = function () {
  17655. this._cache = {};
  17656. this._cache.parent = undefined;
  17657. };
  17658. /** @hidden */
  17659. Node.prototype.updateCache = function (force) {
  17660. if (!force && this.isSynchronized())
  17661. return;
  17662. this._cache.parent = this.parent;
  17663. this._updateCache();
  17664. };
  17665. // override it in derived class if you add new variables to the cache
  17666. // and call the parent class method if !ignoreParentClass
  17667. /** @hidden */
  17668. Node.prototype._updateCache = function (ignoreParentClass) {
  17669. };
  17670. // override it in derived class if you add new variables to the cache
  17671. /** @hidden */
  17672. Node.prototype._isSynchronized = function () {
  17673. return true;
  17674. };
  17675. /** @hidden */
  17676. Node.prototype._markSyncedWithParent = function () {
  17677. if (this.parent) {
  17678. this._parentRenderId = this.parent._childRenderId;
  17679. }
  17680. };
  17681. /** @hidden */
  17682. Node.prototype.isSynchronizedWithParent = function () {
  17683. if (!this.parent) {
  17684. return true;
  17685. }
  17686. if (this._parentRenderId !== this.parent._childRenderId) {
  17687. return false;
  17688. }
  17689. return this.parent.isSynchronized();
  17690. };
  17691. /** @hidden */
  17692. Node.prototype.isSynchronized = function (updateCache) {
  17693. var check = this.hasNewParent();
  17694. check = check || !this.isSynchronizedWithParent();
  17695. check = check || !this._isSynchronized();
  17696. if (updateCache)
  17697. this.updateCache(true);
  17698. return !check;
  17699. };
  17700. /** @hidden */
  17701. Node.prototype.hasNewParent = function (update) {
  17702. if (this._cache.parent === this.parent)
  17703. return false;
  17704. if (update)
  17705. this._cache.parent = this.parent;
  17706. return true;
  17707. };
  17708. /**
  17709. * Is this node ready to be used/rendered
  17710. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  17711. * @return true if the node is ready
  17712. */
  17713. Node.prototype.isReady = function (completeCheck) {
  17714. if (completeCheck === void 0) { completeCheck = false; }
  17715. return this._isReady;
  17716. };
  17717. /**
  17718. * Is this node enabled?
  17719. * 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
  17720. * @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
  17721. * @return whether this node (and its parent) is enabled
  17722. */
  17723. Node.prototype.isEnabled = function (checkAncestors) {
  17724. if (checkAncestors === void 0) { checkAncestors = true; }
  17725. if (checkAncestors === false) {
  17726. return this._isEnabled;
  17727. }
  17728. if (this._isEnabled === false) {
  17729. return false;
  17730. }
  17731. if (this.parent !== undefined && this.parent !== null) {
  17732. return this.parent.isEnabled(checkAncestors);
  17733. }
  17734. return true;
  17735. };
  17736. /**
  17737. * Set the enabled state of this node
  17738. * @param value defines the new enabled state
  17739. */
  17740. Node.prototype.setEnabled = function (value) {
  17741. this._isEnabled = value;
  17742. };
  17743. /**
  17744. * Is this node a descendant of the given node?
  17745. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined
  17746. * @param ancestor defines the parent node to inspect
  17747. * @returns a boolean indicating if this node is a descendant of the given node
  17748. */
  17749. Node.prototype.isDescendantOf = function (ancestor) {
  17750. if (this.parent) {
  17751. if (this.parent === ancestor) {
  17752. return true;
  17753. }
  17754. return this.parent.isDescendantOf(ancestor);
  17755. }
  17756. return false;
  17757. };
  17758. /** @hidden */
  17759. Node.prototype._getDescendants = function (results, directDescendantsOnly, predicate) {
  17760. if (directDescendantsOnly === void 0) { directDescendantsOnly = false; }
  17761. if (!this._children) {
  17762. return;
  17763. }
  17764. for (var index = 0; index < this._children.length; index++) {
  17765. var item = this._children[index];
  17766. if (!predicate || predicate(item)) {
  17767. results.push(item);
  17768. }
  17769. if (!directDescendantsOnly) {
  17770. item._getDescendants(results, false, predicate);
  17771. }
  17772. }
  17773. };
  17774. /**
  17775. * Will return all nodes that have this node as ascendant
  17776. * @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
  17777. * @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
  17778. * @return all children nodes of all types
  17779. */
  17780. Node.prototype.getDescendants = function (directDescendantsOnly, predicate) {
  17781. var results = new Array();
  17782. this._getDescendants(results, directDescendantsOnly, predicate);
  17783. return results;
  17784. };
  17785. /**
  17786. * Get all child-meshes of this node
  17787. * @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
  17788. * @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
  17789. * @returns an array of {BABYLON.AbstractMesh}
  17790. */
  17791. Node.prototype.getChildMeshes = function (directDescendantsOnly, predicate) {
  17792. var results = [];
  17793. this._getDescendants(results, directDescendantsOnly, function (node) {
  17794. return ((!predicate || predicate(node)) && (node instanceof BABYLON.AbstractMesh));
  17795. });
  17796. return results;
  17797. };
  17798. /**
  17799. * Get all child-transformNodes of this node
  17800. * @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
  17801. * @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
  17802. * @returns an array of {BABYLON.TransformNode}
  17803. */
  17804. Node.prototype.getChildTransformNodes = function (directDescendantsOnly, predicate) {
  17805. var results = [];
  17806. this._getDescendants(results, directDescendantsOnly, function (node) {
  17807. return ((!predicate || predicate(node)) && (node instanceof BABYLON.TransformNode));
  17808. });
  17809. return results;
  17810. };
  17811. /**
  17812. * Get all direct children of this node
  17813. * @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
  17814. * @returns an array of {BABYLON.Node}
  17815. */
  17816. Node.prototype.getChildren = function (predicate) {
  17817. return this.getDescendants(true, predicate);
  17818. };
  17819. /** @hidden */
  17820. Node.prototype._setReady = function (state) {
  17821. if (state === this._isReady) {
  17822. return;
  17823. }
  17824. if (!state) {
  17825. this._isReady = false;
  17826. return;
  17827. }
  17828. if (this.onReady) {
  17829. this.onReady(this);
  17830. }
  17831. this._isReady = true;
  17832. };
  17833. /**
  17834. * Get an animation by name
  17835. * @param name defines the name of the animation to look for
  17836. * @returns null if not found else the requested animation
  17837. */
  17838. Node.prototype.getAnimationByName = function (name) {
  17839. for (var i = 0; i < this.animations.length; i++) {
  17840. var animation = this.animations[i];
  17841. if (animation.name === name) {
  17842. return animation;
  17843. }
  17844. }
  17845. return null;
  17846. };
  17847. /**
  17848. * Creates an animation range for this node
  17849. * @param name defines the name of the range
  17850. * @param from defines the starting key
  17851. * @param to defines the end key
  17852. */
  17853. Node.prototype.createAnimationRange = function (name, from, to) {
  17854. // check name not already in use
  17855. if (!this._ranges[name]) {
  17856. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  17857. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  17858. if (this.animations[i]) {
  17859. this.animations[i].createRange(name, from, to);
  17860. }
  17861. }
  17862. }
  17863. };
  17864. /**
  17865. * Delete a specific animation range
  17866. * @param name defines the name of the range to delete
  17867. * @param deleteFrames defines if animation frames from the range must be deleted as well
  17868. */
  17869. Node.prototype.deleteAnimationRange = function (name, deleteFrames) {
  17870. if (deleteFrames === void 0) { deleteFrames = true; }
  17871. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  17872. if (this.animations[i]) {
  17873. this.animations[i].deleteRange(name, deleteFrames);
  17874. }
  17875. }
  17876. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  17877. };
  17878. /**
  17879. * Get an animation range by name
  17880. * @param name defines the name of the animation range to look for
  17881. * @returns null if not found else the requested animation range
  17882. */
  17883. Node.prototype.getAnimationRange = function (name) {
  17884. return this._ranges[name];
  17885. };
  17886. /**
  17887. * Will start the animation sequence
  17888. * @param name defines the range frames for animation sequence
  17889. * @param loop defines if the animation should loop (false by default)
  17890. * @param speedRatio defines the speed factor in which to run the animation (1 by default)
  17891. * @param onAnimationEnd defines a function to be executed when the animation ended (undefined by default)
  17892. * @returns the object created for this animation. If range does not exist, it will return null
  17893. */
  17894. Node.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  17895. var range = this.getAnimationRange(name);
  17896. if (!range) {
  17897. return null;
  17898. }
  17899. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  17900. };
  17901. /**
  17902. * Serialize animation ranges into a JSON compatible object
  17903. * @returns serialization object
  17904. */
  17905. Node.prototype.serializeAnimationRanges = function () {
  17906. var serializationRanges = [];
  17907. for (var name in this._ranges) {
  17908. var localRange = this._ranges[name];
  17909. if (!localRange) {
  17910. continue;
  17911. }
  17912. var range = {};
  17913. range.name = name;
  17914. range.from = localRange.from;
  17915. range.to = localRange.to;
  17916. serializationRanges.push(range);
  17917. }
  17918. return serializationRanges;
  17919. };
  17920. /**
  17921. * Computes the world matrix of the node
  17922. * @param force defines if the cache version should be invalidated forcing the world matrix to be created from scratch
  17923. * @returns the world matrix
  17924. */
  17925. Node.prototype.computeWorldMatrix = function (force) {
  17926. return BABYLON.Matrix.Identity();
  17927. };
  17928. /**
  17929. * Releases resources associated with this node.
  17930. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  17931. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  17932. */
  17933. Node.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  17934. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  17935. if (!doNotRecurse) {
  17936. var nodes = this.getDescendants(true);
  17937. for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) {
  17938. var node = nodes_1[_i];
  17939. node.dispose(doNotRecurse, disposeMaterialAndTextures);
  17940. }
  17941. }
  17942. else {
  17943. var transformNodes = this.getChildTransformNodes(true);
  17944. for (var _a = 0, transformNodes_1 = transformNodes; _a < transformNodes_1.length; _a++) {
  17945. var transformNode = transformNodes_1[_a];
  17946. transformNode.parent = null;
  17947. transformNode.computeWorldMatrix(true);
  17948. }
  17949. }
  17950. this.parent = null;
  17951. // Callback
  17952. this.onDisposeObservable.notifyObservers(this);
  17953. this.onDisposeObservable.clear();
  17954. // Behaviors
  17955. for (var _b = 0, _c = this._behaviors; _b < _c.length; _b++) {
  17956. var behavior = _c[_b];
  17957. behavior.detach();
  17958. }
  17959. this._behaviors = [];
  17960. this._isDisposed = true;
  17961. };
  17962. /**
  17963. * Parse animation range data from a serialization object and store them into a given node
  17964. * @param node defines where to store the animation ranges
  17965. * @param parsedNode defines the serialization object to read data from
  17966. * @param scene defines the hosting scene
  17967. */
  17968. Node.ParseAnimationRanges = function (node, parsedNode, scene) {
  17969. if (parsedNode.ranges) {
  17970. for (var index = 0; index < parsedNode.ranges.length; index++) {
  17971. var data = parsedNode.ranges[index];
  17972. node.createAnimationRange(data.name, data.from, data.to);
  17973. }
  17974. }
  17975. };
  17976. __decorate([
  17977. BABYLON.serialize()
  17978. ], Node.prototype, "name", void 0);
  17979. __decorate([
  17980. BABYLON.serialize()
  17981. ], Node.prototype, "id", void 0);
  17982. __decorate([
  17983. BABYLON.serialize()
  17984. ], Node.prototype, "uniqueId", void 0);
  17985. __decorate([
  17986. BABYLON.serialize()
  17987. ], Node.prototype, "state", void 0);
  17988. __decorate([
  17989. BABYLON.serialize()
  17990. ], Node.prototype, "metadata", void 0);
  17991. return Node;
  17992. }());
  17993. BABYLON.Node = Node;
  17994. })(BABYLON || (BABYLON = {}));
  17995. //# sourceMappingURL=babylon.node.js.map
  17996. var BABYLON;
  17997. (function (BABYLON) {
  17998. var BoundingSphere = /** @class */ (function () {
  17999. /**
  18000. * Creates a new bounding sphere
  18001. * @param min defines the minimum vector (in local space)
  18002. * @param max defines the maximum vector (in local space)
  18003. */
  18004. function BoundingSphere(min, max) {
  18005. this._tempRadiusVector = BABYLON.Vector3.Zero();
  18006. this.reConstruct(min, max);
  18007. }
  18008. /**
  18009. * Recreates the entire bounding sphere from scratch
  18010. * @param min defines the new minimum vector (in local space)
  18011. * @param max defines the new maximum vector (in local space)
  18012. */
  18013. BoundingSphere.prototype.reConstruct = function (min, max) {
  18014. this.minimum = min.clone();
  18015. this.maximum = max.clone();
  18016. var distance = BABYLON.Vector3.Distance(min, max);
  18017. this.center = BABYLON.Vector3.Lerp(min, max, 0.5);
  18018. this.radius = distance * 0.5;
  18019. this.centerWorld = BABYLON.Vector3.Zero();
  18020. this._update(BABYLON.Matrix.Identity());
  18021. };
  18022. // Methods
  18023. BoundingSphere.prototype._update = function (world) {
  18024. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  18025. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  18026. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  18027. };
  18028. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  18029. for (var i = 0; i < 6; i++) {
  18030. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  18031. return false;
  18032. }
  18033. return true;
  18034. };
  18035. BoundingSphere.prototype.intersectsPoint = function (point) {
  18036. var x = this.centerWorld.x - point.x;
  18037. var y = this.centerWorld.y - point.y;
  18038. var z = this.centerWorld.z - point.z;
  18039. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  18040. if (Math.abs(this.radiusWorld - distance) < BABYLON.Epsilon)
  18041. return false;
  18042. return true;
  18043. };
  18044. // Statics
  18045. BoundingSphere.Intersects = function (sphere0, sphere1) {
  18046. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  18047. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  18048. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  18049. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  18050. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  18051. return false;
  18052. return true;
  18053. };
  18054. return BoundingSphere;
  18055. }());
  18056. BABYLON.BoundingSphere = BoundingSphere;
  18057. })(BABYLON || (BABYLON = {}));
  18058. //# sourceMappingURL=babylon.boundingSphere.js.map
  18059. var BABYLON;
  18060. (function (BABYLON) {
  18061. var BoundingBox = /** @class */ (function () {
  18062. /**
  18063. * Creates a new bounding box
  18064. * @param min defines the minimum vector (in local space)
  18065. * @param max defines the maximum vector (in local space)
  18066. */
  18067. function BoundingBox(min, max) {
  18068. this.vectorsWorld = new Array();
  18069. this.reConstruct(min, max);
  18070. }
  18071. // Methods
  18072. /**
  18073. * Recreates the entire bounding box from scratch
  18074. * @param min defines the new minimum vector (in local space)
  18075. * @param max defines the new maximum vector (in local space)
  18076. */
  18077. BoundingBox.prototype.reConstruct = function (min, max) {
  18078. this.minimum = min.clone();
  18079. this.maximum = max.clone();
  18080. // Bounding vectors
  18081. this.vectors = new Array();
  18082. this.vectors.push(this.minimum.clone());
  18083. this.vectors.push(this.maximum.clone());
  18084. this.vectors.push(this.minimum.clone());
  18085. this.vectors[2].x = this.maximum.x;
  18086. this.vectors.push(this.minimum.clone());
  18087. this.vectors[3].y = this.maximum.y;
  18088. this.vectors.push(this.minimum.clone());
  18089. this.vectors[4].z = this.maximum.z;
  18090. this.vectors.push(this.maximum.clone());
  18091. this.vectors[5].z = this.minimum.z;
  18092. this.vectors.push(this.maximum.clone());
  18093. this.vectors[6].x = this.minimum.x;
  18094. this.vectors.push(this.maximum.clone());
  18095. this.vectors[7].y = this.minimum.y;
  18096. // OBB
  18097. this.center = this.maximum.add(this.minimum).scale(0.5);
  18098. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  18099. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  18100. // World
  18101. for (var index = 0; index < this.vectors.length; index++) {
  18102. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  18103. }
  18104. this.minimumWorld = BABYLON.Vector3.Zero();
  18105. this.maximumWorld = BABYLON.Vector3.Zero();
  18106. this.centerWorld = BABYLON.Vector3.Zero();
  18107. this.extendSizeWorld = BABYLON.Vector3.Zero();
  18108. this._update(this._worldMatrix || BABYLON.Matrix.Identity());
  18109. };
  18110. BoundingBox.prototype.getWorldMatrix = function () {
  18111. return this._worldMatrix;
  18112. };
  18113. BoundingBox.prototype.setWorldMatrix = function (matrix) {
  18114. this._worldMatrix.copyFrom(matrix);
  18115. return this;
  18116. };
  18117. BoundingBox.prototype._update = function (world) {
  18118. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  18119. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  18120. for (var index = 0; index < this.vectors.length; index++) {
  18121. var v = this.vectorsWorld[index];
  18122. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  18123. if (v.x < this.minimumWorld.x)
  18124. this.minimumWorld.x = v.x;
  18125. if (v.y < this.minimumWorld.y)
  18126. this.minimumWorld.y = v.y;
  18127. if (v.z < this.minimumWorld.z)
  18128. this.minimumWorld.z = v.z;
  18129. if (v.x > this.maximumWorld.x)
  18130. this.maximumWorld.x = v.x;
  18131. if (v.y > this.maximumWorld.y)
  18132. this.maximumWorld.y = v.y;
  18133. if (v.z > this.maximumWorld.z)
  18134. this.maximumWorld.z = v.z;
  18135. }
  18136. // Extend
  18137. this.maximumWorld.subtractToRef(this.minimumWorld, this.extendSizeWorld);
  18138. this.extendSizeWorld.scaleInPlace(0.5);
  18139. // OBB
  18140. this.maximumWorld.addToRef(this.minimumWorld, this.centerWorld);
  18141. this.centerWorld.scaleInPlace(0.5);
  18142. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  18143. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  18144. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  18145. this._worldMatrix = world;
  18146. };
  18147. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  18148. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  18149. };
  18150. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  18151. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  18152. };
  18153. BoundingBox.prototype.intersectsPoint = function (point) {
  18154. var delta = -BABYLON.Epsilon;
  18155. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  18156. return false;
  18157. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  18158. return false;
  18159. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  18160. return false;
  18161. return true;
  18162. };
  18163. BoundingBox.prototype.intersectsSphere = function (sphere) {
  18164. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  18165. };
  18166. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  18167. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  18168. return false;
  18169. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  18170. return false;
  18171. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  18172. return false;
  18173. return true;
  18174. };
  18175. // Statics
  18176. BoundingBox.Intersects = function (box0, box1) {
  18177. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  18178. return false;
  18179. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  18180. return false;
  18181. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  18182. return false;
  18183. return true;
  18184. };
  18185. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  18186. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  18187. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  18188. return (num <= (sphereRadius * sphereRadius));
  18189. };
  18190. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  18191. for (var p = 0; p < 6; p++) {
  18192. for (var i = 0; i < 8; i++) {
  18193. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  18194. return false;
  18195. }
  18196. }
  18197. }
  18198. return true;
  18199. };
  18200. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  18201. for (var p = 0; p < 6; p++) {
  18202. var inCount = 8;
  18203. for (var i = 0; i < 8; i++) {
  18204. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  18205. --inCount;
  18206. }
  18207. else {
  18208. break;
  18209. }
  18210. }
  18211. if (inCount === 0)
  18212. return false;
  18213. }
  18214. return true;
  18215. };
  18216. return BoundingBox;
  18217. }());
  18218. BABYLON.BoundingBox = BoundingBox;
  18219. })(BABYLON || (BABYLON = {}));
  18220. //# sourceMappingURL=babylon.boundingBox.js.map
  18221. var BABYLON;
  18222. (function (BABYLON) {
  18223. var computeBoxExtents = function (axis, box) {
  18224. var p = BABYLON.Vector3.Dot(box.centerWorld, axis);
  18225. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  18226. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  18227. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  18228. var r = r0 + r1 + r2;
  18229. return {
  18230. min: p - r,
  18231. max: p + r
  18232. };
  18233. };
  18234. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  18235. var axisOverlap = function (axis, box0, box1) {
  18236. var result0 = computeBoxExtents(axis, box0);
  18237. var result1 = computeBoxExtents(axis, box1);
  18238. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  18239. };
  18240. var BoundingInfo = /** @class */ (function () {
  18241. function BoundingInfo(minimum, maximum) {
  18242. this.minimum = minimum;
  18243. this.maximum = maximum;
  18244. this._isLocked = false;
  18245. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  18246. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  18247. }
  18248. Object.defineProperty(BoundingInfo.prototype, "isLocked", {
  18249. get: function () {
  18250. return this._isLocked;
  18251. },
  18252. set: function (value) {
  18253. this._isLocked = value;
  18254. },
  18255. enumerable: true,
  18256. configurable: true
  18257. });
  18258. // Methods
  18259. BoundingInfo.prototype.update = function (world) {
  18260. if (this._isLocked) {
  18261. return;
  18262. }
  18263. this.boundingBox._update(world);
  18264. this.boundingSphere._update(world);
  18265. };
  18266. /**
  18267. * Recreate the bounding info to be centered around a specific point given a specific extend.
  18268. * @param center New center of the bounding info
  18269. * @param extend New extend of the bounding info
  18270. */
  18271. BoundingInfo.prototype.centerOn = function (center, extend) {
  18272. this.minimum = center.subtract(extend);
  18273. this.maximum = center.add(extend);
  18274. this.boundingBox = new BABYLON.BoundingBox(this.minimum, this.maximum);
  18275. this.boundingSphere = new BABYLON.BoundingSphere(this.minimum, this.maximum);
  18276. return this;
  18277. };
  18278. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  18279. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  18280. return false;
  18281. return this.boundingBox.isInFrustum(frustumPlanes);
  18282. };
  18283. Object.defineProperty(BoundingInfo.prototype, "diagonalLength", {
  18284. /**
  18285. * Gets the world distance between the min and max points of the bounding box
  18286. */
  18287. get: function () {
  18288. var boundingBox = this.boundingBox;
  18289. var size = boundingBox.maximumWorld.subtract(boundingBox.minimumWorld);
  18290. return size.length();
  18291. },
  18292. enumerable: true,
  18293. configurable: true
  18294. });
  18295. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  18296. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  18297. };
  18298. BoundingInfo.prototype._checkCollision = function (collider) {
  18299. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  18300. };
  18301. BoundingInfo.prototype.intersectsPoint = function (point) {
  18302. if (!this.boundingSphere.centerWorld) {
  18303. return false;
  18304. }
  18305. if (!this.boundingSphere.intersectsPoint(point)) {
  18306. return false;
  18307. }
  18308. if (!this.boundingBox.intersectsPoint(point)) {
  18309. return false;
  18310. }
  18311. return true;
  18312. };
  18313. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  18314. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  18315. return false;
  18316. }
  18317. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  18318. return false;
  18319. }
  18320. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  18321. return false;
  18322. }
  18323. if (!precise) {
  18324. return true;
  18325. }
  18326. var box0 = this.boundingBox;
  18327. var box1 = boundingInfo.boundingBox;
  18328. if (!axisOverlap(box0.directions[0], box0, box1))
  18329. return false;
  18330. if (!axisOverlap(box0.directions[1], box0, box1))
  18331. return false;
  18332. if (!axisOverlap(box0.directions[2], box0, box1))
  18333. return false;
  18334. if (!axisOverlap(box1.directions[0], box0, box1))
  18335. return false;
  18336. if (!axisOverlap(box1.directions[1], box0, box1))
  18337. return false;
  18338. if (!axisOverlap(box1.directions[2], box0, box1))
  18339. return false;
  18340. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  18341. return false;
  18342. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  18343. return false;
  18344. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  18345. return false;
  18346. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  18347. return false;
  18348. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  18349. return false;
  18350. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  18351. return false;
  18352. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  18353. return false;
  18354. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  18355. return false;
  18356. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  18357. return false;
  18358. return true;
  18359. };
  18360. return BoundingInfo;
  18361. }());
  18362. BABYLON.BoundingInfo = BoundingInfo;
  18363. })(BABYLON || (BABYLON = {}));
  18364. //# sourceMappingURL=babylon.boundingInfo.js.map
  18365. var BABYLON;
  18366. (function (BABYLON) {
  18367. var TransformNode = /** @class */ (function (_super) {
  18368. __extends(TransformNode, _super);
  18369. function TransformNode(name, scene, isPure) {
  18370. if (scene === void 0) { scene = null; }
  18371. if (isPure === void 0) { isPure = true; }
  18372. var _this = _super.call(this, name, scene) || this;
  18373. _this._forward = new BABYLON.Vector3(0, 0, 1);
  18374. _this._forwardInverted = new BABYLON.Vector3(0, 0, -1);
  18375. _this._up = new BABYLON.Vector3(0, 1, 0);
  18376. _this._right = new BABYLON.Vector3(1, 0, 0);
  18377. _this._rightInverted = new BABYLON.Vector3(-1, 0, 0);
  18378. // Properties
  18379. _this._rotation = BABYLON.Vector3.Zero();
  18380. _this._scaling = BABYLON.Vector3.One();
  18381. _this._isDirty = false;
  18382. _this.billboardMode = TransformNode.BILLBOARDMODE_NONE;
  18383. _this.scalingDeterminant = 1;
  18384. _this.infiniteDistance = false;
  18385. _this.position = BABYLON.Vector3.Zero();
  18386. _this._localWorld = BABYLON.Matrix.Zero();
  18387. _this._worldMatrix = BABYLON.Matrix.Zero();
  18388. _this._worldMatrixDeterminant = 0;
  18389. _this._absolutePosition = BABYLON.Vector3.Zero();
  18390. _this._pivotMatrix = BABYLON.Matrix.Identity();
  18391. _this._postMultiplyPivotMatrix = false;
  18392. _this._isWorldMatrixFrozen = false;
  18393. /**
  18394. * An event triggered after the world matrix is updated
  18395. */
  18396. _this.onAfterWorldMatrixUpdateObservable = new BABYLON.Observable();
  18397. _this._nonUniformScaling = false;
  18398. if (isPure) {
  18399. _this.getScene().addTransformNode(_this);
  18400. }
  18401. return _this;
  18402. }
  18403. /**
  18404. * Gets a string idenfifying the name of the class
  18405. * @returns "TransformNode" string
  18406. */
  18407. TransformNode.prototype.getClassName = function () {
  18408. return "TransformNode";
  18409. };
  18410. Object.defineProperty(TransformNode.prototype, "rotation", {
  18411. /**
  18412. * Rotation property : a Vector3 depicting the rotation value in radians around each local axis X, Y, Z.
  18413. * If rotation quaternion is set, this Vector3 will (almost always) be the Zero vector!
  18414. * Default : (0.0, 0.0, 0.0)
  18415. */
  18416. get: function () {
  18417. return this._rotation;
  18418. },
  18419. set: function (newRotation) {
  18420. this._rotation = newRotation;
  18421. },
  18422. enumerable: true,
  18423. configurable: true
  18424. });
  18425. Object.defineProperty(TransformNode.prototype, "scaling", {
  18426. /**
  18427. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  18428. * Default : (1.0, 1.0, 1.0)
  18429. */
  18430. get: function () {
  18431. return this._scaling;
  18432. },
  18433. /**
  18434. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  18435. * Default : (1.0, 1.0, 1.0)
  18436. */
  18437. set: function (newScaling) {
  18438. this._scaling = newScaling;
  18439. },
  18440. enumerable: true,
  18441. configurable: true
  18442. });
  18443. Object.defineProperty(TransformNode.prototype, "rotationQuaternion", {
  18444. /**
  18445. * Rotation Quaternion property : this a Quaternion object depicting the mesh rotation by using a unit quaternion.
  18446. * It's null by default.
  18447. * If set, only the rotationQuaternion is then used to compute the mesh rotation and its property `.rotation\ is then ignored and set to (0.0, 0.0, 0.0)
  18448. */
  18449. get: function () {
  18450. return this._rotationQuaternion;
  18451. },
  18452. set: function (quaternion) {
  18453. this._rotationQuaternion = quaternion;
  18454. //reset the rotation vector.
  18455. if (quaternion && this.rotation.length()) {
  18456. this.rotation.copyFromFloats(0.0, 0.0, 0.0);
  18457. }
  18458. },
  18459. enumerable: true,
  18460. configurable: true
  18461. });
  18462. Object.defineProperty(TransformNode.prototype, "forward", {
  18463. /**
  18464. * The forward direction of that transform in world space.
  18465. */
  18466. get: function () {
  18467. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this.getScene().useRightHandedSystem ? this._forwardInverted : this._forward, this.getWorldMatrix()));
  18468. },
  18469. enumerable: true,
  18470. configurable: true
  18471. });
  18472. Object.defineProperty(TransformNode.prototype, "up", {
  18473. /**
  18474. * The up direction of that transform in world space.
  18475. */
  18476. get: function () {
  18477. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this._up, this.getWorldMatrix()));
  18478. },
  18479. enumerable: true,
  18480. configurable: true
  18481. });
  18482. Object.defineProperty(TransformNode.prototype, "right", {
  18483. /**
  18484. * The right direction of that transform in world space.
  18485. */
  18486. get: function () {
  18487. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this.getScene().useRightHandedSystem ? this._rightInverted : this._right, this.getWorldMatrix()));
  18488. },
  18489. enumerable: true,
  18490. configurable: true
  18491. });
  18492. /**
  18493. * Returns the latest update of the World matrix
  18494. * Returns a Matrix.
  18495. */
  18496. TransformNode.prototype.getWorldMatrix = function () {
  18497. if (this._currentRenderId !== this.getScene().getRenderId()) {
  18498. this.computeWorldMatrix();
  18499. }
  18500. return this._worldMatrix;
  18501. };
  18502. /** @hidden */
  18503. TransformNode.prototype._getWorldMatrixDeterminant = function () {
  18504. return this._worldMatrixDeterminant;
  18505. };
  18506. Object.defineProperty(TransformNode.prototype, "worldMatrixFromCache", {
  18507. /**
  18508. * Returns directly the latest state of the mesh World matrix.
  18509. * A Matrix is returned.
  18510. */
  18511. get: function () {
  18512. return this._worldMatrix;
  18513. },
  18514. enumerable: true,
  18515. configurable: true
  18516. });
  18517. /**
  18518. * Copies the paramater passed Matrix into the mesh Pose matrix.
  18519. * Returns the TransformNode.
  18520. */
  18521. TransformNode.prototype.updatePoseMatrix = function (matrix) {
  18522. this._poseMatrix.copyFrom(matrix);
  18523. return this;
  18524. };
  18525. /**
  18526. * Returns the mesh Pose matrix.
  18527. * Returned object : Matrix
  18528. */
  18529. TransformNode.prototype.getPoseMatrix = function () {
  18530. return this._poseMatrix;
  18531. };
  18532. TransformNode.prototype._isSynchronized = function () {
  18533. if (this._isDirty) {
  18534. return false;
  18535. }
  18536. if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== TransformNode.BILLBOARDMODE_NONE)
  18537. return false;
  18538. if (this._cache.pivotMatrixUpdated) {
  18539. return false;
  18540. }
  18541. if (this.infiniteDistance) {
  18542. return false;
  18543. }
  18544. if (!this._cache.position.equals(this.position))
  18545. return false;
  18546. if (this.rotationQuaternion) {
  18547. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  18548. return false;
  18549. }
  18550. if (!this._cache.rotation.equals(this.rotation))
  18551. return false;
  18552. if (!this._cache.scaling.equals(this.scaling))
  18553. return false;
  18554. return true;
  18555. };
  18556. TransformNode.prototype._initCache = function () {
  18557. _super.prototype._initCache.call(this);
  18558. this._cache.localMatrixUpdated = false;
  18559. this._cache.position = BABYLON.Vector3.Zero();
  18560. this._cache.scaling = BABYLON.Vector3.Zero();
  18561. this._cache.rotation = BABYLON.Vector3.Zero();
  18562. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  18563. this._cache.billboardMode = -1;
  18564. };
  18565. TransformNode.prototype.markAsDirty = function (property) {
  18566. if (property === "rotation") {
  18567. this.rotationQuaternion = null;
  18568. }
  18569. this._currentRenderId = Number.MAX_VALUE;
  18570. this._isDirty = true;
  18571. return this;
  18572. };
  18573. Object.defineProperty(TransformNode.prototype, "absolutePosition", {
  18574. /**
  18575. * Returns the current mesh absolute position.
  18576. * Retuns a Vector3.
  18577. */
  18578. get: function () {
  18579. return this._absolutePosition;
  18580. },
  18581. enumerable: true,
  18582. configurable: true
  18583. });
  18584. /**
  18585. * Sets a new matrix to apply before all other transformation
  18586. * @param matrix defines the transform matrix
  18587. * @returns the current TransformNode
  18588. */
  18589. TransformNode.prototype.setPreTransformMatrix = function (matrix) {
  18590. return this.setPivotMatrix(matrix, false);
  18591. };
  18592. /**
  18593. * Sets a new pivot matrix to the current node
  18594. * @param matrix defines the new pivot matrix to use
  18595. * @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
  18596. * @returns the current TransformNode
  18597. */
  18598. TransformNode.prototype.setPivotMatrix = function (matrix, postMultiplyPivotMatrix) {
  18599. if (postMultiplyPivotMatrix === void 0) { postMultiplyPivotMatrix = true; }
  18600. this._pivotMatrix = matrix.clone();
  18601. this._cache.pivotMatrixUpdated = true;
  18602. this._postMultiplyPivotMatrix = postMultiplyPivotMatrix;
  18603. if (this._postMultiplyPivotMatrix) {
  18604. if (!this._pivotMatrixInverse) {
  18605. this._pivotMatrixInverse = BABYLON.Matrix.Invert(this._pivotMatrix);
  18606. }
  18607. else {
  18608. this._pivotMatrix.invertToRef(this._pivotMatrixInverse);
  18609. }
  18610. }
  18611. return this;
  18612. };
  18613. /**
  18614. * Returns the mesh pivot matrix.
  18615. * Default : Identity.
  18616. * A Matrix is returned.
  18617. */
  18618. TransformNode.prototype.getPivotMatrix = function () {
  18619. return this._pivotMatrix;
  18620. };
  18621. /**
  18622. * Prevents the World matrix to be computed any longer.
  18623. * Returns the TransformNode.
  18624. */
  18625. TransformNode.prototype.freezeWorldMatrix = function () {
  18626. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  18627. this.computeWorldMatrix(true);
  18628. this._isWorldMatrixFrozen = true;
  18629. return this;
  18630. };
  18631. /**
  18632. * Allows back the World matrix computation.
  18633. * Returns the TransformNode.
  18634. */
  18635. TransformNode.prototype.unfreezeWorldMatrix = function () {
  18636. this._isWorldMatrixFrozen = false;
  18637. this.computeWorldMatrix(true);
  18638. return this;
  18639. };
  18640. Object.defineProperty(TransformNode.prototype, "isWorldMatrixFrozen", {
  18641. /**
  18642. * True if the World matrix has been frozen.
  18643. * Returns a boolean.
  18644. */
  18645. get: function () {
  18646. return this._isWorldMatrixFrozen;
  18647. },
  18648. enumerable: true,
  18649. configurable: true
  18650. });
  18651. /**
  18652. * Retuns the mesh absolute position in the World.
  18653. * Returns a Vector3.
  18654. */
  18655. TransformNode.prototype.getAbsolutePosition = function () {
  18656. this.computeWorldMatrix();
  18657. return this._absolutePosition;
  18658. };
  18659. /**
  18660. * Sets the mesh absolute position in the World from a Vector3 or an Array(3).
  18661. * Returns the TransformNode.
  18662. */
  18663. TransformNode.prototype.setAbsolutePosition = function (absolutePosition) {
  18664. if (!absolutePosition) {
  18665. return this;
  18666. }
  18667. var absolutePositionX;
  18668. var absolutePositionY;
  18669. var absolutePositionZ;
  18670. if (absolutePosition.x === undefined) {
  18671. if (arguments.length < 3) {
  18672. return this;
  18673. }
  18674. absolutePositionX = arguments[0];
  18675. absolutePositionY = arguments[1];
  18676. absolutePositionZ = arguments[2];
  18677. }
  18678. else {
  18679. absolutePositionX = absolutePosition.x;
  18680. absolutePositionY = absolutePosition.y;
  18681. absolutePositionZ = absolutePosition.z;
  18682. }
  18683. if (this.parent) {
  18684. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  18685. invertParentWorldMatrix.invert();
  18686. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  18687. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  18688. }
  18689. else {
  18690. this.position.x = absolutePositionX;
  18691. this.position.y = absolutePositionY;
  18692. this.position.z = absolutePositionZ;
  18693. }
  18694. return this;
  18695. };
  18696. /**
  18697. * Sets the mesh position in its local space.
  18698. * Returns the TransformNode.
  18699. */
  18700. TransformNode.prototype.setPositionWithLocalVector = function (vector3) {
  18701. this.computeWorldMatrix();
  18702. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  18703. return this;
  18704. };
  18705. /**
  18706. * Returns the mesh position in the local space from the current World matrix values.
  18707. * Returns a new Vector3.
  18708. */
  18709. TransformNode.prototype.getPositionExpressedInLocalSpace = function () {
  18710. this.computeWorldMatrix();
  18711. var invLocalWorldMatrix = this._localWorld.clone();
  18712. invLocalWorldMatrix.invert();
  18713. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  18714. };
  18715. /**
  18716. * Translates the mesh along the passed Vector3 in its local space.
  18717. * Returns the TransformNode.
  18718. */
  18719. TransformNode.prototype.locallyTranslate = function (vector3) {
  18720. this.computeWorldMatrix(true);
  18721. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  18722. return this;
  18723. };
  18724. /**
  18725. * Orients a mesh towards a target point. Mesh must be drawn facing user.
  18726. * @param targetPoint the position (must be in same space as current mesh) to look at
  18727. * @param yawCor optional yaw (y-axis) correction in radians
  18728. * @param pitchCor optional pitch (x-axis) correction in radians
  18729. * @param rollCor optional roll (z-axis) correction in radians
  18730. * @param space the choosen space of the target
  18731. * @returns the TransformNode.
  18732. */
  18733. TransformNode.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor, space) {
  18734. if (yawCor === void 0) { yawCor = 0; }
  18735. if (pitchCor === void 0) { pitchCor = 0; }
  18736. if (rollCor === void 0) { rollCor = 0; }
  18737. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  18738. var dv = TransformNode._lookAtVectorCache;
  18739. var pos = space === BABYLON.Space.LOCAL ? this.position : this.getAbsolutePosition();
  18740. targetPoint.subtractToRef(pos, dv);
  18741. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  18742. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  18743. var pitch = Math.atan2(dv.y, len);
  18744. if (this.rotationQuaternion) {
  18745. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw + yawCor, pitch + pitchCor, rollCor, this.rotationQuaternion);
  18746. }
  18747. else {
  18748. this.rotation.x = pitch + pitchCor;
  18749. this.rotation.y = yaw + yawCor;
  18750. this.rotation.z = rollCor;
  18751. }
  18752. return this;
  18753. };
  18754. /**
  18755. * Returns a new Vector3 what is the localAxis, expressed in the mesh local space, rotated like the mesh.
  18756. * This Vector3 is expressed in the World space.
  18757. */
  18758. TransformNode.prototype.getDirection = function (localAxis) {
  18759. var result = BABYLON.Vector3.Zero();
  18760. this.getDirectionToRef(localAxis, result);
  18761. return result;
  18762. };
  18763. /**
  18764. * Sets the Vector3 "result" as the rotated Vector3 "localAxis" in the same rotation than the mesh.
  18765. * localAxis is expressed in the mesh local space.
  18766. * result is computed in the Wordl space from the mesh World matrix.
  18767. * Returns the TransformNode.
  18768. */
  18769. TransformNode.prototype.getDirectionToRef = function (localAxis, result) {
  18770. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  18771. return this;
  18772. };
  18773. /**
  18774. * Sets a new pivot point to the current node
  18775. * @param point defines the new pivot point to use
  18776. * @param space defines if the point is in world or local space (local by default)
  18777. * @returns the current TransformNode
  18778. */
  18779. TransformNode.prototype.setPivotPoint = function (point, space) {
  18780. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  18781. if (this.getScene().getRenderId() == 0) {
  18782. this.computeWorldMatrix(true);
  18783. }
  18784. var wm = this.getWorldMatrix();
  18785. if (space == BABYLON.Space.WORLD) {
  18786. var tmat = BABYLON.Tmp.Matrix[0];
  18787. wm.invertToRef(tmat);
  18788. point = BABYLON.Vector3.TransformCoordinates(point, tmat);
  18789. }
  18790. return this.setPivotMatrix(BABYLON.Matrix.Translation(-point.x, -point.y, -point.z), true);
  18791. };
  18792. /**
  18793. * Returns a new Vector3 set with the mesh pivot point coordinates in the local space.
  18794. */
  18795. TransformNode.prototype.getPivotPoint = function () {
  18796. var point = BABYLON.Vector3.Zero();
  18797. this.getPivotPointToRef(point);
  18798. return point;
  18799. };
  18800. /**
  18801. * Sets the passed Vector3 "result" with the coordinates of the mesh pivot point in the local space.
  18802. * Returns the TransformNode.
  18803. */
  18804. TransformNode.prototype.getPivotPointToRef = function (result) {
  18805. result.x = -this._pivotMatrix.m[12];
  18806. result.y = -this._pivotMatrix.m[13];
  18807. result.z = -this._pivotMatrix.m[14];
  18808. return this;
  18809. };
  18810. /**
  18811. * Returns a new Vector3 set with the mesh pivot point World coordinates.
  18812. */
  18813. TransformNode.prototype.getAbsolutePivotPoint = function () {
  18814. var point = BABYLON.Vector3.Zero();
  18815. this.getAbsolutePivotPointToRef(point);
  18816. return point;
  18817. };
  18818. /**
  18819. * Sets the Vector3 "result" coordinates with the mesh pivot point World coordinates.
  18820. * Returns the TransformNode.
  18821. */
  18822. TransformNode.prototype.getAbsolutePivotPointToRef = function (result) {
  18823. result.x = this._pivotMatrix.m[12];
  18824. result.y = this._pivotMatrix.m[13];
  18825. result.z = this._pivotMatrix.m[14];
  18826. this.getPivotPointToRef(result);
  18827. BABYLON.Vector3.TransformCoordinatesToRef(result, this.getWorldMatrix(), result);
  18828. return this;
  18829. };
  18830. /**
  18831. * Defines the passed node as the parent of the current node.
  18832. * The node will remain exactly where it is and its position / rotation will be updated accordingly
  18833. * Returns the TransformNode.
  18834. */
  18835. TransformNode.prototype.setParent = function (node) {
  18836. if (node === null) {
  18837. var rotation = BABYLON.Tmp.Quaternion[0];
  18838. var position = BABYLON.Tmp.Vector3[0];
  18839. var scale = BABYLON.Tmp.Vector3[1];
  18840. if (this.parent && this.parent.computeWorldMatrix) {
  18841. this.parent.computeWorldMatrix(true);
  18842. }
  18843. this.computeWorldMatrix(true);
  18844. this.getWorldMatrix().decompose(scale, rotation, position);
  18845. if (this.rotationQuaternion) {
  18846. this.rotationQuaternion.copyFrom(rotation);
  18847. }
  18848. else {
  18849. rotation.toEulerAnglesToRef(this.rotation);
  18850. }
  18851. this.scaling.x = scale.x;
  18852. this.scaling.y = scale.y;
  18853. this.scaling.z = scale.z;
  18854. this.position.x = position.x;
  18855. this.position.y = position.y;
  18856. this.position.z = position.z;
  18857. }
  18858. else {
  18859. var rotation = BABYLON.Tmp.Quaternion[0];
  18860. var position = BABYLON.Tmp.Vector3[0];
  18861. var scale = BABYLON.Tmp.Vector3[1];
  18862. var diffMatrix = BABYLON.Tmp.Matrix[0];
  18863. var invParentMatrix = BABYLON.Tmp.Matrix[1];
  18864. this.computeWorldMatrix(true);
  18865. node.computeWorldMatrix(true);
  18866. node.getWorldMatrix().invertToRef(invParentMatrix);
  18867. this.getWorldMatrix().multiplyToRef(invParentMatrix, diffMatrix);
  18868. diffMatrix.decompose(scale, rotation, position);
  18869. if (this.rotationQuaternion) {
  18870. this.rotationQuaternion.copyFrom(rotation);
  18871. }
  18872. else {
  18873. rotation.toEulerAnglesToRef(this.rotation);
  18874. }
  18875. this.position.x = position.x;
  18876. this.position.y = position.y;
  18877. this.position.z = position.z;
  18878. this.scaling.x = scale.x;
  18879. this.scaling.y = scale.y;
  18880. this.scaling.z = scale.z;
  18881. }
  18882. this.parent = node;
  18883. return this;
  18884. };
  18885. Object.defineProperty(TransformNode.prototype, "nonUniformScaling", {
  18886. get: function () {
  18887. return this._nonUniformScaling;
  18888. },
  18889. enumerable: true,
  18890. configurable: true
  18891. });
  18892. TransformNode.prototype._updateNonUniformScalingState = function (value) {
  18893. if (this._nonUniformScaling === value) {
  18894. return false;
  18895. }
  18896. this._nonUniformScaling = true;
  18897. return true;
  18898. };
  18899. /**
  18900. * Attach the current TransformNode to another TransformNode associated with a bone
  18901. * @param bone Bone affecting the TransformNode
  18902. * @param affectedTransformNode TransformNode associated with the bone
  18903. */
  18904. TransformNode.prototype.attachToBone = function (bone, affectedTransformNode) {
  18905. this._transformToBoneReferal = affectedTransformNode;
  18906. this.parent = bone;
  18907. if (bone.getWorldMatrix().determinant() < 0) {
  18908. this.scalingDeterminant *= -1;
  18909. }
  18910. return this;
  18911. };
  18912. TransformNode.prototype.detachFromBone = function () {
  18913. if (!this.parent) {
  18914. return this;
  18915. }
  18916. if (this.parent.getWorldMatrix().determinant() < 0) {
  18917. this.scalingDeterminant *= -1;
  18918. }
  18919. this._transformToBoneReferal = null;
  18920. this.parent = null;
  18921. return this;
  18922. };
  18923. /**
  18924. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in the given space.
  18925. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  18926. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  18927. * The passed axis is also normalized.
  18928. * Returns the TransformNode.
  18929. */
  18930. TransformNode.prototype.rotate = function (axis, amount, space) {
  18931. axis.normalize();
  18932. if (!this.rotationQuaternion) {
  18933. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  18934. this.rotation = BABYLON.Vector3.Zero();
  18935. }
  18936. var rotationQuaternion;
  18937. if (!space || space === BABYLON.Space.LOCAL) {
  18938. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, TransformNode._rotationAxisCache);
  18939. this.rotationQuaternion.multiplyToRef(rotationQuaternion, this.rotationQuaternion);
  18940. }
  18941. else {
  18942. if (this.parent) {
  18943. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  18944. invertParentWorldMatrix.invert();
  18945. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  18946. }
  18947. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, TransformNode._rotationAxisCache);
  18948. rotationQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  18949. }
  18950. return this;
  18951. };
  18952. /**
  18953. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in world space.
  18954. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  18955. * The passed axis is also normalized.
  18956. * Returns the TransformNode.
  18957. * Method is based on http://www.euclideanspace.com/maths/geometry/affine/aroundPoint/index.htm
  18958. */
  18959. TransformNode.prototype.rotateAround = function (point, axis, amount) {
  18960. axis.normalize();
  18961. if (!this.rotationQuaternion) {
  18962. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  18963. this.rotation.copyFromFloats(0, 0, 0);
  18964. }
  18965. point.subtractToRef(this.position, BABYLON.Tmp.Vector3[0]);
  18966. BABYLON.Matrix.TranslationToRef(BABYLON.Tmp.Vector3[0].x, BABYLON.Tmp.Vector3[0].y, BABYLON.Tmp.Vector3[0].z, BABYLON.Tmp.Matrix[0]);
  18967. BABYLON.Tmp.Matrix[0].invertToRef(BABYLON.Tmp.Matrix[2]);
  18968. BABYLON.Matrix.RotationAxisToRef(axis, amount, BABYLON.Tmp.Matrix[1]);
  18969. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[2]);
  18970. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[2]);
  18971. BABYLON.Tmp.Matrix[2].decompose(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Quaternion[0], BABYLON.Tmp.Vector3[1]);
  18972. this.position.addInPlace(BABYLON.Tmp.Vector3[1]);
  18973. BABYLON.Tmp.Quaternion[0].multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  18974. return this;
  18975. };
  18976. /**
  18977. * Translates the mesh along the axis vector for the passed distance in the given space.
  18978. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  18979. * Returns the TransformNode.
  18980. */
  18981. TransformNode.prototype.translate = function (axis, distance, space) {
  18982. var displacementVector = axis.scale(distance);
  18983. if (!space || space === BABYLON.Space.LOCAL) {
  18984. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  18985. this.setPositionWithLocalVector(tempV3);
  18986. }
  18987. else {
  18988. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  18989. }
  18990. return this;
  18991. };
  18992. /**
  18993. * Adds a rotation step to the mesh current rotation.
  18994. * x, y, z are Euler angles expressed in radians.
  18995. * This methods updates the current mesh rotation, either mesh.rotation, either mesh.rotationQuaternion if it's set.
  18996. * This means this rotation is made in the mesh local space only.
  18997. * It's useful to set a custom rotation order different from the BJS standard one YXZ.
  18998. * Example : this rotates the mesh first around its local X axis, then around its local Z axis, finally around its local Y axis.
  18999. * ```javascript
  19000. * mesh.addRotation(x1, 0, 0).addRotation(0, 0, z2).addRotation(0, 0, y3);
  19001. * ```
  19002. * Note that `addRotation()` accumulates the passed rotation values to the current ones and computes the .rotation or .rotationQuaternion updated values.
  19003. * 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.
  19004. * Returns the TransformNode.
  19005. */
  19006. TransformNode.prototype.addRotation = function (x, y, z) {
  19007. var rotationQuaternion;
  19008. if (this.rotationQuaternion) {
  19009. rotationQuaternion = this.rotationQuaternion;
  19010. }
  19011. else {
  19012. rotationQuaternion = BABYLON.Tmp.Quaternion[1];
  19013. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, rotationQuaternion);
  19014. }
  19015. var accumulation = BABYLON.Tmp.Quaternion[0];
  19016. BABYLON.Quaternion.RotationYawPitchRollToRef(y, x, z, accumulation);
  19017. rotationQuaternion.multiplyInPlace(accumulation);
  19018. if (!this.rotationQuaternion) {
  19019. rotationQuaternion.toEulerAnglesToRef(this.rotation);
  19020. }
  19021. return this;
  19022. };
  19023. /**
  19024. * Computes the mesh World matrix and returns it.
  19025. * If the mesh world matrix is frozen, this computation does nothing more than returning the last frozen values.
  19026. * If the parameter `force` is let to `false` (default), the current cached World matrix is returned.
  19027. * If the parameter `force`is set to `true`, the actual computation is done.
  19028. * Returns the mesh World Matrix.
  19029. */
  19030. TransformNode.prototype.computeWorldMatrix = function (force) {
  19031. if (this._isWorldMatrixFrozen) {
  19032. return this._worldMatrix;
  19033. }
  19034. if (!force && this.isSynchronized(true)) {
  19035. this._currentRenderId = this.getScene().getRenderId();
  19036. return this._worldMatrix;
  19037. }
  19038. this._cache.position.copyFrom(this.position);
  19039. this._cache.scaling.copyFrom(this.scaling);
  19040. this._cache.pivotMatrixUpdated = false;
  19041. this._cache.billboardMode = this.billboardMode;
  19042. this._currentRenderId = this.getScene().getRenderId();
  19043. this._childRenderId = this.getScene().getRenderId();
  19044. this._isDirty = false;
  19045. // Scaling
  19046. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, BABYLON.Tmp.Matrix[1]);
  19047. // Rotation
  19048. //rotate, if quaternion is set and rotation was used
  19049. if (this.rotationQuaternion) {
  19050. var len = this.rotation.length();
  19051. if (len) {
  19052. this.rotationQuaternion.multiplyInPlace(BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z));
  19053. this.rotation.copyFromFloats(0, 0, 0);
  19054. }
  19055. }
  19056. if (this.rotationQuaternion) {
  19057. this.rotationQuaternion.toRotationMatrix(BABYLON.Tmp.Matrix[0]);
  19058. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  19059. }
  19060. else {
  19061. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, BABYLON.Tmp.Matrix[0]);
  19062. this._cache.rotation.copyFrom(this.rotation);
  19063. }
  19064. // Translation
  19065. var camera = this.getScene().activeCamera;
  19066. if (this.infiniteDistance && !this.parent && camera) {
  19067. var cameraWorldMatrix = camera.getWorldMatrix();
  19068. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  19069. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, BABYLON.Tmp.Matrix[2]);
  19070. }
  19071. else {
  19072. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, BABYLON.Tmp.Matrix[2]);
  19073. }
  19074. // Composing transformations
  19075. this._pivotMatrix.multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[4]);
  19076. BABYLON.Tmp.Matrix[4].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  19077. // Billboarding (testing PG:http://www.babylonjs-playground.com/#UJEIL#13)
  19078. if (this.billboardMode !== TransformNode.BILLBOARDMODE_NONE && camera) {
  19079. if ((this.billboardMode & TransformNode.BILLBOARDMODE_ALL) !== TransformNode.BILLBOARDMODE_ALL) {
  19080. // Need to decompose each rotation here
  19081. var currentPosition = BABYLON.Tmp.Vector3[3];
  19082. if (this.parent && this.parent.getWorldMatrix) {
  19083. if (this._transformToBoneReferal) {
  19084. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  19085. BABYLON.Vector3.TransformCoordinatesToRef(this.position, BABYLON.Tmp.Matrix[6], currentPosition);
  19086. }
  19087. else {
  19088. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), currentPosition);
  19089. }
  19090. }
  19091. else {
  19092. currentPosition.copyFrom(this.position);
  19093. }
  19094. currentPosition.subtractInPlace(camera.globalPosition);
  19095. var finalEuler = BABYLON.Tmp.Vector3[4].copyFromFloats(0, 0, 0);
  19096. if ((this.billboardMode & TransformNode.BILLBOARDMODE_X) === TransformNode.BILLBOARDMODE_X) {
  19097. finalEuler.x = Math.atan2(-currentPosition.y, currentPosition.z);
  19098. }
  19099. if ((this.billboardMode & TransformNode.BILLBOARDMODE_Y) === TransformNode.BILLBOARDMODE_Y) {
  19100. finalEuler.y = Math.atan2(currentPosition.x, currentPosition.z);
  19101. }
  19102. if ((this.billboardMode & TransformNode.BILLBOARDMODE_Z) === TransformNode.BILLBOARDMODE_Z) {
  19103. finalEuler.z = Math.atan2(currentPosition.y, currentPosition.x);
  19104. }
  19105. BABYLON.Matrix.RotationYawPitchRollToRef(finalEuler.y, finalEuler.x, finalEuler.z, BABYLON.Tmp.Matrix[0]);
  19106. }
  19107. else {
  19108. BABYLON.Tmp.Matrix[1].copyFrom(camera.getViewMatrix());
  19109. BABYLON.Tmp.Matrix[1].setTranslationFromFloats(0, 0, 0);
  19110. BABYLON.Tmp.Matrix[1].invertToRef(BABYLON.Tmp.Matrix[0]);
  19111. }
  19112. BABYLON.Tmp.Matrix[1].copyFrom(BABYLON.Tmp.Matrix[5]);
  19113. BABYLON.Tmp.Matrix[1].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  19114. }
  19115. // Local world
  19116. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[2], this._localWorld);
  19117. // Parent
  19118. if (this.parent && this.parent.getWorldMatrix) {
  19119. if (this.billboardMode !== TransformNode.BILLBOARDMODE_NONE) {
  19120. if (this._transformToBoneReferal) {
  19121. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  19122. BABYLON.Tmp.Matrix[5].copyFrom(BABYLON.Tmp.Matrix[6]);
  19123. }
  19124. else {
  19125. BABYLON.Tmp.Matrix[5].copyFrom(this.parent.getWorldMatrix());
  19126. }
  19127. this._localWorld.getTranslationToRef(BABYLON.Tmp.Vector3[5]);
  19128. BABYLON.Vector3.TransformCoordinatesToRef(BABYLON.Tmp.Vector3[5], BABYLON.Tmp.Matrix[5], BABYLON.Tmp.Vector3[5]);
  19129. this._worldMatrix.copyFrom(this._localWorld);
  19130. this._worldMatrix.setTranslation(BABYLON.Tmp.Vector3[5]);
  19131. }
  19132. else {
  19133. if (this._transformToBoneReferal) {
  19134. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  19135. BABYLON.Tmp.Matrix[6].multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), this._worldMatrix);
  19136. }
  19137. else {
  19138. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  19139. }
  19140. }
  19141. this._markSyncedWithParent();
  19142. }
  19143. else {
  19144. this._worldMatrix.copyFrom(this._localWorld);
  19145. }
  19146. // Post multiply inverse of pivotMatrix
  19147. if (this._postMultiplyPivotMatrix) {
  19148. this._worldMatrix.multiplyToRef(this._pivotMatrixInverse, this._worldMatrix);
  19149. }
  19150. // Normal matrix
  19151. if (this.scaling.isNonUniform) {
  19152. this._updateNonUniformScalingState(true);
  19153. }
  19154. else if (this.parent && this.parent._nonUniformScaling) {
  19155. this._updateNonUniformScalingState(this.parent._nonUniformScaling);
  19156. }
  19157. else {
  19158. this._updateNonUniformScalingState(false);
  19159. }
  19160. this._afterComputeWorldMatrix();
  19161. // Absolute position
  19162. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  19163. // Callbacks
  19164. this.onAfterWorldMatrixUpdateObservable.notifyObservers(this);
  19165. if (!this._poseMatrix) {
  19166. this._poseMatrix = BABYLON.Matrix.Invert(this._worldMatrix);
  19167. }
  19168. // Cache the determinant
  19169. this._worldMatrixDeterminant = this._worldMatrix.determinant();
  19170. return this._worldMatrix;
  19171. };
  19172. TransformNode.prototype._afterComputeWorldMatrix = function () {
  19173. };
  19174. /**
  19175. * If you'd like to be called back after the mesh position, rotation or scaling has been updated.
  19176. * @param func: callback function to add
  19177. *
  19178. * Returns the TransformNode.
  19179. */
  19180. TransformNode.prototype.registerAfterWorldMatrixUpdate = function (func) {
  19181. this.onAfterWorldMatrixUpdateObservable.add(func);
  19182. return this;
  19183. };
  19184. /**
  19185. * Removes a registered callback function.
  19186. * Returns the TransformNode.
  19187. */
  19188. TransformNode.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  19189. this.onAfterWorldMatrixUpdateObservable.removeCallback(func);
  19190. return this;
  19191. };
  19192. /**
  19193. * Clone the current transform node
  19194. * Returns the new transform node
  19195. * @param name Name of the new clone
  19196. * @param newParent New parent for the clone
  19197. * @param doNotCloneChildren Do not clone children hierarchy
  19198. */
  19199. TransformNode.prototype.clone = function (name, newParent, doNotCloneChildren) {
  19200. var _this = this;
  19201. var result = BABYLON.SerializationHelper.Clone(function () { return new TransformNode(name, _this.getScene()); }, this);
  19202. result.name = name;
  19203. result.id = name;
  19204. if (newParent) {
  19205. result.parent = newParent;
  19206. }
  19207. if (!doNotCloneChildren) {
  19208. // Children
  19209. var directDescendants = this.getDescendants(true);
  19210. for (var index = 0; index < directDescendants.length; index++) {
  19211. var child = directDescendants[index];
  19212. if (child.clone) {
  19213. child.clone(name + "." + child.name, result);
  19214. }
  19215. }
  19216. }
  19217. return result;
  19218. };
  19219. TransformNode.prototype.serialize = function (currentSerializationObject) {
  19220. var serializationObject = BABYLON.SerializationHelper.Serialize(this, currentSerializationObject);
  19221. serializationObject.type = this.getClassName();
  19222. // Parent
  19223. if (this.parent) {
  19224. serializationObject.parentId = this.parent.id;
  19225. }
  19226. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  19227. serializationObject.tags = BABYLON.Tags.GetTags(this);
  19228. }
  19229. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  19230. serializationObject.isEnabled = this.isEnabled();
  19231. // Parent
  19232. if (this.parent) {
  19233. serializationObject.parentId = this.parent.id;
  19234. }
  19235. return serializationObject;
  19236. };
  19237. // Statics
  19238. /**
  19239. * Returns a new TransformNode object parsed from the source provided.
  19240. * The parameter `parsedMesh` is the source.
  19241. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  19242. */
  19243. TransformNode.Parse = function (parsedTransformNode, scene, rootUrl) {
  19244. var transformNode = BABYLON.SerializationHelper.Parse(function () { return new TransformNode(parsedTransformNode.name, scene); }, parsedTransformNode, scene, rootUrl);
  19245. if (BABYLON.Tags) {
  19246. BABYLON.Tags.AddTagsTo(transformNode, parsedTransformNode.tags);
  19247. }
  19248. if (parsedTransformNode.localMatrix) {
  19249. transformNode.setPreTransformMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.localMatrix));
  19250. }
  19251. else if (parsedTransformNode.pivotMatrix) {
  19252. transformNode.setPivotMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.pivotMatrix));
  19253. }
  19254. transformNode.setEnabled(parsedTransformNode.isEnabled);
  19255. // Parent
  19256. if (parsedTransformNode.parentId) {
  19257. transformNode._waitingParentId = parsedTransformNode.parentId;
  19258. }
  19259. return transformNode;
  19260. };
  19261. /**
  19262. * Releases resources associated with this transform node.
  19263. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  19264. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  19265. */
  19266. TransformNode.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  19267. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  19268. // Animations
  19269. this.getScene().stopAnimation(this);
  19270. // Remove from scene
  19271. this.getScene().removeTransformNode(this);
  19272. this.onAfterWorldMatrixUpdateObservable.clear();
  19273. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  19274. };
  19275. // Statics
  19276. TransformNode.BILLBOARDMODE_NONE = 0;
  19277. TransformNode.BILLBOARDMODE_X = 1;
  19278. TransformNode.BILLBOARDMODE_Y = 2;
  19279. TransformNode.BILLBOARDMODE_Z = 4;
  19280. TransformNode.BILLBOARDMODE_ALL = 7;
  19281. TransformNode._lookAtVectorCache = new BABYLON.Vector3(0, 0, 0);
  19282. TransformNode._rotationAxisCache = new BABYLON.Quaternion();
  19283. __decorate([
  19284. BABYLON.serializeAsVector3()
  19285. ], TransformNode.prototype, "_rotation", void 0);
  19286. __decorate([
  19287. BABYLON.serializeAsQuaternion()
  19288. ], TransformNode.prototype, "_rotationQuaternion", void 0);
  19289. __decorate([
  19290. BABYLON.serializeAsVector3()
  19291. ], TransformNode.prototype, "_scaling", void 0);
  19292. __decorate([
  19293. BABYLON.serialize()
  19294. ], TransformNode.prototype, "billboardMode", void 0);
  19295. __decorate([
  19296. BABYLON.serialize()
  19297. ], TransformNode.prototype, "scalingDeterminant", void 0);
  19298. __decorate([
  19299. BABYLON.serialize()
  19300. ], TransformNode.prototype, "infiniteDistance", void 0);
  19301. __decorate([
  19302. BABYLON.serializeAsVector3()
  19303. ], TransformNode.prototype, "position", void 0);
  19304. return TransformNode;
  19305. }(BABYLON.Node));
  19306. BABYLON.TransformNode = TransformNode;
  19307. })(BABYLON || (BABYLON = {}));
  19308. //# sourceMappingURL=babylon.transformNode.js.map
  19309. var BABYLON;
  19310. (function (BABYLON) {
  19311. /**
  19312. * Class used to store all common mesh properties
  19313. */
  19314. var AbstractMesh = /** @class */ (function (_super) {
  19315. __extends(AbstractMesh, _super);
  19316. // Constructor
  19317. /**
  19318. * Creates a new AbstractMesh
  19319. * @param name defines the name of the mesh
  19320. * @param scene defines the hosting scene
  19321. */
  19322. function AbstractMesh(name, scene) {
  19323. if (scene === void 0) { scene = null; }
  19324. var _this = _super.call(this, name, scene, false) || this;
  19325. _this._facetNb = 0; // facet number
  19326. _this._partitioningSubdivisions = 10; // number of subdivisions per axis in the partioning space
  19327. _this._partitioningBBoxRatio = 1.01; // the partioning array space is by default 1% bigger than the bounding box
  19328. _this._facetDataEnabled = false; // is the facet data feature enabled on this mesh ?
  19329. _this._facetParameters = {}; // keep a reference to the object parameters to avoid memory re-allocation
  19330. _this._bbSize = BABYLON.Vector3.Zero(); // bbox size approximated for facet data
  19331. _this._subDiv = {
  19332. max: 1,
  19333. X: 1,
  19334. Y: 1,
  19335. Z: 1
  19336. };
  19337. _this._facetDepthSort = false; // is the facet depth sort to be computed
  19338. _this._facetDepthSortEnabled = false; // is the facet depth sort initialized
  19339. // Events
  19340. /**
  19341. * An event triggered when this mesh collides with another one
  19342. */
  19343. _this.onCollideObservable = new BABYLON.Observable();
  19344. /**
  19345. * An event triggered when the collision's position changes
  19346. */
  19347. _this.onCollisionPositionChangeObservable = new BABYLON.Observable();
  19348. /**
  19349. * An event triggered when material is changed
  19350. */
  19351. _this.onMaterialChangedObservable = new BABYLON.Observable();
  19352. // Properties
  19353. /**
  19354. * Gets or sets the orientation for POV movement & rotation
  19355. */
  19356. _this.definedFacingForward = true;
  19357. /**
  19358. * This property determines the type of occlusion query algorithm to run in WebGl, you can use:
  19359. * * AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE which is mapped to GL_ANY_SAMPLES_PASSED.
  19360. * * AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE (Default Value) which is mapped to GL_ANY_SAMPLES_PASSED_CONSERVATIVE which is a false positive algorithm that is faster than GL_ANY_SAMPLES_PASSED but less accurate.
  19361. * @see http://doc.babylonjs.com/features/occlusionquery
  19362. */
  19363. _this.occlusionQueryAlgorithmType = AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE;
  19364. /**
  19365. * This property is responsible for starting the occlusion query within the Mesh or not, this property is also used to determine what should happen when the occlusionRetryCount is reached. It has supports 3 values:
  19366. * * OCCLUSION_TYPE_NONE (Default Value): this option means no occlusion query whith the Mesh.
  19367. * * OCCLUSION_TYPE_OPTIMISTIC: this option is means use occlusion query and if occlusionRetryCount is reached and the query is broken show the mesh.
  19368. * * OCCLUSION_TYPE_STRICT: this option is means use occlusion query and if occlusionRetryCount is reached and the query is broken restore the last state of the mesh occlusion if the mesh was visible then show the mesh if was hidden then hide don't show.
  19369. * @see http://doc.babylonjs.com/features/occlusionquery
  19370. */
  19371. _this.occlusionType = AbstractMesh.OCCLUSION_TYPE_NONE;
  19372. /**
  19373. * This number indicates the number of allowed retries before stop the occlusion query, this is useful if the occlusion query is taking long time before to the query result is retireved, the query result indicates if the object is visible within the scene or not and based on that Babylon.Js engine decideds to show or hide the object.
  19374. * The default value is -1 which means don't break the query and wait till the result
  19375. * @see http://doc.babylonjs.com/features/occlusionquery
  19376. */
  19377. _this.occlusionRetryCount = -1;
  19378. _this._occlusionInternalRetryCounter = 0;
  19379. _this._isOccluded = false;
  19380. _this._isOcclusionQueryInProgress = false;
  19381. _this._visibility = 1.0;
  19382. /** Gets or sets the alpha index used to sort transparent meshes
  19383. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered#alpha-index
  19384. */
  19385. _this.alphaIndex = Number.MAX_VALUE;
  19386. /**
  19387. * Gets or sets a boolean indicating if the mesh is visible (renderable). Default is true
  19388. */
  19389. _this.isVisible = true;
  19390. /**
  19391. * Gets or sets a boolean indicating if the mesh can be picked (by scene.pick for instance or through actions). Default is true
  19392. */
  19393. _this.isPickable = true;
  19394. /**
  19395. * Gets or sets a boolean indicating if the bounding box must be rendered as well (false by default)
  19396. */
  19397. _this.showBoundingBox = false;
  19398. /** Gets or sets a boolean indicating that bounding boxes of subMeshes must be rendered as well (false by default) */
  19399. _this.showSubMeshesBoundingBox = false;
  19400. /** Gets or sets a boolean indicating if the mesh must be considered as a ray blocker for lens flares (false by default)
  19401. * @see http://doc.babylonjs.com/how_to/how_to_use_lens_flares
  19402. */
  19403. _this.isBlocker = false;
  19404. /**
  19405. * Gets or sets a boolean indicating that pointer move events must be supported on this mesh (false by default)
  19406. */
  19407. _this.enablePointerMoveEvents = false;
  19408. /**
  19409. * Specifies the rendering group id for this mesh (0 by default)
  19410. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered#rendering-groups
  19411. */
  19412. _this.renderingGroupId = 0;
  19413. _this._receiveShadows = false;
  19414. /**
  19415. * Gets or sets a boolean indicating if the outline must be rendered as well
  19416. * @see https://www.babylonjs-playground.com/#10WJ5S#3
  19417. */
  19418. _this.renderOutline = false;
  19419. /** Defines color to use when rendering outline */
  19420. _this.outlineColor = BABYLON.Color3.Red();
  19421. /** Define width to use when rendering outline */
  19422. _this.outlineWidth = 0.02;
  19423. /**
  19424. * Gets or sets a boolean indicating if the overlay must be rendered as well
  19425. * @see https://www.babylonjs-playground.com/#10WJ5S#2
  19426. */
  19427. _this.renderOverlay = false;
  19428. /** Defines color to use when rendering overlay */
  19429. _this.overlayColor = BABYLON.Color3.Red();
  19430. /** Defines alpha to use when rendering overlay */
  19431. _this.overlayAlpha = 0.5;
  19432. _this._hasVertexAlpha = false;
  19433. _this._useVertexColors = true;
  19434. _this._computeBonesUsingShaders = true;
  19435. _this._numBoneInfluencers = 4;
  19436. _this._applyFog = true;
  19437. /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes selection (true by default) */
  19438. _this.useOctreeForRenderingSelection = true;
  19439. /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes picking (true by default) */
  19440. _this.useOctreeForPicking = true;
  19441. /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes collision (true by default) */
  19442. _this.useOctreeForCollisions = true;
  19443. _this._layerMask = 0x0FFFFFFF;
  19444. /**
  19445. * True if the mesh must be rendered in any case (this will shortcut the frustum clipping phase)
  19446. */
  19447. _this.alwaysSelectAsActiveMesh = false;
  19448. /**
  19449. * Gets or sets the current action manager
  19450. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  19451. */
  19452. _this.actionManager = null;
  19453. /**
  19454. * Gets or sets impostor used for physic simulation
  19455. * @see http://doc.babylonjs.com/features/physics_engine
  19456. */
  19457. _this.physicsImpostor = null;
  19458. // Collisions
  19459. _this._checkCollisions = false;
  19460. _this._collisionMask = -1;
  19461. _this._collisionGroup = -1;
  19462. /**
  19463. * Gets or sets the ellipsoid used to impersonate this mesh when using collision engine (default is (0.5, 1, 0.5))
  19464. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  19465. */
  19466. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  19467. /**
  19468. * Gets or sets the ellipsoid offset used to impersonate this mesh when using collision engine (default is (0, 0, 0))
  19469. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  19470. */
  19471. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  19472. _this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  19473. _this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  19474. // Edges
  19475. /**
  19476. * Defines edge width used when edgesRenderer is enabled
  19477. * @see https://www.babylonjs-playground.com/#10OJSG#13
  19478. */
  19479. _this.edgesWidth = 1;
  19480. /**
  19481. * Defines edge color used when edgesRenderer is enabled
  19482. * @see https://www.babylonjs-playground.com/#10OJSG#13
  19483. */
  19484. _this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  19485. // Cache
  19486. _this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  19487. _this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  19488. /** @hidden */
  19489. _this._renderId = 0;
  19490. /** @hidden */
  19491. _this._intersectionsInProgress = new Array();
  19492. /** @hidden */
  19493. _this._unIndexed = false;
  19494. /** @hidden */
  19495. _this._lightSources = new Array();
  19496. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  19497. if (collidedMesh === void 0) { collidedMesh = null; }
  19498. //TODO move this to the collision coordinator!
  19499. if (_this.getScene().workerCollisions)
  19500. newPosition.multiplyInPlace(_this._collider._radius);
  19501. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  19502. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  19503. _this.position.addInPlace(_this._diffPositionForCollisions);
  19504. }
  19505. if (collidedMesh) {
  19506. _this.onCollideObservable.notifyObservers(collidedMesh);
  19507. }
  19508. _this.onCollisionPositionChangeObservable.notifyObservers(_this.position);
  19509. };
  19510. _this.getScene().addMesh(_this);
  19511. _this._resyncLightSources();
  19512. return _this;
  19513. }
  19514. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  19515. /**
  19516. * No billboard
  19517. */
  19518. get: function () {
  19519. return BABYLON.TransformNode.BILLBOARDMODE_NONE;
  19520. },
  19521. enumerable: true,
  19522. configurable: true
  19523. });
  19524. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  19525. /** Billboard on X axis */
  19526. get: function () {
  19527. return BABYLON.TransformNode.BILLBOARDMODE_X;
  19528. },
  19529. enumerable: true,
  19530. configurable: true
  19531. });
  19532. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  19533. /** Billboard on Y axis */
  19534. get: function () {
  19535. return BABYLON.TransformNode.BILLBOARDMODE_Y;
  19536. },
  19537. enumerable: true,
  19538. configurable: true
  19539. });
  19540. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  19541. /** Billboard on Z axis */
  19542. get: function () {
  19543. return BABYLON.TransformNode.BILLBOARDMODE_Z;
  19544. },
  19545. enumerable: true,
  19546. configurable: true
  19547. });
  19548. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  19549. /** Billboard on all axes */
  19550. get: function () {
  19551. return BABYLON.TransformNode.BILLBOARDMODE_ALL;
  19552. },
  19553. enumerable: true,
  19554. configurable: true
  19555. });
  19556. Object.defineProperty(AbstractMesh.prototype, "facetNb", {
  19557. /**
  19558. * Gets the number of facets in the mesh
  19559. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#what-is-a-mesh-facet
  19560. */
  19561. get: function () {
  19562. return this._facetNb;
  19563. },
  19564. enumerable: true,
  19565. configurable: true
  19566. });
  19567. Object.defineProperty(AbstractMesh.prototype, "partitioningSubdivisions", {
  19568. /**
  19569. * Gets or set the number (integer) of subdivisions per axis in the partioning space
  19570. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#tweaking-the-partitioning
  19571. */
  19572. get: function () {
  19573. return this._partitioningSubdivisions;
  19574. },
  19575. set: function (nb) {
  19576. this._partitioningSubdivisions = nb;
  19577. },
  19578. enumerable: true,
  19579. configurable: true
  19580. });
  19581. Object.defineProperty(AbstractMesh.prototype, "partitioningBBoxRatio", {
  19582. /**
  19583. * The ratio (float) to apply to the bouding box size to set to the partioning space.
  19584. * Ex : 1.01 (default) the partioning space is 1% bigger than the bounding box
  19585. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#tweaking-the-partitioning
  19586. */
  19587. get: function () {
  19588. return this._partitioningBBoxRatio;
  19589. },
  19590. set: function (ratio) {
  19591. this._partitioningBBoxRatio = ratio;
  19592. },
  19593. enumerable: true,
  19594. configurable: true
  19595. });
  19596. Object.defineProperty(AbstractMesh.prototype, "mustDepthSortFacets", {
  19597. /**
  19598. * Gets or sets a boolean indicating that the facets must be depth sorted on next call to `updateFacetData()`.
  19599. * Works only for updatable meshes.
  19600. * Doesn't work with multi-materials
  19601. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#facet-depth-sort
  19602. */
  19603. get: function () {
  19604. return this._facetDepthSort;
  19605. },
  19606. set: function (sort) {
  19607. this._facetDepthSort = sort;
  19608. },
  19609. enumerable: true,
  19610. configurable: true
  19611. });
  19612. Object.defineProperty(AbstractMesh.prototype, "facetDepthSortFrom", {
  19613. /**
  19614. * The location (Vector3) where the facet depth sort must be computed from.
  19615. * By default, the active camera position.
  19616. * Used only when facet depth sort is enabled
  19617. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#facet-depth-sort
  19618. */
  19619. get: function () {
  19620. return this._facetDepthSortFrom;
  19621. },
  19622. set: function (location) {
  19623. this._facetDepthSortFrom = location;
  19624. },
  19625. enumerable: true,
  19626. configurable: true
  19627. });
  19628. Object.defineProperty(AbstractMesh.prototype, "isFacetDataEnabled", {
  19629. /**
  19630. * gets a boolean indicating if facetData is enabled
  19631. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#what-is-a-mesh-facet
  19632. */
  19633. get: function () {
  19634. return this._facetDataEnabled;
  19635. },
  19636. enumerable: true,
  19637. configurable: true
  19638. });
  19639. /** @hidden */
  19640. AbstractMesh.prototype._updateNonUniformScalingState = function (value) {
  19641. if (!_super.prototype._updateNonUniformScalingState.call(this, value)) {
  19642. return false;
  19643. }
  19644. this._markSubMeshesAsMiscDirty();
  19645. return true;
  19646. };
  19647. Object.defineProperty(AbstractMesh.prototype, "onCollide", {
  19648. /** Set a function to call when this mesh collides with another one */
  19649. set: function (callback) {
  19650. if (this._onCollideObserver) {
  19651. this.onCollideObservable.remove(this._onCollideObserver);
  19652. }
  19653. this._onCollideObserver = this.onCollideObservable.add(callback);
  19654. },
  19655. enumerable: true,
  19656. configurable: true
  19657. });
  19658. Object.defineProperty(AbstractMesh.prototype, "onCollisionPositionChange", {
  19659. /** Set a function to call when the collision's position changes */
  19660. set: function (callback) {
  19661. if (this._onCollisionPositionChangeObserver) {
  19662. this.onCollisionPositionChangeObservable.remove(this._onCollisionPositionChangeObserver);
  19663. }
  19664. this._onCollisionPositionChangeObserver = this.onCollisionPositionChangeObservable.add(callback);
  19665. },
  19666. enumerable: true,
  19667. configurable: true
  19668. });
  19669. Object.defineProperty(AbstractMesh.prototype, "isOccluded", {
  19670. /**
  19671. * Gets or sets whether the mesh is occluded or not, it is used also to set the intial state of the mesh to be occluded or not
  19672. * @see http://doc.babylonjs.com/features/occlusionquery
  19673. */
  19674. get: function () {
  19675. return this._isOccluded;
  19676. },
  19677. set: function (value) {
  19678. this._isOccluded = value;
  19679. },
  19680. enumerable: true,
  19681. configurable: true
  19682. });
  19683. Object.defineProperty(AbstractMesh.prototype, "isOcclusionQueryInProgress", {
  19684. /**
  19685. * Flag to check the progress status of the query
  19686. * @see http://doc.babylonjs.com/features/occlusionquery
  19687. */
  19688. get: function () {
  19689. return this._isOcclusionQueryInProgress;
  19690. },
  19691. enumerable: true,
  19692. configurable: true
  19693. });
  19694. Object.defineProperty(AbstractMesh.prototype, "visibility", {
  19695. /**
  19696. * Gets or sets mesh visibility between 0 and 1 (default is 1)
  19697. */
  19698. get: function () {
  19699. return this._visibility;
  19700. },
  19701. /**
  19702. * Gets or sets mesh visibility between 0 and 1 (default is 1)
  19703. */
  19704. set: function (value) {
  19705. if (this._visibility === value) {
  19706. return;
  19707. }
  19708. this._visibility = value;
  19709. this._markSubMeshesAsMiscDirty();
  19710. },
  19711. enumerable: true,
  19712. configurable: true
  19713. });
  19714. Object.defineProperty(AbstractMesh.prototype, "material", {
  19715. /** Gets or sets current material */
  19716. get: function () {
  19717. return this._material;
  19718. },
  19719. set: function (value) {
  19720. if (this._material === value) {
  19721. return;
  19722. }
  19723. this._material = value;
  19724. if (this.onMaterialChangedObservable.hasObservers) {
  19725. this.onMaterialChangedObservable.notifyObservers(this);
  19726. }
  19727. if (!this.subMeshes) {
  19728. return;
  19729. }
  19730. this._unBindEffect();
  19731. },
  19732. enumerable: true,
  19733. configurable: true
  19734. });
  19735. Object.defineProperty(AbstractMesh.prototype, "receiveShadows", {
  19736. /**
  19737. * Gets or sets a boolean indicating that this mesh can receive realtime shadows
  19738. * @see http://doc.babylonjs.com/babylon101/shadows
  19739. */
  19740. get: function () {
  19741. return this._receiveShadows;
  19742. },
  19743. set: function (value) {
  19744. if (this._receiveShadows === value) {
  19745. return;
  19746. }
  19747. this._receiveShadows = value;
  19748. this._markSubMeshesAsLightDirty();
  19749. },
  19750. enumerable: true,
  19751. configurable: true
  19752. });
  19753. Object.defineProperty(AbstractMesh.prototype, "hasVertexAlpha", {
  19754. /** Gets or sets a boolean indicating that this mesh contains vertex color data with alpha values */
  19755. get: function () {
  19756. return this._hasVertexAlpha;
  19757. },
  19758. set: function (value) {
  19759. if (this._hasVertexAlpha === value) {
  19760. return;
  19761. }
  19762. this._hasVertexAlpha = value;
  19763. this._markSubMeshesAsAttributesDirty();
  19764. this._markSubMeshesAsMiscDirty();
  19765. },
  19766. enumerable: true,
  19767. configurable: true
  19768. });
  19769. Object.defineProperty(AbstractMesh.prototype, "useVertexColors", {
  19770. /** 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) */
  19771. get: function () {
  19772. return this._useVertexColors;
  19773. },
  19774. set: function (value) {
  19775. if (this._useVertexColors === value) {
  19776. return;
  19777. }
  19778. this._useVertexColors = value;
  19779. this._markSubMeshesAsAttributesDirty();
  19780. },
  19781. enumerable: true,
  19782. configurable: true
  19783. });
  19784. Object.defineProperty(AbstractMesh.prototype, "computeBonesUsingShaders", {
  19785. /**
  19786. * Gets or sets a boolean indicating that bone animations must be computed by the CPU (false by default)
  19787. */
  19788. get: function () {
  19789. return this._computeBonesUsingShaders;
  19790. },
  19791. set: function (value) {
  19792. if (this._computeBonesUsingShaders === value) {
  19793. return;
  19794. }
  19795. this._computeBonesUsingShaders = value;
  19796. this._markSubMeshesAsAttributesDirty();
  19797. },
  19798. enumerable: true,
  19799. configurable: true
  19800. });
  19801. Object.defineProperty(AbstractMesh.prototype, "numBoneInfluencers", {
  19802. /** Gets or sets the number of allowed bone influences per vertex (4 by default) */
  19803. get: function () {
  19804. return this._numBoneInfluencers;
  19805. },
  19806. set: function (value) {
  19807. if (this._numBoneInfluencers === value) {
  19808. return;
  19809. }
  19810. this._numBoneInfluencers = value;
  19811. this._markSubMeshesAsAttributesDirty();
  19812. },
  19813. enumerable: true,
  19814. configurable: true
  19815. });
  19816. Object.defineProperty(AbstractMesh.prototype, "applyFog", {
  19817. /** Gets or sets a boolean indicating that this mesh will allow fog to be rendered on it (true by default) */
  19818. get: function () {
  19819. return this._applyFog;
  19820. },
  19821. set: function (value) {
  19822. if (this._applyFog === value) {
  19823. return;
  19824. }
  19825. this._applyFog = value;
  19826. this._markSubMeshesAsMiscDirty();
  19827. },
  19828. enumerable: true,
  19829. configurable: true
  19830. });
  19831. Object.defineProperty(AbstractMesh.prototype, "layerMask", {
  19832. /**
  19833. * Gets or sets the current layer mask (default is 0x0FFFFFFF)
  19834. * @see http://doc.babylonjs.com/how_to/layermasks_and_multi-cam_textures
  19835. */
  19836. get: function () {
  19837. return this._layerMask;
  19838. },
  19839. set: function (value) {
  19840. if (value === this._layerMask) {
  19841. return;
  19842. }
  19843. this._layerMask = value;
  19844. this._resyncLightSources();
  19845. },
  19846. enumerable: true,
  19847. configurable: true
  19848. });
  19849. Object.defineProperty(AbstractMesh.prototype, "collisionMask", {
  19850. /**
  19851. * Gets or sets a collision mask used to mask collisions (default is -1).
  19852. * A collision between A and B will happen if A.collisionGroup & b.collisionMask !== 0
  19853. */
  19854. get: function () {
  19855. return this._collisionMask;
  19856. },
  19857. set: function (mask) {
  19858. this._collisionMask = !isNaN(mask) ? mask : -1;
  19859. },
  19860. enumerable: true,
  19861. configurable: true
  19862. });
  19863. Object.defineProperty(AbstractMesh.prototype, "collisionGroup", {
  19864. /**
  19865. * Gets or sets the current collision group mask (-1 by default).
  19866. * A collision between A and B will happen if A.collisionGroup & b.collisionMask !== 0
  19867. */
  19868. get: function () {
  19869. return this._collisionGroup;
  19870. },
  19871. set: function (mask) {
  19872. this._collisionGroup = !isNaN(mask) ? mask : -1;
  19873. },
  19874. enumerable: true,
  19875. configurable: true
  19876. });
  19877. Object.defineProperty(AbstractMesh.prototype, "_positions", {
  19878. /** @hidden */
  19879. get: function () {
  19880. return null;
  19881. },
  19882. enumerable: true,
  19883. configurable: true
  19884. });
  19885. Object.defineProperty(AbstractMesh.prototype, "skeleton", {
  19886. get: function () {
  19887. return this._skeleton;
  19888. },
  19889. /**
  19890. * Gets or sets a skeleton to apply skining transformations
  19891. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  19892. */
  19893. set: function (value) {
  19894. if (this._skeleton && this._skeleton.needInitialSkinMatrix) {
  19895. this._skeleton._unregisterMeshWithPoseMatrix(this);
  19896. }
  19897. if (value && value.needInitialSkinMatrix) {
  19898. value._registerMeshWithPoseMatrix(this);
  19899. }
  19900. this._skeleton = value;
  19901. if (!this._skeleton) {
  19902. this._bonesTransformMatrices = null;
  19903. }
  19904. this._markSubMeshesAsAttributesDirty();
  19905. },
  19906. enumerable: true,
  19907. configurable: true
  19908. });
  19909. /**
  19910. * Returns the string "AbstractMesh"
  19911. * @returns "AbstractMesh"
  19912. */
  19913. AbstractMesh.prototype.getClassName = function () {
  19914. return "AbstractMesh";
  19915. };
  19916. /**
  19917. * Gets a string representation of the current mesh
  19918. * @param fullDetails defines a boolean indicating if full details must be included
  19919. * @returns a string representation of the current mesh
  19920. */
  19921. AbstractMesh.prototype.toString = function (fullDetails) {
  19922. var ret = "Name: " + this.name + ", isInstance: " + (this instanceof BABYLON.InstancedMesh ? "YES" : "NO");
  19923. ret += ", # of submeshes: " + (this.subMeshes ? this.subMeshes.length : 0);
  19924. if (this._skeleton) {
  19925. ret += ", skeleton: " + this._skeleton.name;
  19926. }
  19927. if (fullDetails) {
  19928. ret += ", billboard mode: " + (["NONE", "X", "Y", null, "Z", null, null, "ALL"])[this.billboardMode];
  19929. ret += ", freeze wrld mat: " + (this._isWorldMatrixFrozen || this._waitingFreezeWorldMatrix ? "YES" : "NO");
  19930. }
  19931. return ret;
  19932. };
  19933. /** @hidden */
  19934. AbstractMesh.prototype._rebuild = function () {
  19935. if (this._occlusionQuery) {
  19936. this._occlusionQuery = null;
  19937. }
  19938. if (this._edgesRenderer) {
  19939. this._edgesRenderer._rebuild();
  19940. }
  19941. if (!this.subMeshes) {
  19942. return;
  19943. }
  19944. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  19945. var subMesh = _a[_i];
  19946. subMesh._rebuild();
  19947. }
  19948. };
  19949. /** @hidden */
  19950. AbstractMesh.prototype._resyncLightSources = function () {
  19951. this._lightSources.length = 0;
  19952. for (var _i = 0, _a = this.getScene().lights; _i < _a.length; _i++) {
  19953. var light = _a[_i];
  19954. if (!light.isEnabled()) {
  19955. continue;
  19956. }
  19957. if (light.canAffectMesh(this)) {
  19958. this._lightSources.push(light);
  19959. }
  19960. }
  19961. this._markSubMeshesAsLightDirty();
  19962. };
  19963. /** @hidden */
  19964. AbstractMesh.prototype._resyncLighSource = function (light) {
  19965. var isIn = light.isEnabled() && light.canAffectMesh(this);
  19966. var index = this._lightSources.indexOf(light);
  19967. if (index === -1) {
  19968. if (!isIn) {
  19969. return;
  19970. }
  19971. this._lightSources.push(light);
  19972. }
  19973. else {
  19974. if (isIn) {
  19975. return;
  19976. }
  19977. this._lightSources.splice(index, 1);
  19978. }
  19979. this._markSubMeshesAsLightDirty();
  19980. };
  19981. /** @hidden */
  19982. AbstractMesh.prototype._unBindEffect = function () {
  19983. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  19984. var subMesh = _a[_i];
  19985. subMesh.setEffect(null);
  19986. }
  19987. };
  19988. /** @hidden */
  19989. AbstractMesh.prototype._removeLightSource = function (light) {
  19990. var index = this._lightSources.indexOf(light);
  19991. if (index === -1) {
  19992. return;
  19993. }
  19994. this._lightSources.splice(index, 1);
  19995. this._markSubMeshesAsLightDirty();
  19996. };
  19997. AbstractMesh.prototype._markSubMeshesAsDirty = function (func) {
  19998. if (!this.subMeshes) {
  19999. return;
  20000. }
  20001. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  20002. var subMesh = _a[_i];
  20003. if (subMesh._materialDefines) {
  20004. func(subMesh._materialDefines);
  20005. }
  20006. }
  20007. };
  20008. /** @hidden */
  20009. AbstractMesh.prototype._markSubMeshesAsLightDirty = function () {
  20010. this._markSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  20011. };
  20012. /** @hidden */
  20013. AbstractMesh.prototype._markSubMeshesAsAttributesDirty = function () {
  20014. this._markSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  20015. };
  20016. /** @hidden */
  20017. AbstractMesh.prototype._markSubMeshesAsMiscDirty = function () {
  20018. if (!this.subMeshes) {
  20019. return;
  20020. }
  20021. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  20022. var subMesh = _a[_i];
  20023. var material = subMesh.getMaterial();
  20024. if (material) {
  20025. material.markAsDirty(BABYLON.Material.MiscDirtyFlag);
  20026. }
  20027. }
  20028. };
  20029. Object.defineProperty(AbstractMesh.prototype, "scaling", {
  20030. /**
  20031. * Gets or sets a Vector3 depicting the mesh scaling along each local axis X, Y, Z. Default is (1.0, 1.0, 1.0)
  20032. */
  20033. get: function () {
  20034. return this._scaling;
  20035. },
  20036. set: function (newScaling) {
  20037. this._scaling = newScaling;
  20038. if (this.physicsImpostor) {
  20039. this.physicsImpostor.forceUpdate();
  20040. }
  20041. },
  20042. enumerable: true,
  20043. configurable: true
  20044. });
  20045. // Methods
  20046. /**
  20047. * Disables the mesh edge rendering mode
  20048. * @returns the currentAbstractMesh
  20049. */
  20050. AbstractMesh.prototype.disableEdgesRendering = function () {
  20051. if (this._edgesRenderer) {
  20052. this._edgesRenderer.dispose();
  20053. this._edgesRenderer = null;
  20054. }
  20055. return this;
  20056. };
  20057. /**
  20058. * Enables the edge rendering mode on the mesh.
  20059. * This mode makes the mesh edges visible
  20060. * @param epsilon defines the maximal distance between two angles to detect a face
  20061. * @param checkVerticesInsteadOfIndices indicates that we should check vertex list directly instead of faces
  20062. * @returns the currentAbstractMesh
  20063. * @see https://www.babylonjs-playground.com/#19O9TU#0
  20064. */
  20065. AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  20066. if (epsilon === void 0) { epsilon = 0.95; }
  20067. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  20068. this.disableEdgesRendering();
  20069. this._edgesRenderer = new BABYLON.EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  20070. return this;
  20071. };
  20072. Object.defineProperty(AbstractMesh.prototype, "edgesRenderer", {
  20073. /**
  20074. * Gets the edgesRenderer associated with the mesh
  20075. */
  20076. get: function () {
  20077. return this._edgesRenderer;
  20078. },
  20079. enumerable: true,
  20080. configurable: true
  20081. });
  20082. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  20083. /**
  20084. * Returns true if the mesh is blocked. Implemented by child classes
  20085. */
  20086. get: function () {
  20087. return false;
  20088. },
  20089. enumerable: true,
  20090. configurable: true
  20091. });
  20092. /**
  20093. * Returns the mesh itself by default. Implemented by child classes
  20094. * @param camera defines the camera to use to pick the right LOD level
  20095. * @returns the currentAbstractMesh
  20096. */
  20097. AbstractMesh.prototype.getLOD = function (camera) {
  20098. return this;
  20099. };
  20100. /**
  20101. * Returns 0 by default. Implemented by child classes
  20102. * @returns an integer
  20103. */
  20104. AbstractMesh.prototype.getTotalVertices = function () {
  20105. return 0;
  20106. };
  20107. /**
  20108. * Returns null by default. Implemented by child classes
  20109. * @returns null
  20110. */
  20111. AbstractMesh.prototype.getIndices = function () {
  20112. return null;
  20113. };
  20114. /**
  20115. * Returns the array of the requested vertex data kind. Implemented by child classes
  20116. * @param kind defines the vertex data kind to use
  20117. * @returns null
  20118. */
  20119. AbstractMesh.prototype.getVerticesData = function (kind) {
  20120. return null;
  20121. };
  20122. /**
  20123. * Sets the vertex data of the mesh geometry for the requested `kind`.
  20124. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  20125. * Note that a new underlying VertexBuffer object is created each call.
  20126. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  20127. * @param kind defines vertex data kind:
  20128. * * BABYLON.VertexBuffer.PositionKind
  20129. * * BABYLON.VertexBuffer.UVKind
  20130. * * BABYLON.VertexBuffer.UV2Kind
  20131. * * BABYLON.VertexBuffer.UV3Kind
  20132. * * BABYLON.VertexBuffer.UV4Kind
  20133. * * BABYLON.VertexBuffer.UV5Kind
  20134. * * BABYLON.VertexBuffer.UV6Kind
  20135. * * BABYLON.VertexBuffer.ColorKind
  20136. * * BABYLON.VertexBuffer.MatricesIndicesKind
  20137. * * BABYLON.VertexBuffer.MatricesIndicesExtraKind
  20138. * * BABYLON.VertexBuffer.MatricesWeightsKind
  20139. * * BABYLON.VertexBuffer.MatricesWeightsExtraKind
  20140. * @param data defines the data source
  20141. * @param updatable defines if the data must be flagged as updatable (or static)
  20142. * @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
  20143. * @returns the current mesh
  20144. */
  20145. AbstractMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  20146. return this;
  20147. };
  20148. /**
  20149. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  20150. * If the mesh has no geometry, it is simply returned as it is.
  20151. * @param kind defines vertex data kind:
  20152. * * BABYLON.VertexBuffer.PositionKind
  20153. * * BABYLON.VertexBuffer.UVKind
  20154. * * BABYLON.VertexBuffer.UV2Kind
  20155. * * BABYLON.VertexBuffer.UV3Kind
  20156. * * BABYLON.VertexBuffer.UV4Kind
  20157. * * BABYLON.VertexBuffer.UV5Kind
  20158. * * BABYLON.VertexBuffer.UV6Kind
  20159. * * BABYLON.VertexBuffer.ColorKind
  20160. * * BABYLON.VertexBuffer.MatricesIndicesKind
  20161. * * BABYLON.VertexBuffer.MatricesIndicesExtraKind
  20162. * * BABYLON.VertexBuffer.MatricesWeightsKind
  20163. * * BABYLON.VertexBuffer.MatricesWeightsExtraKind
  20164. * @param data defines the data source
  20165. * @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
  20166. * @param makeItUnique If true, a new global geometry is created from this data and is set to the mesh
  20167. * @returns the current mesh
  20168. */
  20169. AbstractMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  20170. return this;
  20171. };
  20172. /**
  20173. * Sets the mesh indices,
  20174. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  20175. * @param indices Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array)
  20176. * @param totalVertices Defines the total number of vertices
  20177. * @returns the current mesh
  20178. */
  20179. AbstractMesh.prototype.setIndices = function (indices, totalVertices) {
  20180. return this;
  20181. };
  20182. /**
  20183. * Gets a boolean indicating if specific vertex data is present
  20184. * @param kind defines the vertex data kind to use
  20185. * @returns true is data kind is present
  20186. */
  20187. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  20188. return false;
  20189. };
  20190. /**
  20191. * Returns the mesh BoundingInfo object or creates a new one and returns if it was undefined
  20192. * @returns a BoundingInfo
  20193. */
  20194. AbstractMesh.prototype.getBoundingInfo = function () {
  20195. if (this._masterMesh) {
  20196. return this._masterMesh.getBoundingInfo();
  20197. }
  20198. if (!this._boundingInfo) {
  20199. // this._boundingInfo is being created here
  20200. this._updateBoundingInfo();
  20201. }
  20202. // cannot be null.
  20203. return this._boundingInfo;
  20204. };
  20205. /**
  20206. * Uniformly scales the mesh to fit inside of a unit cube (1 X 1 X 1 units)
  20207. * @param includeDescendants Use the hierarchy's bounding box instead of the mesh's bounding box
  20208. * @returns the current mesh
  20209. */
  20210. AbstractMesh.prototype.normalizeToUnitCube = function (includeDescendants) {
  20211. if (includeDescendants === void 0) { includeDescendants = true; }
  20212. var boundingVectors = this.getHierarchyBoundingVectors(includeDescendants);
  20213. var sizeVec = boundingVectors.max.subtract(boundingVectors.min);
  20214. var maxDimension = Math.max(sizeVec.x, sizeVec.y, sizeVec.z);
  20215. if (maxDimension === 0) {
  20216. return this;
  20217. }
  20218. var scale = 1 / maxDimension;
  20219. this.scaling.scaleInPlace(scale);
  20220. return this;
  20221. };
  20222. /**
  20223. * Overwrite the current bounding info
  20224. * @param boundingInfo defines the new bounding info
  20225. * @returns the current mesh
  20226. */
  20227. AbstractMesh.prototype.setBoundingInfo = function (boundingInfo) {
  20228. this._boundingInfo = boundingInfo;
  20229. return this;
  20230. };
  20231. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  20232. /** Gets a boolean indicating if this mesh has skinning data and an attached skeleton */
  20233. get: function () {
  20234. return (this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind));
  20235. },
  20236. enumerable: true,
  20237. configurable: true
  20238. });
  20239. /** @hidden */
  20240. AbstractMesh.prototype._preActivate = function () {
  20241. };
  20242. /** @hidden */
  20243. AbstractMesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  20244. };
  20245. /** @hidden */
  20246. AbstractMesh.prototype._activate = function (renderId) {
  20247. this._renderId = renderId;
  20248. };
  20249. /**
  20250. * Gets the current world matrix
  20251. * @returns a Matrix
  20252. */
  20253. AbstractMesh.prototype.getWorldMatrix = function () {
  20254. if (this._masterMesh) {
  20255. return this._masterMesh.getWorldMatrix();
  20256. }
  20257. return _super.prototype.getWorldMatrix.call(this);
  20258. };
  20259. /** @hidden */
  20260. AbstractMesh.prototype._getWorldMatrixDeterminant = function () {
  20261. if (this._masterMesh) {
  20262. return this._masterMesh._getWorldMatrixDeterminant();
  20263. }
  20264. return _super.prototype._getWorldMatrixDeterminant.call(this);
  20265. };
  20266. // ================================== Point of View Movement =================================
  20267. /**
  20268. * Perform relative position change from the point of view of behind the front of the mesh.
  20269. * This is performed taking into account the meshes current rotation, so you do not have to care.
  20270. * Supports definition of mesh facing forward or backward
  20271. * @param amountRight defines the distance on the right axis
  20272. * @param amountUp defines the distance on the up axis
  20273. * @param amountForward defines the distance on the forward axis
  20274. * @returns the current mesh
  20275. */
  20276. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  20277. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  20278. return this;
  20279. };
  20280. /**
  20281. * Calculate relative position change from the point of view of behind the front of the mesh.
  20282. * This is performed taking into account the meshes current rotation, so you do not have to care.
  20283. * Supports definition of mesh facing forward or backward
  20284. * @param amountRight defines the distance on the right axis
  20285. * @param amountUp defines the distance on the up axis
  20286. * @param amountForward defines the distance on the forward axis
  20287. * @returns the new displacement vector
  20288. */
  20289. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  20290. var rotMatrix = new BABYLON.Matrix();
  20291. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  20292. rotQuaternion.toRotationMatrix(rotMatrix);
  20293. var translationDelta = BABYLON.Vector3.Zero();
  20294. var defForwardMult = this.definedFacingForward ? -1 : 1;
  20295. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  20296. return translationDelta;
  20297. };
  20298. // ================================== Point of View Rotation =================================
  20299. /**
  20300. * Perform relative rotation change from the point of view of behind the front of the mesh.
  20301. * Supports definition of mesh facing forward or backward
  20302. * @param flipBack defines the flip
  20303. * @param twirlClockwise defines the twirl
  20304. * @param tiltRight defines the tilt
  20305. * @returns the current mesh
  20306. */
  20307. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  20308. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  20309. return this;
  20310. };
  20311. /**
  20312. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  20313. * Supports definition of mesh facing forward or backward.
  20314. * @param flipBack defines the flip
  20315. * @param twirlClockwise defines the twirl
  20316. * @param tiltRight defines the tilt
  20317. * @returns the new rotation vector
  20318. */
  20319. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  20320. var defForwardMult = this.definedFacingForward ? 1 : -1;
  20321. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  20322. };
  20323. /**
  20324. * Return the minimum and maximum world vectors of the entire hierarchy under current mesh
  20325. * @param includeDescendants Include bounding info from descendants as well (true by default)
  20326. * @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
  20327. * @returns the new bounding vectors
  20328. */
  20329. AbstractMesh.prototype.getHierarchyBoundingVectors = function (includeDescendants, predicate) {
  20330. if (includeDescendants === void 0) { includeDescendants = true; }
  20331. if (predicate === void 0) { predicate = null; }
  20332. // Ensures that all world matrix will be recomputed.
  20333. this.getScene().incrementRenderId();
  20334. this.computeWorldMatrix(true);
  20335. var min;
  20336. var max;
  20337. var boundingInfo = this.getBoundingInfo();
  20338. if (!this.subMeshes) {
  20339. min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  20340. max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  20341. }
  20342. else {
  20343. min = boundingInfo.boundingBox.minimumWorld;
  20344. max = boundingInfo.boundingBox.maximumWorld;
  20345. }
  20346. if (includeDescendants) {
  20347. var descendants = this.getDescendants(false);
  20348. for (var _i = 0, descendants_1 = descendants; _i < descendants_1.length; _i++) {
  20349. var descendant = descendants_1[_i];
  20350. var childMesh = descendant;
  20351. childMesh.computeWorldMatrix(true);
  20352. // Filters meshes based on custom predicate function.
  20353. if (predicate && !predicate(childMesh)) {
  20354. continue;
  20355. }
  20356. //make sure we have the needed params to get mix and max
  20357. if (!childMesh.getBoundingInfo || childMesh.getTotalVertices() === 0) {
  20358. continue;
  20359. }
  20360. var childBoundingInfo = childMesh.getBoundingInfo();
  20361. var boundingBox = childBoundingInfo.boundingBox;
  20362. var minBox = boundingBox.minimumWorld;
  20363. var maxBox = boundingBox.maximumWorld;
  20364. BABYLON.Tools.CheckExtends(minBox, min, max);
  20365. BABYLON.Tools.CheckExtends(maxBox, min, max);
  20366. }
  20367. }
  20368. return {
  20369. min: min,
  20370. max: max
  20371. };
  20372. };
  20373. /** @hidden */
  20374. AbstractMesh.prototype._updateBoundingInfo = function () {
  20375. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  20376. this._boundingInfo.update(this.worldMatrixFromCache);
  20377. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  20378. return this;
  20379. };
  20380. /** @hidden */
  20381. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  20382. if (!this.subMeshes) {
  20383. return this;
  20384. }
  20385. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  20386. var subMesh = this.subMeshes[subIndex];
  20387. if (!subMesh.IsGlobal) {
  20388. subMesh.updateBoundingInfo(matrix);
  20389. }
  20390. }
  20391. return this;
  20392. };
  20393. /** @hidden */
  20394. AbstractMesh.prototype._afterComputeWorldMatrix = function () {
  20395. // Bounding info
  20396. this._updateBoundingInfo();
  20397. };
  20398. /**
  20399. * Returns `true` if the mesh is within the frustum defined by the passed array of planes.
  20400. * A mesh is in the frustum if its bounding box intersects the frustum
  20401. * @param frustumPlanes defines the frustum to test
  20402. * @returns true if the mesh is in the frustum planes
  20403. */
  20404. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  20405. return this._boundingInfo !== null && this._boundingInfo.isInFrustum(frustumPlanes);
  20406. };
  20407. /**
  20408. * Returns `true` if the mesh is completely in the frustum defined be the passed array of planes.
  20409. * A mesh is completely in the frustum if its bounding box it completely inside the frustum.
  20410. * @param frustumPlanes defines the frustum to test
  20411. * @returns true if the mesh is completely in the frustum planes
  20412. */
  20413. AbstractMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  20414. return this._boundingInfo !== null && this._boundingInfo.isCompletelyInFrustum(frustumPlanes);
  20415. };
  20416. /**
  20417. * True if the mesh intersects another mesh or a SolidParticle object
  20418. * @param mesh defines a target mesh or SolidParticle to test
  20419. * @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)
  20420. * @param includeDescendants Can be set to true to test if the mesh defined in parameters intersects with the current mesh or any child meshes
  20421. * @returns true if there is an intersection
  20422. */
  20423. AbstractMesh.prototype.intersectsMesh = function (mesh, precise, includeDescendants) {
  20424. if (precise === void 0) { precise = false; }
  20425. if (!this._boundingInfo || !mesh._boundingInfo) {
  20426. return false;
  20427. }
  20428. if (this._boundingInfo.intersects(mesh._boundingInfo, precise)) {
  20429. return true;
  20430. }
  20431. if (includeDescendants) {
  20432. for (var _i = 0, _a = this.getChildMeshes(); _i < _a.length; _i++) {
  20433. var child = _a[_i];
  20434. if (child.intersectsMesh(mesh, precise, true)) {
  20435. return true;
  20436. }
  20437. }
  20438. }
  20439. return false;
  20440. };
  20441. /**
  20442. * Returns true if the passed point (Vector3) is inside the mesh bounding box
  20443. * @param point defines the point to test
  20444. * @returns true if there is an intersection
  20445. */
  20446. AbstractMesh.prototype.intersectsPoint = function (point) {
  20447. if (!this._boundingInfo) {
  20448. return false;
  20449. }
  20450. return this._boundingInfo.intersectsPoint(point);
  20451. };
  20452. /**
  20453. * Gets the current physics impostor
  20454. * @see http://doc.babylonjs.com/features/physics_engine
  20455. * @returns a physics impostor or null
  20456. */
  20457. AbstractMesh.prototype.getPhysicsImpostor = function () {
  20458. return this.physicsImpostor;
  20459. };
  20460. /**
  20461. * Gets the position of the current mesh in camera space
  20462. * @param camera defines the camera to use
  20463. * @returns a position
  20464. */
  20465. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  20466. if (camera === void 0) { camera = null; }
  20467. if (!camera) {
  20468. camera = this.getScene().activeCamera;
  20469. }
  20470. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  20471. };
  20472. /**
  20473. * Returns the distance from the mesh to the active camera
  20474. * @param camera defines the camera to use
  20475. * @returns the distance
  20476. */
  20477. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  20478. if (camera === void 0) { camera = null; }
  20479. if (!camera) {
  20480. camera = this.getScene().activeCamera;
  20481. }
  20482. return this.absolutePosition.subtract(camera.position).length();
  20483. };
  20484. /**
  20485. * Apply a physic impulse to the mesh
  20486. * @param force defines the force to apply
  20487. * @param contactPoint defines where to apply the force
  20488. * @returns the current mesh
  20489. * @see http://doc.babylonjs.com/how_to/using_the_physics_engine
  20490. */
  20491. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  20492. if (!this.physicsImpostor) {
  20493. return this;
  20494. }
  20495. this.physicsImpostor.applyImpulse(force, contactPoint);
  20496. return this;
  20497. };
  20498. /**
  20499. * Creates a physic joint between two meshes
  20500. * @param otherMesh defines the other mesh to use
  20501. * @param pivot1 defines the pivot to use on this mesh
  20502. * @param pivot2 defines the pivot to use on the other mesh
  20503. * @param options defines additional options (can be plugin dependent)
  20504. * @returns the current mesh
  20505. * @see https://www.babylonjs-playground.com/#0BS5U0#0
  20506. */
  20507. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  20508. if (!this.physicsImpostor || !otherMesh.physicsImpostor) {
  20509. return this;
  20510. }
  20511. this.physicsImpostor.createJoint(otherMesh.physicsImpostor, BABYLON.PhysicsJoint.HingeJoint, {
  20512. mainPivot: pivot1,
  20513. connectedPivot: pivot2,
  20514. nativeParams: options
  20515. });
  20516. return this;
  20517. };
  20518. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  20519. // Collisions
  20520. /**
  20521. * Gets or sets a boolean indicating that this mesh can be used in the collision engine
  20522. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  20523. */
  20524. get: function () {
  20525. return this._checkCollisions;
  20526. },
  20527. set: function (collisionEnabled) {
  20528. this._checkCollisions = collisionEnabled;
  20529. if (this.getScene().workerCollisions) {
  20530. this.getScene().collisionCoordinator.onMeshUpdated(this);
  20531. }
  20532. },
  20533. enumerable: true,
  20534. configurable: true
  20535. });
  20536. Object.defineProperty(AbstractMesh.prototype, "collider", {
  20537. /**
  20538. * Gets Collider object used to compute collisions (not physics)
  20539. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  20540. */
  20541. get: function () {
  20542. return this._collider;
  20543. },
  20544. enumerable: true,
  20545. configurable: true
  20546. });
  20547. /**
  20548. * Move the mesh using collision engine
  20549. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  20550. * @param displacement defines the requested displacement vector
  20551. * @returns the current mesh
  20552. */
  20553. AbstractMesh.prototype.moveWithCollisions = function (displacement) {
  20554. var globalPosition = this.getAbsolutePosition();
  20555. globalPosition.addToRef(this.ellipsoidOffset, this._oldPositionForCollisions);
  20556. if (!this._collider) {
  20557. this._collider = new BABYLON.Collider();
  20558. }
  20559. this._collider._radius = this.ellipsoid;
  20560. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, displacement, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  20561. return this;
  20562. };
  20563. // Submeshes octree
  20564. /**
  20565. * This function will create an octree to help to select the right submeshes for rendering, picking and collision computations.
  20566. * Please note that you must have a decent number of submeshes to get performance improvements when using an octree
  20567. * @param maxCapacity defines the maximum size of each block (64 by default)
  20568. * @param maxDepth defines the maximum depth to use (no more than 2 levels by default)
  20569. * @returns the new octree
  20570. * @see https://www.babylonjs-playground.com/#NA4OQ#12
  20571. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees
  20572. */
  20573. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  20574. if (maxCapacity === void 0) { maxCapacity = 64; }
  20575. if (maxDepth === void 0) { maxDepth = 2; }
  20576. if (!this._submeshesOctree) {
  20577. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  20578. }
  20579. this.computeWorldMatrix(true);
  20580. var boundingInfo = this.getBoundingInfo();
  20581. // Update octree
  20582. var bbox = boundingInfo.boundingBox;
  20583. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  20584. return this._submeshesOctree;
  20585. };
  20586. // Collisions
  20587. /** @hidden */
  20588. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  20589. this._generatePointsArray();
  20590. if (!this._positions) {
  20591. return this;
  20592. }
  20593. // Transformation
  20594. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  20595. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  20596. subMesh._lastColliderWorldVertices = [];
  20597. subMesh._trianglePlanes = [];
  20598. var start = subMesh.verticesStart;
  20599. var end = (subMesh.verticesStart + subMesh.verticesCount);
  20600. for (var i = start; i < end; i++) {
  20601. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  20602. }
  20603. }
  20604. // Collide
  20605. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  20606. if (collider.collisionFound) {
  20607. collider.collidedMesh = this;
  20608. }
  20609. return this;
  20610. };
  20611. /** @hidden */
  20612. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  20613. var subMeshes;
  20614. var len;
  20615. // Octrees
  20616. if (this._submeshesOctree && this.useOctreeForCollisions) {
  20617. var radius = collider._velocityWorldLength + Math.max(collider._radius.x, collider._radius.y, collider._radius.z);
  20618. var intersections = this._submeshesOctree.intersects(collider._basePointWorld, radius);
  20619. len = intersections.length;
  20620. subMeshes = intersections.data;
  20621. }
  20622. else {
  20623. subMeshes = this.subMeshes;
  20624. len = subMeshes.length;
  20625. }
  20626. for (var index = 0; index < len; index++) {
  20627. var subMesh = subMeshes[index];
  20628. // Bounding test
  20629. if (len > 1 && !subMesh._checkCollision(collider))
  20630. continue;
  20631. this._collideForSubMesh(subMesh, transformMatrix, collider);
  20632. }
  20633. return this;
  20634. };
  20635. /** @hidden */
  20636. AbstractMesh.prototype._checkCollision = function (collider) {
  20637. // Bounding box test
  20638. if (!this._boundingInfo || !this._boundingInfo._checkCollision(collider))
  20639. return this;
  20640. // Transformation matrix
  20641. BABYLON.Matrix.ScalingToRef(1.0 / collider._radius.x, 1.0 / collider._radius.y, 1.0 / collider._radius.z, this._collisionsScalingMatrix);
  20642. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  20643. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  20644. return this;
  20645. };
  20646. // Picking
  20647. /** @hidden */
  20648. AbstractMesh.prototype._generatePointsArray = function () {
  20649. return false;
  20650. };
  20651. /**
  20652. * Checks if the passed Ray intersects with the mesh
  20653. * @param ray defines the ray to use
  20654. * @param fastCheck defines if fast mode (but less precise) must be used (false by default)
  20655. * @returns the picking info
  20656. * @see http://doc.babylonjs.com/babylon101/intersect_collisions_-_mesh
  20657. */
  20658. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  20659. var pickingInfo = new BABYLON.PickingInfo();
  20660. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  20661. return pickingInfo;
  20662. }
  20663. if (!this._generatePointsArray()) {
  20664. return pickingInfo;
  20665. }
  20666. var intersectInfo = null;
  20667. // Octrees
  20668. var subMeshes;
  20669. var len;
  20670. if (this._submeshesOctree && this.useOctreeForPicking) {
  20671. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  20672. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  20673. len = intersections.length;
  20674. subMeshes = intersections.data;
  20675. }
  20676. else {
  20677. subMeshes = this.subMeshes;
  20678. len = subMeshes.length;
  20679. }
  20680. for (var index = 0; index < len; index++) {
  20681. var subMesh = subMeshes[index];
  20682. // Bounding test
  20683. if (len > 1 && !subMesh.canIntersects(ray))
  20684. continue;
  20685. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  20686. if (currentIntersectInfo) {
  20687. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  20688. intersectInfo = currentIntersectInfo;
  20689. intersectInfo.subMeshId = index;
  20690. if (fastCheck) {
  20691. break;
  20692. }
  20693. }
  20694. }
  20695. }
  20696. if (intersectInfo) {
  20697. // Get picked point
  20698. var world = this.getWorldMatrix();
  20699. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  20700. var direction = ray.direction.clone();
  20701. direction = direction.scale(intersectInfo.distance);
  20702. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  20703. var pickedPoint = worldOrigin.add(worldDirection);
  20704. // Return result
  20705. pickingInfo.hit = true;
  20706. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  20707. pickingInfo.pickedPoint = pickedPoint;
  20708. pickingInfo.pickedMesh = this;
  20709. pickingInfo.bu = intersectInfo.bu || 0;
  20710. pickingInfo.bv = intersectInfo.bv || 0;
  20711. pickingInfo.faceId = intersectInfo.faceId;
  20712. pickingInfo.subMeshId = intersectInfo.subMeshId;
  20713. return pickingInfo;
  20714. }
  20715. return pickingInfo;
  20716. };
  20717. /**
  20718. * Clones the current mesh
  20719. * @param name defines the mesh name
  20720. * @param newParent defines the new mesh parent
  20721. * @param doNotCloneChildren defines a boolean indicating that children must not be cloned (false by default)
  20722. * @returns the new mesh
  20723. */
  20724. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  20725. return null;
  20726. };
  20727. /**
  20728. * Disposes all the submeshes of the current meshnp
  20729. * @returns the current mesh
  20730. */
  20731. AbstractMesh.prototype.releaseSubMeshes = function () {
  20732. if (this.subMeshes) {
  20733. while (this.subMeshes.length) {
  20734. this.subMeshes[0].dispose();
  20735. }
  20736. }
  20737. else {
  20738. this.subMeshes = new Array();
  20739. }
  20740. return this;
  20741. };
  20742. /**
  20743. * Releases resources associated with this abstract mesh.
  20744. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  20745. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  20746. */
  20747. AbstractMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  20748. var _this = this;
  20749. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  20750. var index;
  20751. // Smart Array Retainers.
  20752. this.getScene().freeActiveMeshes();
  20753. this.getScene().freeRenderingGroups();
  20754. // Action manager
  20755. if (this.actionManager !== undefined && this.actionManager !== null) {
  20756. this.actionManager.dispose();
  20757. this.actionManager = null;
  20758. }
  20759. // Skeleton
  20760. this._skeleton = null;
  20761. // Physics
  20762. if (this.physicsImpostor) {
  20763. this.physicsImpostor.dispose( /*!doNotRecurse*/);
  20764. }
  20765. // Intersections in progress
  20766. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  20767. var other = this._intersectionsInProgress[index];
  20768. var pos = other._intersectionsInProgress.indexOf(this);
  20769. other._intersectionsInProgress.splice(pos, 1);
  20770. }
  20771. this._intersectionsInProgress = [];
  20772. // Lights
  20773. var lights = this.getScene().lights;
  20774. lights.forEach(function (light) {
  20775. var meshIndex = light.includedOnlyMeshes.indexOf(_this);
  20776. if (meshIndex !== -1) {
  20777. light.includedOnlyMeshes.splice(meshIndex, 1);
  20778. }
  20779. meshIndex = light.excludedMeshes.indexOf(_this);
  20780. if (meshIndex !== -1) {
  20781. light.excludedMeshes.splice(meshIndex, 1);
  20782. }
  20783. // Shadow generators
  20784. var generator = light.getShadowGenerator();
  20785. if (generator) {
  20786. var shadowMap = generator.getShadowMap();
  20787. if (shadowMap && shadowMap.renderList) {
  20788. meshIndex = shadowMap.renderList.indexOf(_this);
  20789. if (meshIndex !== -1) {
  20790. shadowMap.renderList.splice(meshIndex, 1);
  20791. }
  20792. }
  20793. }
  20794. });
  20795. // Edges
  20796. if (this._edgesRenderer) {
  20797. this._edgesRenderer.dispose();
  20798. this._edgesRenderer = null;
  20799. }
  20800. // SubMeshes
  20801. if (this.getClassName() !== "InstancedMesh") {
  20802. this.releaseSubMeshes();
  20803. }
  20804. // Octree
  20805. var sceneOctree = this.getScene().selectionOctree;
  20806. if (sceneOctree !== undefined && sceneOctree !== null) {
  20807. var index = sceneOctree.dynamicContent.indexOf(this);
  20808. if (index !== -1) {
  20809. sceneOctree.dynamicContent.splice(index, 1);
  20810. }
  20811. }
  20812. // Query
  20813. var engine = this.getScene().getEngine();
  20814. if (this._occlusionQuery) {
  20815. this._isOcclusionQueryInProgress = false;
  20816. engine.deleteQuery(this._occlusionQuery);
  20817. this._occlusionQuery = null;
  20818. }
  20819. // Engine
  20820. engine.wipeCaches();
  20821. // Remove from scene
  20822. this.getScene().removeMesh(this);
  20823. if (disposeMaterialAndTextures) {
  20824. if (this.material) {
  20825. this.material.dispose(false, true);
  20826. }
  20827. }
  20828. if (!doNotRecurse) {
  20829. // Particles
  20830. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  20831. if (this.getScene().particleSystems[index].emitter === this) {
  20832. this.getScene().particleSystems[index].dispose();
  20833. index--;
  20834. }
  20835. }
  20836. }
  20837. // facet data
  20838. if (this._facetDataEnabled) {
  20839. this.disableFacetData();
  20840. }
  20841. this.onAfterWorldMatrixUpdateObservable.clear();
  20842. this.onCollideObservable.clear();
  20843. this.onCollisionPositionChangeObservable.clear();
  20844. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  20845. };
  20846. /**
  20847. * Adds the passed mesh as a child to the current mesh
  20848. * @param mesh defines the child mesh
  20849. * @returns the current mesh
  20850. */
  20851. AbstractMesh.prototype.addChild = function (mesh) {
  20852. mesh.setParent(this);
  20853. return this;
  20854. };
  20855. /**
  20856. * Removes the passed mesh from the current mesh children list
  20857. * @param mesh defines the child mesh
  20858. * @returns the current mesh
  20859. */
  20860. AbstractMesh.prototype.removeChild = function (mesh) {
  20861. mesh.setParent(null);
  20862. return this;
  20863. };
  20864. // Facet data
  20865. /** @hidden */
  20866. AbstractMesh.prototype._initFacetData = function () {
  20867. if (!this._facetNormals) {
  20868. this._facetNormals = new Array();
  20869. }
  20870. if (!this._facetPositions) {
  20871. this._facetPositions = new Array();
  20872. }
  20873. if (!this._facetPartitioning) {
  20874. this._facetPartitioning = new Array();
  20875. }
  20876. this._facetNb = (this.getIndices().length / 3) | 0;
  20877. this._partitioningSubdivisions = (this._partitioningSubdivisions) ? this._partitioningSubdivisions : 10; // default nb of partitioning subdivisions = 10
  20878. this._partitioningBBoxRatio = (this._partitioningBBoxRatio) ? this._partitioningBBoxRatio : 1.01; // default ratio 1.01 = the partitioning is 1% bigger than the bounding box
  20879. for (var f = 0; f < this._facetNb; f++) {
  20880. this._facetNormals[f] = BABYLON.Vector3.Zero();
  20881. this._facetPositions[f] = BABYLON.Vector3.Zero();
  20882. }
  20883. this._facetDataEnabled = true;
  20884. return this;
  20885. };
  20886. /**
  20887. * Updates the mesh facetData arrays and the internal partitioning when the mesh is morphed or updated.
  20888. * This method can be called within the render loop.
  20889. * 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
  20890. * @returns the current mesh
  20891. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  20892. */
  20893. AbstractMesh.prototype.updateFacetData = function () {
  20894. if (!this._facetDataEnabled) {
  20895. this._initFacetData();
  20896. }
  20897. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  20898. var indices = this.getIndices();
  20899. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  20900. var bInfo = this.getBoundingInfo();
  20901. if (this._facetDepthSort && !this._facetDepthSortEnabled) {
  20902. // init arrays, matrix and sort function on first call
  20903. this._facetDepthSortEnabled = true;
  20904. if (indices instanceof Uint16Array) {
  20905. this._depthSortedIndices = new Uint16Array(indices);
  20906. }
  20907. else if (indices instanceof Uint32Array) {
  20908. this._depthSortedIndices = new Uint32Array(indices);
  20909. }
  20910. else {
  20911. var needs32bits = false;
  20912. for (var i = 0; i < indices.length; i++) {
  20913. if (indices[i] > 65535) {
  20914. needs32bits = true;
  20915. break;
  20916. }
  20917. }
  20918. if (needs32bits) {
  20919. this._depthSortedIndices = new Uint32Array(indices);
  20920. }
  20921. else {
  20922. this._depthSortedIndices = new Uint16Array(indices);
  20923. }
  20924. }
  20925. this._facetDepthSortFunction = function (f1, f2) {
  20926. return (f2.sqDistance - f1.sqDistance);
  20927. };
  20928. if (!this._facetDepthSortFrom) {
  20929. var camera = this.getScene().activeCamera;
  20930. this._facetDepthSortFrom = (camera) ? camera.position : BABYLON.Vector3.Zero();
  20931. }
  20932. this._depthSortedFacets = [];
  20933. for (var f = 0; f < this._facetNb; f++) {
  20934. var depthSortedFacet = { ind: f * 3, sqDistance: 0.0 };
  20935. this._depthSortedFacets.push(depthSortedFacet);
  20936. }
  20937. this._invertedMatrix = BABYLON.Matrix.Identity();
  20938. this._facetDepthSortOrigin = BABYLON.Vector3.Zero();
  20939. }
  20940. this._bbSize.x = (bInfo.maximum.x - bInfo.minimum.x > BABYLON.Epsilon) ? bInfo.maximum.x - bInfo.minimum.x : BABYLON.Epsilon;
  20941. this._bbSize.y = (bInfo.maximum.y - bInfo.minimum.y > BABYLON.Epsilon) ? bInfo.maximum.y - bInfo.minimum.y : BABYLON.Epsilon;
  20942. this._bbSize.z = (bInfo.maximum.z - bInfo.minimum.z > BABYLON.Epsilon) ? bInfo.maximum.z - bInfo.minimum.z : BABYLON.Epsilon;
  20943. var bbSizeMax = (this._bbSize.x > this._bbSize.y) ? this._bbSize.x : this._bbSize.y;
  20944. bbSizeMax = (bbSizeMax > this._bbSize.z) ? bbSizeMax : this._bbSize.z;
  20945. this._subDiv.max = this._partitioningSubdivisions;
  20946. this._subDiv.X = Math.floor(this._subDiv.max * this._bbSize.x / bbSizeMax); // adjust the number of subdivisions per axis
  20947. this._subDiv.Y = Math.floor(this._subDiv.max * this._bbSize.y / bbSizeMax); // according to each bbox size per axis
  20948. this._subDiv.Z = Math.floor(this._subDiv.max * this._bbSize.z / bbSizeMax);
  20949. this._subDiv.X = this._subDiv.X < 1 ? 1 : this._subDiv.X; // at least one subdivision
  20950. this._subDiv.Y = this._subDiv.Y < 1 ? 1 : this._subDiv.Y;
  20951. this._subDiv.Z = this._subDiv.Z < 1 ? 1 : this._subDiv.Z;
  20952. // set the parameters for ComputeNormals()
  20953. this._facetParameters.facetNormals = this.getFacetLocalNormals();
  20954. this._facetParameters.facetPositions = this.getFacetLocalPositions();
  20955. this._facetParameters.facetPartitioning = this.getFacetLocalPartitioning();
  20956. this._facetParameters.bInfo = bInfo;
  20957. this._facetParameters.bbSize = this._bbSize;
  20958. this._facetParameters.subDiv = this._subDiv;
  20959. this._facetParameters.ratio = this.partitioningBBoxRatio;
  20960. this._facetParameters.depthSort = this._facetDepthSort;
  20961. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  20962. this.computeWorldMatrix(true);
  20963. this._worldMatrix.invertToRef(this._invertedMatrix);
  20964. BABYLON.Vector3.TransformCoordinatesToRef(this._facetDepthSortFrom, this._invertedMatrix, this._facetDepthSortOrigin);
  20965. this._facetParameters.distanceTo = this._facetDepthSortOrigin;
  20966. }
  20967. this._facetParameters.depthSortedFacets = this._depthSortedFacets;
  20968. BABYLON.VertexData.ComputeNormals(positions, indices, normals, this._facetParameters);
  20969. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  20970. this._depthSortedFacets.sort(this._facetDepthSortFunction);
  20971. var l = (this._depthSortedIndices.length / 3) | 0;
  20972. for (var f = 0; f < l; f++) {
  20973. var sind = this._depthSortedFacets[f].ind;
  20974. this._depthSortedIndices[f * 3] = indices[sind];
  20975. this._depthSortedIndices[f * 3 + 1] = indices[sind + 1];
  20976. this._depthSortedIndices[f * 3 + 2] = indices[sind + 2];
  20977. }
  20978. this.updateIndices(this._depthSortedIndices);
  20979. }
  20980. return this;
  20981. };
  20982. /**
  20983. * Returns the facetLocalNormals array.
  20984. * The normals are expressed in the mesh local spac
  20985. * @returns an array of Vector3
  20986. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  20987. */
  20988. AbstractMesh.prototype.getFacetLocalNormals = function () {
  20989. if (!this._facetNormals) {
  20990. this.updateFacetData();
  20991. }
  20992. return this._facetNormals;
  20993. };
  20994. /**
  20995. * Returns the facetLocalPositions array.
  20996. * The facet positions are expressed in the mesh local space
  20997. * @returns an array of Vector3
  20998. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  20999. */
  21000. AbstractMesh.prototype.getFacetLocalPositions = function () {
  21001. if (!this._facetPositions) {
  21002. this.updateFacetData();
  21003. }
  21004. return this._facetPositions;
  21005. };
  21006. /**
  21007. * Returns the facetLocalPartioning array
  21008. * @returns an array of array of numbers
  21009. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21010. */
  21011. AbstractMesh.prototype.getFacetLocalPartitioning = function () {
  21012. if (!this._facetPartitioning) {
  21013. this.updateFacetData();
  21014. }
  21015. return this._facetPartitioning;
  21016. };
  21017. /**
  21018. * Returns the i-th facet position in the world system.
  21019. * This method allocates a new Vector3 per call
  21020. * @param i defines the facet index
  21021. * @returns a new Vector3
  21022. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21023. */
  21024. AbstractMesh.prototype.getFacetPosition = function (i) {
  21025. var pos = BABYLON.Vector3.Zero();
  21026. this.getFacetPositionToRef(i, pos);
  21027. return pos;
  21028. };
  21029. /**
  21030. * Sets the reference Vector3 with the i-th facet position in the world system
  21031. * @param i defines the facet index
  21032. * @param ref defines the target vector
  21033. * @returns the current mesh
  21034. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21035. */
  21036. AbstractMesh.prototype.getFacetPositionToRef = function (i, ref) {
  21037. var localPos = (this.getFacetLocalPositions())[i];
  21038. var world = this.getWorldMatrix();
  21039. BABYLON.Vector3.TransformCoordinatesToRef(localPos, world, ref);
  21040. return this;
  21041. };
  21042. /**
  21043. * Returns the i-th facet normal in the world system.
  21044. * This method allocates a new Vector3 per call
  21045. * @param i defines the facet index
  21046. * @returns a new Vector3
  21047. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21048. */
  21049. AbstractMesh.prototype.getFacetNormal = function (i) {
  21050. var norm = BABYLON.Vector3.Zero();
  21051. this.getFacetNormalToRef(i, norm);
  21052. return norm;
  21053. };
  21054. /**
  21055. * Sets the reference Vector3 with the i-th facet normal in the world system
  21056. * @param i defines the facet index
  21057. * @param ref defines the target vector
  21058. * @returns the current mesh
  21059. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21060. */
  21061. AbstractMesh.prototype.getFacetNormalToRef = function (i, ref) {
  21062. var localNorm = (this.getFacetLocalNormals())[i];
  21063. BABYLON.Vector3.TransformNormalToRef(localNorm, this.getWorldMatrix(), ref);
  21064. return this;
  21065. };
  21066. /**
  21067. * 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)
  21068. * @param x defines x coordinate
  21069. * @param y defines y coordinate
  21070. * @param z defines z coordinate
  21071. * @returns the array of facet indexes
  21072. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21073. */
  21074. AbstractMesh.prototype.getFacetsAtLocalCoordinates = function (x, y, z) {
  21075. var bInfo = this.getBoundingInfo();
  21076. var ox = Math.floor((x - bInfo.minimum.x * this._partitioningBBoxRatio) * this._subDiv.X * this._partitioningBBoxRatio / this._bbSize.x);
  21077. var oy = Math.floor((y - bInfo.minimum.y * this._partitioningBBoxRatio) * this._subDiv.Y * this._partitioningBBoxRatio / this._bbSize.y);
  21078. var oz = Math.floor((z - bInfo.minimum.z * this._partitioningBBoxRatio) * this._subDiv.Z * this._partitioningBBoxRatio / this._bbSize.z);
  21079. if (ox < 0 || ox > this._subDiv.max || oy < 0 || oy > this._subDiv.max || oz < 0 || oz > this._subDiv.max) {
  21080. return null;
  21081. }
  21082. return this._facetPartitioning[ox + this._subDiv.max * oy + this._subDiv.max * this._subDiv.max * oz];
  21083. };
  21084. /**
  21085. * Returns the closest mesh facet index at (x,y,z) World coordinates, null if not found
  21086. * @param projected sets as the (x,y,z) world projection on the facet
  21087. * @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
  21088. * @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
  21089. * @param x defines x coordinate
  21090. * @param y defines y coordinate
  21091. * @param z defines z coordinate
  21092. * @returns the face index if found (or null instead)
  21093. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21094. */
  21095. AbstractMesh.prototype.getClosestFacetAtCoordinates = function (x, y, z, projected, checkFace, facing) {
  21096. if (checkFace === void 0) { checkFace = false; }
  21097. if (facing === void 0) { facing = true; }
  21098. var world = this.getWorldMatrix();
  21099. var invMat = BABYLON.Tmp.Matrix[5];
  21100. world.invertToRef(invMat);
  21101. var invVect = BABYLON.Tmp.Vector3[8];
  21102. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, invMat, invVect); // transform (x,y,z) to coordinates in the mesh local space
  21103. var closest = this.getClosestFacetAtLocalCoordinates(invVect.x, invVect.y, invVect.z, projected, checkFace, facing);
  21104. if (projected) {
  21105. // tranform the local computed projected vector to world coordinates
  21106. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(projected.x, projected.y, projected.z, world, projected);
  21107. }
  21108. return closest;
  21109. };
  21110. /**
  21111. * Returns the closest mesh facet index at (x,y,z) local coordinates, null if not found
  21112. * @param projected sets as the (x,y,z) local projection on the facet
  21113. * @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
  21114. * @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
  21115. * @param x defines x coordinate
  21116. * @param y defines y coordinate
  21117. * @param z defines z coordinate
  21118. * @returns the face index if found (or null instead)
  21119. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21120. */
  21121. AbstractMesh.prototype.getClosestFacetAtLocalCoordinates = function (x, y, z, projected, checkFace, facing) {
  21122. if (checkFace === void 0) { checkFace = false; }
  21123. if (facing === void 0) { facing = true; }
  21124. var closest = null;
  21125. var tmpx = 0.0;
  21126. var tmpy = 0.0;
  21127. var tmpz = 0.0;
  21128. var d = 0.0; // tmp dot facet normal * facet position
  21129. var t0 = 0.0;
  21130. var projx = 0.0;
  21131. var projy = 0.0;
  21132. var projz = 0.0;
  21133. // Get all the facets in the same partitioning block than (x, y, z)
  21134. var facetPositions = this.getFacetLocalPositions();
  21135. var facetNormals = this.getFacetLocalNormals();
  21136. var facetsInBlock = this.getFacetsAtLocalCoordinates(x, y, z);
  21137. if (!facetsInBlock) {
  21138. return null;
  21139. }
  21140. // Get the closest facet to (x, y, z)
  21141. var shortest = Number.MAX_VALUE; // init distance vars
  21142. var tmpDistance = shortest;
  21143. var fib; // current facet in the block
  21144. var norm; // current facet normal
  21145. var p0; // current facet barycenter position
  21146. // loop on all the facets in the current partitioning block
  21147. for (var idx = 0; idx < facetsInBlock.length; idx++) {
  21148. fib = facetsInBlock[idx];
  21149. norm = facetNormals[fib];
  21150. p0 = facetPositions[fib];
  21151. d = (x - p0.x) * norm.x + (y - p0.y) * norm.y + (z - p0.z) * norm.z;
  21152. if (!checkFace || (checkFace && facing && d >= 0.0) || (checkFace && !facing && d <= 0.0)) {
  21153. // compute (x,y,z) projection on the facet = (projx, projy, projz)
  21154. d = norm.x * p0.x + norm.y * p0.y + norm.z * p0.z;
  21155. t0 = -(norm.x * x + norm.y * y + norm.z * z - d) / (norm.x * norm.x + norm.y * norm.y + norm.z * norm.z);
  21156. projx = x + norm.x * t0;
  21157. projy = y + norm.y * t0;
  21158. projz = z + norm.z * t0;
  21159. tmpx = projx - x;
  21160. tmpy = projy - y;
  21161. tmpz = projz - z;
  21162. tmpDistance = tmpx * tmpx + tmpy * tmpy + tmpz * tmpz; // compute length between (x, y, z) and its projection on the facet
  21163. if (tmpDistance < shortest) { // just keep the closest facet to (x, y, z)
  21164. shortest = tmpDistance;
  21165. closest = fib;
  21166. if (projected) {
  21167. projected.x = projx;
  21168. projected.y = projy;
  21169. projected.z = projz;
  21170. }
  21171. }
  21172. }
  21173. }
  21174. return closest;
  21175. };
  21176. /**
  21177. * Returns the object "parameter" set with all the expected parameters for facetData computation by ComputeNormals()
  21178. * @returns the parameters
  21179. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21180. */
  21181. AbstractMesh.prototype.getFacetDataParameters = function () {
  21182. return this._facetParameters;
  21183. };
  21184. /**
  21185. * Disables the feature FacetData and frees the related memory
  21186. * @returns the current mesh
  21187. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21188. */
  21189. AbstractMesh.prototype.disableFacetData = function () {
  21190. if (this._facetDataEnabled) {
  21191. this._facetDataEnabled = false;
  21192. this._facetPositions = new Array();
  21193. this._facetNormals = new Array();
  21194. this._facetPartitioning = new Array();
  21195. this._facetParameters = null;
  21196. this._depthSortedIndices = new Uint32Array(0);
  21197. }
  21198. return this;
  21199. };
  21200. /**
  21201. * Updates the AbstractMesh indices array
  21202. * @param indices defines the data source
  21203. * @returns the current mesh
  21204. */
  21205. AbstractMesh.prototype.updateIndices = function (indices) {
  21206. return this;
  21207. };
  21208. /**
  21209. * Creates new normals data for the mesh
  21210. * @param updatable defines if the normal vertex buffer must be flagged as updatable
  21211. * @returns the current mesh
  21212. */
  21213. AbstractMesh.prototype.createNormals = function (updatable) {
  21214. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  21215. var indices = this.getIndices();
  21216. var normals;
  21217. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  21218. normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  21219. }
  21220. else {
  21221. normals = [];
  21222. }
  21223. BABYLON.VertexData.ComputeNormals(positions, indices, normals, { useRightHandedSystem: this.getScene().useRightHandedSystem });
  21224. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  21225. return this;
  21226. };
  21227. /**
  21228. * Align the mesh with a normal
  21229. * @param normal defines the normal to use
  21230. * @param upDirection can be used to redefined the up vector to use (will use the (0, 1, 0) by default)
  21231. * @returns the current mesh
  21232. */
  21233. AbstractMesh.prototype.alignWithNormal = function (normal, upDirection) {
  21234. if (!upDirection) {
  21235. upDirection = BABYLON.Axis.Y;
  21236. }
  21237. var axisX = BABYLON.Tmp.Vector3[0];
  21238. var axisZ = BABYLON.Tmp.Vector3[1];
  21239. BABYLON.Vector3.CrossToRef(upDirection, normal, axisZ);
  21240. BABYLON.Vector3.CrossToRef(normal, axisZ, axisX);
  21241. if (this.rotationQuaternion) {
  21242. BABYLON.Quaternion.RotationQuaternionFromAxisToRef(axisX, normal, axisZ, this.rotationQuaternion);
  21243. }
  21244. else {
  21245. BABYLON.Vector3.RotationFromAxisToRef(axisX, normal, axisZ, this.rotation);
  21246. }
  21247. return this;
  21248. };
  21249. /** @hidden */
  21250. AbstractMesh.prototype._checkOcclusionQuery = function () {
  21251. var engine = this.getEngine();
  21252. if (engine.webGLVersion < 2 || this.occlusionType === AbstractMesh.OCCLUSION_TYPE_NONE) {
  21253. this._isOccluded = false;
  21254. return;
  21255. }
  21256. if (this.isOcclusionQueryInProgress && this._occlusionQuery) {
  21257. var isOcclusionQueryAvailable = engine.isQueryResultAvailable(this._occlusionQuery);
  21258. if (isOcclusionQueryAvailable) {
  21259. var occlusionQueryResult = engine.getQueryResult(this._occlusionQuery);
  21260. this._isOcclusionQueryInProgress = false;
  21261. this._occlusionInternalRetryCounter = 0;
  21262. this._isOccluded = occlusionQueryResult === 1 ? false : true;
  21263. }
  21264. else {
  21265. this._occlusionInternalRetryCounter++;
  21266. if (this.occlusionRetryCount !== -1 && this._occlusionInternalRetryCounter > this.occlusionRetryCount) {
  21267. this._isOcclusionQueryInProgress = false;
  21268. this._occlusionInternalRetryCounter = 0;
  21269. // if optimistic set isOccluded to false regardless of the status of isOccluded. (Render in the current render loop)
  21270. // if strict continue the last state of the object.
  21271. this._isOccluded = this.occlusionType === AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC ? false : this._isOccluded;
  21272. }
  21273. else {
  21274. return;
  21275. }
  21276. }
  21277. }
  21278. var scene = this.getScene();
  21279. var occlusionBoundingBoxRenderer = scene.getBoundingBoxRenderer();
  21280. if (!this._occlusionQuery) {
  21281. this._occlusionQuery = engine.createQuery();
  21282. }
  21283. engine.beginOcclusionQuery(this.occlusionQueryAlgorithmType, this._occlusionQuery);
  21284. occlusionBoundingBoxRenderer.renderOcclusionBoundingBox(this);
  21285. engine.endOcclusionQuery(this.occlusionQueryAlgorithmType);
  21286. this._isOcclusionQueryInProgress = true;
  21287. };
  21288. /** No occlusion */
  21289. AbstractMesh.OCCLUSION_TYPE_NONE = 0;
  21290. /** Occlusion set to optimisitic */
  21291. AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC = 1;
  21292. /** Occlusion set to strict */
  21293. AbstractMesh.OCCLUSION_TYPE_STRICT = 2;
  21294. /** Use an accurante occlusion algorithm */
  21295. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE = 0;
  21296. /** Use a conservative occlusion algorithm */
  21297. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE = 1;
  21298. return AbstractMesh;
  21299. }(BABYLON.TransformNode));
  21300. BABYLON.AbstractMesh = AbstractMesh;
  21301. })(BABYLON || (BABYLON = {}));
  21302. //# sourceMappingURL=babylon.abstractMesh.js.map
  21303. var BABYLON;
  21304. (function (BABYLON) {
  21305. /**
  21306. * Base class of all the lights in Babylon. It groups all the generic information about lights.
  21307. * Lights are used, as you would expect, to affect how meshes are seen, in terms of both illumination and colour.
  21308. * 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.
  21309. */
  21310. var Light = /** @class */ (function (_super) {
  21311. __extends(Light, _super);
  21312. /**
  21313. * Creates a Light object in the scene.
  21314. * Documentation : http://doc.babylonjs.com/tutorials/lights
  21315. * @param name The firendly name of the light
  21316. * @param scene The scene the light belongs too
  21317. */
  21318. function Light(name, scene) {
  21319. var _this = _super.call(this, name, scene) || this;
  21320. /**
  21321. * Diffuse gives the basic color to an object.
  21322. */
  21323. _this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  21324. /**
  21325. * Specular produces a highlight color on an object.
  21326. * Note: This is note affecting PBR materials.
  21327. */
  21328. _this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  21329. /**
  21330. * Strength of the light.
  21331. * Note: By default it is define in the framework own unit.
  21332. * Note: In PBR materials the intensityMode can be use to chose what unit the intensity is defined in.
  21333. */
  21334. _this.intensity = 1.0;
  21335. /**
  21336. * Defines how far from the source the light is impacting in scene units.
  21337. * Note: Unused in PBR material as the distance light falloff is defined following the inverse squared falloff.
  21338. */
  21339. _this.range = Number.MAX_VALUE;
  21340. /**
  21341. * Cached photometric scale default to 1.0 as the automatic intensity mode defaults to 1.0 for every type
  21342. * of light.
  21343. */
  21344. _this._photometricScale = 1.0;
  21345. _this._intensityMode = Light.INTENSITYMODE_AUTOMATIC;
  21346. _this._radius = 0.00001;
  21347. /**
  21348. * Defines the rendering priority of the lights. It can help in case of fallback or number of lights
  21349. * exceeding the number allowed of the materials.
  21350. */
  21351. _this.renderPriority = 0;
  21352. _this._shadowEnabled = true;
  21353. _this._excludeWithLayerMask = 0;
  21354. _this._includeOnlyWithLayerMask = 0;
  21355. _this._lightmapMode = 0;
  21356. /**
  21357. * @hidden Internal use only.
  21358. */
  21359. _this._excludedMeshesIds = new Array();
  21360. /**
  21361. * @hidden Internal use only.
  21362. */
  21363. _this._includedOnlyMeshesIds = new Array();
  21364. _this.getScene().addLight(_this);
  21365. _this._uniformBuffer = new BABYLON.UniformBuffer(_this.getScene().getEngine());
  21366. _this._buildUniformLayout();
  21367. _this.includedOnlyMeshes = new Array();
  21368. _this.excludedMeshes = new Array();
  21369. _this._resyncMeshes();
  21370. return _this;
  21371. }
  21372. Object.defineProperty(Light, "LIGHTMAP_DEFAULT", {
  21373. /**
  21374. * If every light affecting the material is in this lightmapMode,
  21375. * material.lightmapTexture adds or multiplies
  21376. * (depends on material.useLightmapAsShadowmap)
  21377. * after every other light calculations.
  21378. */
  21379. get: function () {
  21380. return Light._LIGHTMAP_DEFAULT;
  21381. },
  21382. enumerable: true,
  21383. configurable: true
  21384. });
  21385. Object.defineProperty(Light, "LIGHTMAP_SPECULAR", {
  21386. /**
  21387. * material.lightmapTexture as only diffuse lighting from this light
  21388. * adds only specular lighting from this light
  21389. * adds dynamic shadows
  21390. */
  21391. get: function () {
  21392. return Light._LIGHTMAP_SPECULAR;
  21393. },
  21394. enumerable: true,
  21395. configurable: true
  21396. });
  21397. Object.defineProperty(Light, "LIGHTMAP_SHADOWSONLY", {
  21398. /**
  21399. * material.lightmapTexture as only lighting
  21400. * no light calculation from this light
  21401. * only adds dynamic shadows from this light
  21402. */
  21403. get: function () {
  21404. return Light._LIGHTMAP_SHADOWSONLY;
  21405. },
  21406. enumerable: true,
  21407. configurable: true
  21408. });
  21409. Object.defineProperty(Light, "INTENSITYMODE_AUTOMATIC", {
  21410. /**
  21411. * Each light type uses the default quantity according to its type:
  21412. * point/spot lights use luminous intensity
  21413. * directional lights use illuminance
  21414. */
  21415. get: function () {
  21416. return Light._INTENSITYMODE_AUTOMATIC;
  21417. },
  21418. enumerable: true,
  21419. configurable: true
  21420. });
  21421. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSPOWER", {
  21422. /**
  21423. * lumen (lm)
  21424. */
  21425. get: function () {
  21426. return Light._INTENSITYMODE_LUMINOUSPOWER;
  21427. },
  21428. enumerable: true,
  21429. configurable: true
  21430. });
  21431. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSINTENSITY", {
  21432. /**
  21433. * candela (lm/sr)
  21434. */
  21435. get: function () {
  21436. return Light._INTENSITYMODE_LUMINOUSINTENSITY;
  21437. },
  21438. enumerable: true,
  21439. configurable: true
  21440. });
  21441. Object.defineProperty(Light, "INTENSITYMODE_ILLUMINANCE", {
  21442. /**
  21443. * lux (lm/m^2)
  21444. */
  21445. get: function () {
  21446. return Light._INTENSITYMODE_ILLUMINANCE;
  21447. },
  21448. enumerable: true,
  21449. configurable: true
  21450. });
  21451. Object.defineProperty(Light, "INTENSITYMODE_LUMINANCE", {
  21452. /**
  21453. * nit (cd/m^2)
  21454. */
  21455. get: function () {
  21456. return Light._INTENSITYMODE_LUMINANCE;
  21457. },
  21458. enumerable: true,
  21459. configurable: true
  21460. });
  21461. Object.defineProperty(Light, "LIGHTTYPEID_POINTLIGHT", {
  21462. /**
  21463. * Light type const id of the point light.
  21464. */
  21465. get: function () {
  21466. return Light._LIGHTTYPEID_POINTLIGHT;
  21467. },
  21468. enumerable: true,
  21469. configurable: true
  21470. });
  21471. Object.defineProperty(Light, "LIGHTTYPEID_DIRECTIONALLIGHT", {
  21472. /**
  21473. * Light type const id of the directional light.
  21474. */
  21475. get: function () {
  21476. return Light._LIGHTTYPEID_DIRECTIONALLIGHT;
  21477. },
  21478. enumerable: true,
  21479. configurable: true
  21480. });
  21481. Object.defineProperty(Light, "LIGHTTYPEID_SPOTLIGHT", {
  21482. /**
  21483. * Light type const id of the spot light.
  21484. */
  21485. get: function () {
  21486. return Light._LIGHTTYPEID_SPOTLIGHT;
  21487. },
  21488. enumerable: true,
  21489. configurable: true
  21490. });
  21491. Object.defineProperty(Light, "LIGHTTYPEID_HEMISPHERICLIGHT", {
  21492. /**
  21493. * Light type const id of the hemispheric light.
  21494. */
  21495. get: function () {
  21496. return Light._LIGHTTYPEID_HEMISPHERICLIGHT;
  21497. },
  21498. enumerable: true,
  21499. configurable: true
  21500. });
  21501. Object.defineProperty(Light.prototype, "intensityMode", {
  21502. /**
  21503. * Gets the photometric scale used to interpret the intensity.
  21504. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  21505. */
  21506. get: function () {
  21507. return this._intensityMode;
  21508. },
  21509. /**
  21510. * Sets the photometric scale used to interpret the intensity.
  21511. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  21512. */
  21513. set: function (value) {
  21514. this._intensityMode = value;
  21515. this._computePhotometricScale();
  21516. },
  21517. enumerable: true,
  21518. configurable: true
  21519. });
  21520. ;
  21521. ;
  21522. Object.defineProperty(Light.prototype, "radius", {
  21523. /**
  21524. * Gets the light radius used by PBR Materials to simulate soft area lights.
  21525. */
  21526. get: function () {
  21527. return this._radius;
  21528. },
  21529. /**
  21530. * sets the light radius used by PBR Materials to simulate soft area lights.
  21531. */
  21532. set: function (value) {
  21533. this._radius = value;
  21534. this._computePhotometricScale();
  21535. },
  21536. enumerable: true,
  21537. configurable: true
  21538. });
  21539. ;
  21540. ;
  21541. Object.defineProperty(Light.prototype, "shadowEnabled", {
  21542. /**
  21543. * Gets wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
  21544. * the current shadow generator.
  21545. */
  21546. get: function () {
  21547. return this._shadowEnabled;
  21548. },
  21549. /**
  21550. * Sets wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
  21551. * the current shadow generator.
  21552. */
  21553. set: function (value) {
  21554. if (this._shadowEnabled === value) {
  21555. return;
  21556. }
  21557. this._shadowEnabled = value;
  21558. this._markMeshesAsLightDirty();
  21559. },
  21560. enumerable: true,
  21561. configurable: true
  21562. });
  21563. Object.defineProperty(Light.prototype, "includedOnlyMeshes", {
  21564. /**
  21565. * Gets the only meshes impacted by this light.
  21566. */
  21567. get: function () {
  21568. return this._includedOnlyMeshes;
  21569. },
  21570. /**
  21571. * Sets the only meshes impacted by this light.
  21572. */
  21573. set: function (value) {
  21574. this._includedOnlyMeshes = value;
  21575. this._hookArrayForIncludedOnly(value);
  21576. },
  21577. enumerable: true,
  21578. configurable: true
  21579. });
  21580. Object.defineProperty(Light.prototype, "excludedMeshes", {
  21581. /**
  21582. * Gets the meshes not impacted by this light.
  21583. */
  21584. get: function () {
  21585. return this._excludedMeshes;
  21586. },
  21587. /**
  21588. * Sets the meshes not impacted by this light.
  21589. */
  21590. set: function (value) {
  21591. this._excludedMeshes = value;
  21592. this._hookArrayForExcluded(value);
  21593. },
  21594. enumerable: true,
  21595. configurable: true
  21596. });
  21597. Object.defineProperty(Light.prototype, "excludeWithLayerMask", {
  21598. /**
  21599. * Gets the layer id use to find what meshes are not impacted by the light.
  21600. * Inactive if 0
  21601. */
  21602. get: function () {
  21603. return this._excludeWithLayerMask;
  21604. },
  21605. /**
  21606. * Sets the layer id use to find what meshes are not impacted by the light.
  21607. * Inactive if 0
  21608. */
  21609. set: function (value) {
  21610. this._excludeWithLayerMask = value;
  21611. this._resyncMeshes();
  21612. },
  21613. enumerable: true,
  21614. configurable: true
  21615. });
  21616. Object.defineProperty(Light.prototype, "includeOnlyWithLayerMask", {
  21617. /**
  21618. * Gets the layer id use to find what meshes are impacted by the light.
  21619. * Inactive if 0
  21620. */
  21621. get: function () {
  21622. return this._includeOnlyWithLayerMask;
  21623. },
  21624. /**
  21625. * Sets the layer id use to find what meshes are impacted by the light.
  21626. * Inactive if 0
  21627. */
  21628. set: function (value) {
  21629. this._includeOnlyWithLayerMask = value;
  21630. this._resyncMeshes();
  21631. },
  21632. enumerable: true,
  21633. configurable: true
  21634. });
  21635. Object.defineProperty(Light.prototype, "lightmapMode", {
  21636. /**
  21637. * Gets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  21638. */
  21639. get: function () {
  21640. return this._lightmapMode;
  21641. },
  21642. /**
  21643. * Sets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  21644. */
  21645. set: function (value) {
  21646. if (this._lightmapMode === value) {
  21647. return;
  21648. }
  21649. this._lightmapMode = value;
  21650. this._markMeshesAsLightDirty();
  21651. },
  21652. enumerable: true,
  21653. configurable: true
  21654. });
  21655. /**
  21656. * Returns the string "Light".
  21657. * @returns the class name
  21658. */
  21659. Light.prototype.getClassName = function () {
  21660. return "Light";
  21661. };
  21662. /**
  21663. * Converts the light information to a readable string for debug purpose.
  21664. * @param fullDetails Supports for multiple levels of logging within scene loading
  21665. * @returns the human readable light info
  21666. */
  21667. Light.prototype.toString = function (fullDetails) {
  21668. var ret = "Name: " + this.name;
  21669. ret += ", type: " + (["Point", "Directional", "Spot", "Hemispheric"])[this.getTypeID()];
  21670. if (this.animations) {
  21671. for (var i = 0; i < this.animations.length; i++) {
  21672. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  21673. }
  21674. }
  21675. if (fullDetails) {
  21676. }
  21677. return ret;
  21678. };
  21679. /**
  21680. * Set the enabled state of this node.
  21681. * @param value - the new enabled state
  21682. */
  21683. Light.prototype.setEnabled = function (value) {
  21684. _super.prototype.setEnabled.call(this, value);
  21685. this._resyncMeshes();
  21686. };
  21687. /**
  21688. * Returns the Light associated shadow generator if any.
  21689. * @return the associated shadow generator.
  21690. */
  21691. Light.prototype.getShadowGenerator = function () {
  21692. return this._shadowGenerator;
  21693. };
  21694. /**
  21695. * Returns a Vector3, the absolute light position in the World.
  21696. * @returns the world space position of the light
  21697. */
  21698. Light.prototype.getAbsolutePosition = function () {
  21699. return BABYLON.Vector3.Zero();
  21700. };
  21701. /**
  21702. * Specifies if the light will affect the passed mesh.
  21703. * @param mesh The mesh to test against the light
  21704. * @return true the mesh is affected otherwise, false.
  21705. */
  21706. Light.prototype.canAffectMesh = function (mesh) {
  21707. if (!mesh) {
  21708. return true;
  21709. }
  21710. if (this.includedOnlyMeshes && this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  21711. return false;
  21712. }
  21713. if (this.excludedMeshes && this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  21714. return false;
  21715. }
  21716. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  21717. return false;
  21718. }
  21719. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  21720. return false;
  21721. }
  21722. return true;
  21723. };
  21724. /**
  21725. * Computes and Returns the light World matrix.
  21726. * @returns the world matrix
  21727. */
  21728. Light.prototype.getWorldMatrix = function () {
  21729. this._currentRenderId = this.getScene().getRenderId();
  21730. this._childRenderId = this._currentRenderId;
  21731. var worldMatrix = this._getWorldMatrix();
  21732. if (this.parent && this.parent.getWorldMatrix) {
  21733. if (!this._parentedWorldMatrix) {
  21734. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  21735. }
  21736. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  21737. this._markSyncedWithParent();
  21738. return this._parentedWorldMatrix;
  21739. }
  21740. return worldMatrix;
  21741. };
  21742. /**
  21743. * Sort function to order lights for rendering.
  21744. * @param a First Light object to compare to second.
  21745. * @param b Second Light object to compare first.
  21746. * @return -1 to reduce's a's index relative to be, 0 for no change, 1 to increase a's index relative to b.
  21747. */
  21748. Light.CompareLightsPriority = function (a, b) {
  21749. //shadow-casting lights have priority over non-shadow-casting lights
  21750. //the renderPrioirty is a secondary sort criterion
  21751. if (a.shadowEnabled !== b.shadowEnabled) {
  21752. return (b.shadowEnabled ? 1 : 0) - (a.shadowEnabled ? 1 : 0);
  21753. }
  21754. return b.renderPriority - a.renderPriority;
  21755. };
  21756. /**
  21757. * Releases resources associated with this node.
  21758. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  21759. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  21760. */
  21761. Light.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  21762. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  21763. if (this._shadowGenerator) {
  21764. this._shadowGenerator.dispose();
  21765. this._shadowGenerator = null;
  21766. }
  21767. // Animations
  21768. this.getScene().stopAnimation(this);
  21769. // Remove from meshes
  21770. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  21771. var mesh = _a[_i];
  21772. mesh._removeLightSource(this);
  21773. }
  21774. this._uniformBuffer.dispose();
  21775. // Remove from scene
  21776. this.getScene().removeLight(this);
  21777. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  21778. };
  21779. /**
  21780. * Returns the light type ID (integer).
  21781. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  21782. */
  21783. Light.prototype.getTypeID = function () {
  21784. return 0;
  21785. };
  21786. /**
  21787. * Returns the intensity scaled by the Photometric Scale according to the light type and intensity mode.
  21788. * @returns the scaled intensity in intensity mode unit
  21789. */
  21790. Light.prototype.getScaledIntensity = function () {
  21791. return this._photometricScale * this.intensity;
  21792. };
  21793. /**
  21794. * Returns a new Light object, named "name", from the current one.
  21795. * @param name The name of the cloned light
  21796. * @returns the new created light
  21797. */
  21798. Light.prototype.clone = function (name) {
  21799. var constructor = Light.GetConstructorFromName(this.getTypeID(), name, this.getScene());
  21800. if (!constructor) {
  21801. return null;
  21802. }
  21803. return BABYLON.SerializationHelper.Clone(constructor, this);
  21804. };
  21805. /**
  21806. * Serializes the current light into a Serialization object.
  21807. * @returns the serialized object.
  21808. */
  21809. Light.prototype.serialize = function () {
  21810. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  21811. // Type
  21812. serializationObject.type = this.getTypeID();
  21813. // Parent
  21814. if (this.parent) {
  21815. serializationObject.parentId = this.parent.id;
  21816. }
  21817. // Inclusion / exclusions
  21818. if (this.excludedMeshes.length > 0) {
  21819. serializationObject.excludedMeshesIds = [];
  21820. this.excludedMeshes.forEach(function (mesh) {
  21821. serializationObject.excludedMeshesIds.push(mesh.id);
  21822. });
  21823. }
  21824. if (this.includedOnlyMeshes.length > 0) {
  21825. serializationObject.includedOnlyMeshesIds = [];
  21826. this.includedOnlyMeshes.forEach(function (mesh) {
  21827. serializationObject.includedOnlyMeshesIds.push(mesh.id);
  21828. });
  21829. }
  21830. // Animations
  21831. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  21832. serializationObject.ranges = this.serializeAnimationRanges();
  21833. return serializationObject;
  21834. };
  21835. /**
  21836. * Creates a new typed light from the passed type (integer) : point light = 0, directional light = 1, spot light = 2, hemispheric light = 3.
  21837. * This new light is named "name" and added to the passed scene.
  21838. * @param type Type according to the types available in Light.LIGHTTYPEID_x
  21839. * @param name The friendly name of the light
  21840. * @param scene The scene the new light will belong to
  21841. * @returns the constructor function
  21842. */
  21843. Light.GetConstructorFromName = function (type, name, scene) {
  21844. switch (type) {
  21845. case 0:
  21846. return function () { return new BABYLON.PointLight(name, BABYLON.Vector3.Zero(), scene); };
  21847. case 1:
  21848. return function () { return new BABYLON.DirectionalLight(name, BABYLON.Vector3.Zero(), scene); };
  21849. case 2:
  21850. return function () { return new BABYLON.SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, scene); };
  21851. case 3:
  21852. return function () { return new BABYLON.HemisphericLight(name, BABYLON.Vector3.Zero(), scene); };
  21853. }
  21854. return null;
  21855. };
  21856. /**
  21857. * Parses the passed "parsedLight" and returns a new instanced Light from this parsing.
  21858. * @param parsedLight The JSON representation of the light
  21859. * @param scene The scene to create the parsed light in
  21860. * @returns the created light after parsing
  21861. */
  21862. Light.Parse = function (parsedLight, scene) {
  21863. var constructor = Light.GetConstructorFromName(parsedLight.type, parsedLight.name, scene);
  21864. if (!constructor) {
  21865. return null;
  21866. }
  21867. var light = BABYLON.SerializationHelper.Parse(constructor, parsedLight, scene);
  21868. // Inclusion / exclusions
  21869. if (parsedLight.excludedMeshesIds) {
  21870. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  21871. }
  21872. if (parsedLight.includedOnlyMeshesIds) {
  21873. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  21874. }
  21875. // Parent
  21876. if (parsedLight.parentId) {
  21877. light._waitingParentId = parsedLight.parentId;
  21878. }
  21879. // Animations
  21880. if (parsedLight.animations) {
  21881. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  21882. var parsedAnimation = parsedLight.animations[animationIndex];
  21883. light.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  21884. }
  21885. BABYLON.Node.ParseAnimationRanges(light, parsedLight, scene);
  21886. }
  21887. if (parsedLight.autoAnimate) {
  21888. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, parsedLight.autoAnimateSpeed || 1.0);
  21889. }
  21890. return light;
  21891. };
  21892. Light.prototype._hookArrayForExcluded = function (array) {
  21893. var _this = this;
  21894. var oldPush = array.push;
  21895. array.push = function () {
  21896. var items = [];
  21897. for (var _i = 0; _i < arguments.length; _i++) {
  21898. items[_i] = arguments[_i];
  21899. }
  21900. var result = oldPush.apply(array, items);
  21901. for (var _a = 0, items_1 = items; _a < items_1.length; _a++) {
  21902. var item = items_1[_a];
  21903. item._resyncLighSource(_this);
  21904. }
  21905. return result;
  21906. };
  21907. var oldSplice = array.splice;
  21908. array.splice = function (index, deleteCount) {
  21909. var deleted = oldSplice.apply(array, [index, deleteCount]);
  21910. for (var _i = 0, deleted_1 = deleted; _i < deleted_1.length; _i++) {
  21911. var item = deleted_1[_i];
  21912. item._resyncLighSource(_this);
  21913. }
  21914. return deleted;
  21915. };
  21916. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  21917. var item = array_1[_i];
  21918. item._resyncLighSource(this);
  21919. }
  21920. };
  21921. Light.prototype._hookArrayForIncludedOnly = function (array) {
  21922. var _this = this;
  21923. var oldPush = array.push;
  21924. array.push = function () {
  21925. var items = [];
  21926. for (var _i = 0; _i < arguments.length; _i++) {
  21927. items[_i] = arguments[_i];
  21928. }
  21929. var result = oldPush.apply(array, items);
  21930. _this._resyncMeshes();
  21931. return result;
  21932. };
  21933. var oldSplice = array.splice;
  21934. array.splice = function (index, deleteCount) {
  21935. var deleted = oldSplice.apply(array, [index, deleteCount]);
  21936. _this._resyncMeshes();
  21937. return deleted;
  21938. };
  21939. this._resyncMeshes();
  21940. };
  21941. Light.prototype._resyncMeshes = function () {
  21942. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  21943. var mesh = _a[_i];
  21944. mesh._resyncLighSource(this);
  21945. }
  21946. };
  21947. /**
  21948. * Forces the meshes to update their light related information in their rendering used effects
  21949. * @hidden Internal Use Only
  21950. */
  21951. Light.prototype._markMeshesAsLightDirty = function () {
  21952. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  21953. var mesh = _a[_i];
  21954. if (mesh._lightSources.indexOf(this) !== -1) {
  21955. mesh._markSubMeshesAsLightDirty();
  21956. }
  21957. }
  21958. };
  21959. /**
  21960. * Recomputes the cached photometric scale if needed.
  21961. */
  21962. Light.prototype._computePhotometricScale = function () {
  21963. this._photometricScale = this._getPhotometricScale();
  21964. this.getScene().resetCachedMaterial();
  21965. };
  21966. /**
  21967. * Returns the Photometric Scale according to the light type and intensity mode.
  21968. */
  21969. Light.prototype._getPhotometricScale = function () {
  21970. var photometricScale = 0.0;
  21971. var lightTypeID = this.getTypeID();
  21972. //get photometric mode
  21973. var photometricMode = this.intensityMode;
  21974. if (photometricMode === Light.INTENSITYMODE_AUTOMATIC) {
  21975. if (lightTypeID === Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  21976. photometricMode = Light.INTENSITYMODE_ILLUMINANCE;
  21977. }
  21978. else {
  21979. photometricMode = Light.INTENSITYMODE_LUMINOUSINTENSITY;
  21980. }
  21981. }
  21982. //compute photometric scale
  21983. switch (lightTypeID) {
  21984. case Light.LIGHTTYPEID_POINTLIGHT:
  21985. case Light.LIGHTTYPEID_SPOTLIGHT:
  21986. switch (photometricMode) {
  21987. case Light.INTENSITYMODE_LUMINOUSPOWER:
  21988. photometricScale = 1.0 / (4.0 * Math.PI);
  21989. break;
  21990. case Light.INTENSITYMODE_LUMINOUSINTENSITY:
  21991. photometricScale = 1.0;
  21992. break;
  21993. case Light.INTENSITYMODE_LUMINANCE:
  21994. photometricScale = this.radius * this.radius;
  21995. break;
  21996. }
  21997. break;
  21998. case Light.LIGHTTYPEID_DIRECTIONALLIGHT:
  21999. switch (photometricMode) {
  22000. case Light.INTENSITYMODE_ILLUMINANCE:
  22001. photometricScale = 1.0;
  22002. break;
  22003. case Light.INTENSITYMODE_LUMINANCE:
  22004. // When radius (and therefore solid angle) is non-zero a directional lights brightness can be specified via central (peak) luminance.
  22005. // For a directional light the 'radius' defines the angular radius (in radians) rather than world-space radius (e.g. in metres).
  22006. var apexAngleRadians = this.radius;
  22007. // Impose a minimum light angular size to avoid the light becoming an infinitely small angular light source (i.e. a dirac delta function).
  22008. apexAngleRadians = Math.max(apexAngleRadians, 0.001);
  22009. var solidAngle = 2.0 * Math.PI * (1.0 - Math.cos(apexAngleRadians));
  22010. photometricScale = solidAngle;
  22011. break;
  22012. }
  22013. break;
  22014. case Light.LIGHTTYPEID_HEMISPHERICLIGHT:
  22015. // No fall off in hemisperic light.
  22016. photometricScale = 1.0;
  22017. break;
  22018. }
  22019. return photometricScale;
  22020. };
  22021. /**
  22022. * Reorder the light in the scene according to their defined priority.
  22023. * @hidden Internal Use Only
  22024. */
  22025. Light.prototype._reorderLightsInScene = function () {
  22026. var scene = this.getScene();
  22027. if (this._renderPriority != 0) {
  22028. scene.requireLightSorting = true;
  22029. }
  22030. this.getScene().sortLightsByPriority();
  22031. };
  22032. //lightmapMode Consts
  22033. Light._LIGHTMAP_DEFAULT = 0;
  22034. Light._LIGHTMAP_SPECULAR = 1;
  22035. Light._LIGHTMAP_SHADOWSONLY = 2;
  22036. // Intensity Mode Consts
  22037. Light._INTENSITYMODE_AUTOMATIC = 0;
  22038. Light._INTENSITYMODE_LUMINOUSPOWER = 1;
  22039. Light._INTENSITYMODE_LUMINOUSINTENSITY = 2;
  22040. Light._INTENSITYMODE_ILLUMINANCE = 3;
  22041. Light._INTENSITYMODE_LUMINANCE = 4;
  22042. // Light types ids const.
  22043. Light._LIGHTTYPEID_POINTLIGHT = 0;
  22044. Light._LIGHTTYPEID_DIRECTIONALLIGHT = 1;
  22045. Light._LIGHTTYPEID_SPOTLIGHT = 2;
  22046. Light._LIGHTTYPEID_HEMISPHERICLIGHT = 3;
  22047. __decorate([
  22048. BABYLON.serializeAsColor3()
  22049. ], Light.prototype, "diffuse", void 0);
  22050. __decorate([
  22051. BABYLON.serializeAsColor3()
  22052. ], Light.prototype, "specular", void 0);
  22053. __decorate([
  22054. BABYLON.serialize()
  22055. ], Light.prototype, "intensity", void 0);
  22056. __decorate([
  22057. BABYLON.serialize()
  22058. ], Light.prototype, "range", void 0);
  22059. __decorate([
  22060. BABYLON.serialize()
  22061. ], Light.prototype, "intensityMode", null);
  22062. __decorate([
  22063. BABYLON.serialize()
  22064. ], Light.prototype, "radius", null);
  22065. __decorate([
  22066. BABYLON.serialize()
  22067. ], Light.prototype, "_renderPriority", void 0);
  22068. __decorate([
  22069. BABYLON.expandToProperty("_reorderLightsInScene")
  22070. ], Light.prototype, "renderPriority", void 0);
  22071. __decorate([
  22072. BABYLON.serialize("shadowEnabled")
  22073. ], Light.prototype, "_shadowEnabled", void 0);
  22074. __decorate([
  22075. BABYLON.serialize("excludeWithLayerMask")
  22076. ], Light.prototype, "_excludeWithLayerMask", void 0);
  22077. __decorate([
  22078. BABYLON.serialize("includeOnlyWithLayerMask")
  22079. ], Light.prototype, "_includeOnlyWithLayerMask", void 0);
  22080. __decorate([
  22081. BABYLON.serialize("lightmapMode")
  22082. ], Light.prototype, "_lightmapMode", void 0);
  22083. return Light;
  22084. }(BABYLON.Node));
  22085. BABYLON.Light = Light;
  22086. })(BABYLON || (BABYLON = {}));
  22087. //# sourceMappingURL=babylon.light.js.map
  22088. var BABYLON;
  22089. (function (BABYLON) {
  22090. var Camera = /** @class */ (function (_super) {
  22091. __extends(Camera, _super);
  22092. function Camera(name, position, scene, setActiveOnSceneIfNoneActive) {
  22093. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  22094. var _this = _super.call(this, name, scene) || this;
  22095. /**
  22096. * The vector the camera should consider as up.
  22097. * (default is Vector3(0, 1, 0) aka Vector3.Up())
  22098. */
  22099. _this.upVector = BABYLON.Vector3.Up();
  22100. _this.orthoLeft = null;
  22101. _this.orthoRight = null;
  22102. _this.orthoBottom = null;
  22103. _this.orthoTop = null;
  22104. /**
  22105. * FOV is set in Radians. (default is 0.8)
  22106. */
  22107. _this.fov = 0.8;
  22108. _this.minZ = 1;
  22109. _this.maxZ = 10000.0;
  22110. _this.inertia = 0.9;
  22111. _this.mode = Camera.PERSPECTIVE_CAMERA;
  22112. _this.isIntermediate = false;
  22113. _this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  22114. /**
  22115. * Restricts the camera to viewing objects with the same layerMask.
  22116. * A camera with a layerMask of 1 will render mesh.layerMask & camera.layerMask!== 0
  22117. */
  22118. _this.layerMask = 0x0FFFFFFF;
  22119. /**
  22120. * fovMode sets the camera frustum bounds to the viewport bounds. (default is FOVMODE_VERTICAL_FIXED)
  22121. */
  22122. _this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  22123. // Camera rig members
  22124. _this.cameraRigMode = Camera.RIG_MODE_NONE;
  22125. _this._rigCameras = new Array();
  22126. _this._webvrViewMatrix = BABYLON.Matrix.Identity();
  22127. _this._skipRendering = false;
  22128. _this.customRenderTargets = new Array();
  22129. // Observables
  22130. _this.onViewMatrixChangedObservable = new BABYLON.Observable();
  22131. _this.onProjectionMatrixChangedObservable = new BABYLON.Observable();
  22132. _this.onAfterCheckInputsObservable = new BABYLON.Observable();
  22133. _this.onRestoreStateObservable = new BABYLON.Observable();
  22134. // Cache
  22135. _this._computedViewMatrix = BABYLON.Matrix.Identity();
  22136. _this._projectionMatrix = new BABYLON.Matrix();
  22137. _this._doNotComputeProjectionMatrix = false;
  22138. _this._worldMatrix = BABYLON.Matrix.Identity();
  22139. _this._postProcesses = new Array();
  22140. _this._transformMatrix = BABYLON.Matrix.Zero();
  22141. _this._activeMeshes = new BABYLON.SmartArray(256);
  22142. _this._globalPosition = BABYLON.Vector3.Zero();
  22143. _this._refreshFrustumPlanes = true;
  22144. _this.getScene().addCamera(_this);
  22145. if (setActiveOnSceneIfNoneActive && !_this.getScene().activeCamera) {
  22146. _this.getScene().activeCamera = _this;
  22147. }
  22148. _this.position = position;
  22149. return _this;
  22150. }
  22151. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  22152. get: function () {
  22153. return Camera._PERSPECTIVE_CAMERA;
  22154. },
  22155. enumerable: true,
  22156. configurable: true
  22157. });
  22158. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  22159. get: function () {
  22160. return Camera._ORTHOGRAPHIC_CAMERA;
  22161. },
  22162. enumerable: true,
  22163. configurable: true
  22164. });
  22165. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  22166. /**
  22167. * This is the default FOV mode for perspective cameras.
  22168. * This setting aligns the upper and lower bounds of the viewport to the upper and lower bounds of the camera frustum.
  22169. *
  22170. */
  22171. get: function () {
  22172. return Camera._FOVMODE_VERTICAL_FIXED;
  22173. },
  22174. enumerable: true,
  22175. configurable: true
  22176. });
  22177. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  22178. /**
  22179. * This setting aligns the left and right bounds of the viewport to the left and right bounds of the camera frustum.
  22180. *
  22181. */
  22182. get: function () {
  22183. return Camera._FOVMODE_HORIZONTAL_FIXED;
  22184. },
  22185. enumerable: true,
  22186. configurable: true
  22187. });
  22188. Object.defineProperty(Camera, "RIG_MODE_NONE", {
  22189. get: function () {
  22190. return Camera._RIG_MODE_NONE;
  22191. },
  22192. enumerable: true,
  22193. configurable: true
  22194. });
  22195. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_ANAGLYPH", {
  22196. get: function () {
  22197. return Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH;
  22198. },
  22199. enumerable: true,
  22200. configurable: true
  22201. });
  22202. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL", {
  22203. get: function () {
  22204. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL;
  22205. },
  22206. enumerable: true,
  22207. configurable: true
  22208. });
  22209. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED", {
  22210. get: function () {
  22211. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  22212. },
  22213. enumerable: true,
  22214. configurable: true
  22215. });
  22216. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_OVERUNDER", {
  22217. get: function () {
  22218. return Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER;
  22219. },
  22220. enumerable: true,
  22221. configurable: true
  22222. });
  22223. Object.defineProperty(Camera, "RIG_MODE_VR", {
  22224. get: function () {
  22225. return Camera._RIG_MODE_VR;
  22226. },
  22227. enumerable: true,
  22228. configurable: true
  22229. });
  22230. Object.defineProperty(Camera, "RIG_MODE_WEBVR", {
  22231. get: function () {
  22232. return Camera._RIG_MODE_WEBVR;
  22233. },
  22234. enumerable: true,
  22235. configurable: true
  22236. });
  22237. /**
  22238. * Store current camera state (fov, position, etc..)
  22239. */
  22240. Camera.prototype.storeState = function () {
  22241. this._stateStored = true;
  22242. this._storedFov = this.fov;
  22243. return this;
  22244. };
  22245. /**
  22246. * Restores the camera state values if it has been stored. You must call storeState() first
  22247. */
  22248. Camera.prototype._restoreStateValues = function () {
  22249. if (!this._stateStored) {
  22250. return false;
  22251. }
  22252. this.fov = this._storedFov;
  22253. return true;
  22254. };
  22255. /**
  22256. * Restored camera state. You must call storeState() first
  22257. */
  22258. Camera.prototype.restoreState = function () {
  22259. if (this._restoreStateValues()) {
  22260. this.onRestoreStateObservable.notifyObservers(this);
  22261. return true;
  22262. }
  22263. return false;
  22264. };
  22265. Camera.prototype.getClassName = function () {
  22266. return "Camera";
  22267. };
  22268. /**
  22269. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  22270. */
  22271. Camera.prototype.toString = function (fullDetails) {
  22272. var ret = "Name: " + this.name;
  22273. ret += ", type: " + this.getClassName();
  22274. if (this.animations) {
  22275. for (var i = 0; i < this.animations.length; i++) {
  22276. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  22277. }
  22278. }
  22279. if (fullDetails) {
  22280. }
  22281. return ret;
  22282. };
  22283. Object.defineProperty(Camera.prototype, "globalPosition", {
  22284. get: function () {
  22285. return this._globalPosition;
  22286. },
  22287. enumerable: true,
  22288. configurable: true
  22289. });
  22290. Camera.prototype.getActiveMeshes = function () {
  22291. return this._activeMeshes;
  22292. };
  22293. Camera.prototype.isActiveMesh = function (mesh) {
  22294. return (this._activeMeshes.indexOf(mesh) !== -1);
  22295. };
  22296. /**
  22297. * Is this camera ready to be used/rendered
  22298. * @param completeCheck defines if a complete check (including post processes) has to be done (false by default)
  22299. * @return true if the camera is ready
  22300. */
  22301. Camera.prototype.isReady = function (completeCheck) {
  22302. if (completeCheck === void 0) { completeCheck = false; }
  22303. if (completeCheck) {
  22304. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  22305. var pp = _a[_i];
  22306. if (pp && !pp.isReady()) {
  22307. return false;
  22308. }
  22309. }
  22310. }
  22311. return _super.prototype.isReady.call(this, completeCheck);
  22312. };
  22313. //Cache
  22314. Camera.prototype._initCache = function () {
  22315. _super.prototype._initCache.call(this);
  22316. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  22317. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  22318. this._cache.mode = undefined;
  22319. this._cache.minZ = undefined;
  22320. this._cache.maxZ = undefined;
  22321. this._cache.fov = undefined;
  22322. this._cache.fovMode = undefined;
  22323. this._cache.aspectRatio = undefined;
  22324. this._cache.orthoLeft = undefined;
  22325. this._cache.orthoRight = undefined;
  22326. this._cache.orthoBottom = undefined;
  22327. this._cache.orthoTop = undefined;
  22328. this._cache.renderWidth = undefined;
  22329. this._cache.renderHeight = undefined;
  22330. };
  22331. Camera.prototype._updateCache = function (ignoreParentClass) {
  22332. if (!ignoreParentClass) {
  22333. _super.prototype._updateCache.call(this);
  22334. }
  22335. this._cache.position.copyFrom(this.position);
  22336. this._cache.upVector.copyFrom(this.upVector);
  22337. };
  22338. // Synchronized
  22339. Camera.prototype._isSynchronized = function () {
  22340. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  22341. };
  22342. Camera.prototype._isSynchronizedViewMatrix = function () {
  22343. if (!_super.prototype._isSynchronized.call(this))
  22344. return false;
  22345. return this._cache.position.equals(this.position)
  22346. && this._cache.upVector.equals(this.upVector)
  22347. && this.isSynchronizedWithParent();
  22348. };
  22349. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  22350. var check = this._cache.mode === this.mode
  22351. && this._cache.minZ === this.minZ
  22352. && this._cache.maxZ === this.maxZ;
  22353. if (!check) {
  22354. return false;
  22355. }
  22356. var engine = this.getEngine();
  22357. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  22358. check = this._cache.fov === this.fov
  22359. && this._cache.fovMode === this.fovMode
  22360. && this._cache.aspectRatio === engine.getAspectRatio(this);
  22361. }
  22362. else {
  22363. check = this._cache.orthoLeft === this.orthoLeft
  22364. && this._cache.orthoRight === this.orthoRight
  22365. && this._cache.orthoBottom === this.orthoBottom
  22366. && this._cache.orthoTop === this.orthoTop
  22367. && this._cache.renderWidth === engine.getRenderWidth()
  22368. && this._cache.renderHeight === engine.getRenderHeight();
  22369. }
  22370. return check;
  22371. };
  22372. // Controls
  22373. Camera.prototype.attachControl = function (element, noPreventDefault) {
  22374. };
  22375. Camera.prototype.detachControl = function (element) {
  22376. };
  22377. Camera.prototype.update = function () {
  22378. this._checkInputs();
  22379. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  22380. this._updateRigCameras();
  22381. }
  22382. };
  22383. Camera.prototype._checkInputs = function () {
  22384. this.onAfterCheckInputsObservable.notifyObservers(this);
  22385. };
  22386. Object.defineProperty(Camera.prototype, "rigCameras", {
  22387. get: function () {
  22388. return this._rigCameras;
  22389. },
  22390. enumerable: true,
  22391. configurable: true
  22392. });
  22393. Object.defineProperty(Camera.prototype, "rigPostProcess", {
  22394. get: function () {
  22395. return this._rigPostProcess;
  22396. },
  22397. enumerable: true,
  22398. configurable: true
  22399. });
  22400. /**
  22401. * Internal, gets the first post proces.
  22402. * @returns the first post process to be run on this camera.
  22403. */
  22404. Camera.prototype._getFirstPostProcess = function () {
  22405. for (var ppIndex = 0; ppIndex < this._postProcesses.length; ppIndex++) {
  22406. if (this._postProcesses[ppIndex] !== null) {
  22407. return this._postProcesses[ppIndex];
  22408. }
  22409. }
  22410. return null;
  22411. };
  22412. Camera.prototype._cascadePostProcessesToRigCams = function () {
  22413. // invalidate framebuffer
  22414. var firstPostProcess = this._getFirstPostProcess();
  22415. if (firstPostProcess) {
  22416. firstPostProcess.markTextureDirty();
  22417. }
  22418. // glue the rigPostProcess to the end of the user postprocesses & assign to each sub-camera
  22419. for (var i = 0, len = this._rigCameras.length; i < len; i++) {
  22420. var cam = this._rigCameras[i];
  22421. var rigPostProcess = cam._rigPostProcess;
  22422. // for VR rig, there does not have to be a post process
  22423. if (rigPostProcess) {
  22424. var isPass = rigPostProcess instanceof BABYLON.PassPostProcess;
  22425. if (isPass) {
  22426. // any rig which has a PassPostProcess for rig[0], cannot be isIntermediate when there are also user postProcesses
  22427. cam.isIntermediate = this._postProcesses.length === 0;
  22428. }
  22429. cam._postProcesses = this._postProcesses.slice(0).concat(rigPostProcess);
  22430. rigPostProcess.markTextureDirty();
  22431. }
  22432. else {
  22433. cam._postProcesses = this._postProcesses.slice(0);
  22434. }
  22435. }
  22436. };
  22437. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  22438. if (insertAt === void 0) { insertAt = null; }
  22439. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  22440. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  22441. return 0;
  22442. }
  22443. if (insertAt == null || insertAt < 0) {
  22444. this._postProcesses.push(postProcess);
  22445. }
  22446. else if (this._postProcesses[insertAt] === null) {
  22447. this._postProcesses[insertAt] = postProcess;
  22448. }
  22449. else {
  22450. this._postProcesses.splice(insertAt, 0, postProcess);
  22451. }
  22452. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  22453. return this._postProcesses.indexOf(postProcess);
  22454. };
  22455. Camera.prototype.detachPostProcess = function (postProcess) {
  22456. var idx = this._postProcesses.indexOf(postProcess);
  22457. if (idx !== -1) {
  22458. this._postProcesses[idx] = null;
  22459. }
  22460. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  22461. };
  22462. Camera.prototype.getWorldMatrix = function () {
  22463. if (this._isSynchronizedViewMatrix()) {
  22464. return this._worldMatrix;
  22465. }
  22466. // Getting the the view matrix will also compute the world matrix.
  22467. this.getViewMatrix();
  22468. return this._worldMatrix;
  22469. };
  22470. Camera.prototype._getViewMatrix = function () {
  22471. return BABYLON.Matrix.Identity();
  22472. };
  22473. Camera.prototype.getViewMatrix = function (force) {
  22474. if (!force && this._isSynchronizedViewMatrix()) {
  22475. return this._computedViewMatrix;
  22476. }
  22477. this.updateCache();
  22478. this._computedViewMatrix = this._getViewMatrix();
  22479. this._currentRenderId = this.getScene().getRenderId();
  22480. this._childRenderId = this._currentRenderId;
  22481. this._refreshFrustumPlanes = true;
  22482. if (this._cameraRigParams && this._cameraRigParams.vrPreViewMatrix) {
  22483. this._computedViewMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._computedViewMatrix);
  22484. }
  22485. this.onViewMatrixChangedObservable.notifyObservers(this);
  22486. this._computedViewMatrix.invertToRef(this._worldMatrix);
  22487. return this._computedViewMatrix;
  22488. };
  22489. Camera.prototype.freezeProjectionMatrix = function (projection) {
  22490. this._doNotComputeProjectionMatrix = true;
  22491. if (projection !== undefined) {
  22492. this._projectionMatrix = projection;
  22493. }
  22494. };
  22495. ;
  22496. Camera.prototype.unfreezeProjectionMatrix = function () {
  22497. this._doNotComputeProjectionMatrix = false;
  22498. };
  22499. ;
  22500. Camera.prototype.getProjectionMatrix = function (force) {
  22501. if (this._doNotComputeProjectionMatrix || (!force && this._isSynchronizedProjectionMatrix())) {
  22502. return this._projectionMatrix;
  22503. }
  22504. // Cache
  22505. this._cache.mode = this.mode;
  22506. this._cache.minZ = this.minZ;
  22507. this._cache.maxZ = this.maxZ;
  22508. // Matrix
  22509. this._refreshFrustumPlanes = true;
  22510. var engine = this.getEngine();
  22511. var scene = this.getScene();
  22512. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  22513. this._cache.fov = this.fov;
  22514. this._cache.fovMode = this.fovMode;
  22515. this._cache.aspectRatio = engine.getAspectRatio(this);
  22516. if (this.minZ <= 0) {
  22517. this.minZ = 0.1;
  22518. }
  22519. if (scene.useRightHandedSystem) {
  22520. BABYLON.Matrix.PerspectiveFovRHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  22521. }
  22522. else {
  22523. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  22524. }
  22525. }
  22526. else {
  22527. var halfWidth = engine.getRenderWidth() / 2.0;
  22528. var halfHeight = engine.getRenderHeight() / 2.0;
  22529. if (scene.useRightHandedSystem) {
  22530. BABYLON.Matrix.OrthoOffCenterRHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  22531. }
  22532. else {
  22533. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  22534. }
  22535. this._cache.orthoLeft = this.orthoLeft;
  22536. this._cache.orthoRight = this.orthoRight;
  22537. this._cache.orthoBottom = this.orthoBottom;
  22538. this._cache.orthoTop = this.orthoTop;
  22539. this._cache.renderWidth = engine.getRenderWidth();
  22540. this._cache.renderHeight = engine.getRenderHeight();
  22541. }
  22542. this.onProjectionMatrixChangedObservable.notifyObservers(this);
  22543. return this._projectionMatrix;
  22544. };
  22545. Camera.prototype.getTranformationMatrix = function () {
  22546. this._computedViewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  22547. return this._transformMatrix;
  22548. };
  22549. Camera.prototype.updateFrustumPlanes = function () {
  22550. if (!this._refreshFrustumPlanes) {
  22551. return;
  22552. }
  22553. this.getTranformationMatrix();
  22554. if (!this._frustumPlanes) {
  22555. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  22556. }
  22557. else {
  22558. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  22559. }
  22560. this._refreshFrustumPlanes = false;
  22561. };
  22562. Camera.prototype.isInFrustum = function (target) {
  22563. this.updateFrustumPlanes();
  22564. return target.isInFrustum(this._frustumPlanes);
  22565. };
  22566. Camera.prototype.isCompletelyInFrustum = function (target) {
  22567. this.updateFrustumPlanes();
  22568. return target.isCompletelyInFrustum(this._frustumPlanes);
  22569. };
  22570. Camera.prototype.getForwardRay = function (length, transform, origin) {
  22571. if (length === void 0) { length = 100; }
  22572. if (!transform) {
  22573. transform = this.getWorldMatrix();
  22574. }
  22575. if (!origin) {
  22576. origin = this.position;
  22577. }
  22578. var forward = new BABYLON.Vector3(0, 0, 1);
  22579. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, transform);
  22580. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  22581. return new BABYLON.Ray(origin, direction, length);
  22582. };
  22583. /**
  22584. * Releases resources associated with this node.
  22585. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  22586. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  22587. */
  22588. Camera.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  22589. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  22590. // Observables
  22591. this.onViewMatrixChangedObservable.clear();
  22592. this.onProjectionMatrixChangedObservable.clear();
  22593. this.onAfterCheckInputsObservable.clear();
  22594. this.onRestoreStateObservable.clear();
  22595. // Inputs
  22596. if (this.inputs) {
  22597. this.inputs.clear();
  22598. }
  22599. // Animations
  22600. this.getScene().stopAnimation(this);
  22601. // Remove from scene
  22602. this.getScene().removeCamera(this);
  22603. while (this._rigCameras.length > 0) {
  22604. var camera = this._rigCameras.pop();
  22605. if (camera) {
  22606. camera.dispose();
  22607. }
  22608. }
  22609. // Postprocesses
  22610. if (this._rigPostProcess) {
  22611. this._rigPostProcess.dispose(this);
  22612. this._rigPostProcess = null;
  22613. this._postProcesses = [];
  22614. }
  22615. else if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  22616. this._rigPostProcess = null;
  22617. this._postProcesses = [];
  22618. }
  22619. else {
  22620. var i = this._postProcesses.length;
  22621. while (--i >= 0) {
  22622. var postProcess = this._postProcesses[i];
  22623. if (postProcess) {
  22624. postProcess.dispose(this);
  22625. }
  22626. }
  22627. }
  22628. // Render targets
  22629. var i = this.customRenderTargets.length;
  22630. while (--i >= 0) {
  22631. this.customRenderTargets[i].dispose();
  22632. }
  22633. this.customRenderTargets = [];
  22634. // Active Meshes
  22635. this._activeMeshes.dispose();
  22636. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  22637. };
  22638. Object.defineProperty(Camera.prototype, "leftCamera", {
  22639. // ---- Camera rigs section ----
  22640. get: function () {
  22641. if (this._rigCameras.length < 1) {
  22642. return null;
  22643. }
  22644. return this._rigCameras[0];
  22645. },
  22646. enumerable: true,
  22647. configurable: true
  22648. });
  22649. Object.defineProperty(Camera.prototype, "rightCamera", {
  22650. get: function () {
  22651. if (this._rigCameras.length < 2) {
  22652. return null;
  22653. }
  22654. return this._rigCameras[1];
  22655. },
  22656. enumerable: true,
  22657. configurable: true
  22658. });
  22659. Camera.prototype.getLeftTarget = function () {
  22660. if (this._rigCameras.length < 1) {
  22661. return null;
  22662. }
  22663. return this._rigCameras[0].getTarget();
  22664. };
  22665. Camera.prototype.getRightTarget = function () {
  22666. if (this._rigCameras.length < 2) {
  22667. return null;
  22668. }
  22669. return this._rigCameras[1].getTarget();
  22670. };
  22671. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  22672. if (this.cameraRigMode === mode) {
  22673. return;
  22674. }
  22675. while (this._rigCameras.length > 0) {
  22676. var camera = this._rigCameras.pop();
  22677. if (camera) {
  22678. camera.dispose();
  22679. }
  22680. }
  22681. this.cameraRigMode = mode;
  22682. this._cameraRigParams = {};
  22683. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  22684. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  22685. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  22686. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  22687. // create the rig cameras, unless none
  22688. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  22689. var leftCamera = this.createRigCamera(this.name + "_L", 0);
  22690. var rightCamera = this.createRigCamera(this.name + "_R", 1);
  22691. if (leftCamera && rightCamera) {
  22692. this._rigCameras.push(leftCamera);
  22693. this._rigCameras.push(rightCamera);
  22694. }
  22695. }
  22696. switch (this.cameraRigMode) {
  22697. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  22698. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  22699. this._rigCameras[1]._rigPostProcess = new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras);
  22700. break;
  22701. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  22702. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  22703. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  22704. var isStereoscopicHoriz = this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  22705. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  22706. this._rigCameras[1]._rigPostProcess = new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras, isStereoscopicHoriz);
  22707. break;
  22708. case Camera.RIG_MODE_VR:
  22709. var metrics = rigParams.vrCameraMetrics || BABYLON.VRCameraMetrics.GetDefault();
  22710. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  22711. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  22712. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  22713. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  22714. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  22715. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  22716. this._rigCameras[1]._cameraRigParams.vrMetrics = metrics;
  22717. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  22718. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  22719. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  22720. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  22721. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  22722. if (metrics.compensateDistortion) {
  22723. this._rigCameras[0]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics);
  22724. this._rigCameras[1]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics);
  22725. }
  22726. break;
  22727. case Camera.RIG_MODE_WEBVR:
  22728. if (rigParams.vrDisplay) {
  22729. var leftEye = rigParams.vrDisplay.getEyeParameters('left');
  22730. var rightEye = rigParams.vrDisplay.getEyeParameters('right');
  22731. //Left eye
  22732. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  22733. this._rigCameras[0].setCameraRigParameter("left", true);
  22734. //leaving this for future reference
  22735. this._rigCameras[0].setCameraRigParameter("specs", rigParams.specs);
  22736. this._rigCameras[0].setCameraRigParameter("eyeParameters", leftEye);
  22737. this._rigCameras[0].setCameraRigParameter("frameData", rigParams.frameData);
  22738. this._rigCameras[0].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  22739. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  22740. this._rigCameras[0].getProjectionMatrix = this._getWebVRProjectionMatrix;
  22741. this._rigCameras[0].parent = this;
  22742. this._rigCameras[0]._getViewMatrix = this._getWebVRViewMatrix;
  22743. //Right eye
  22744. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  22745. this._rigCameras[1].setCameraRigParameter('eyeParameters', rightEye);
  22746. this._rigCameras[1].setCameraRigParameter("specs", rigParams.specs);
  22747. this._rigCameras[1].setCameraRigParameter("frameData", rigParams.frameData);
  22748. this._rigCameras[1].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  22749. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  22750. this._rigCameras[1].getProjectionMatrix = this._getWebVRProjectionMatrix;
  22751. this._rigCameras[1].parent = this;
  22752. this._rigCameras[1]._getViewMatrix = this._getWebVRViewMatrix;
  22753. if (Camera.UseAlternateWebVRRendering) {
  22754. this._rigCameras[1]._skipRendering = true;
  22755. this._rigCameras[0]._alternateCamera = this._rigCameras[1];
  22756. }
  22757. }
  22758. break;
  22759. }
  22760. this._cascadePostProcessesToRigCams();
  22761. this.update();
  22762. };
  22763. Camera.prototype._getVRProjectionMatrix = function () {
  22764. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  22765. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  22766. return this._projectionMatrix;
  22767. };
  22768. Camera.prototype._updateCameraRotationMatrix = function () {
  22769. //Here for WebVR
  22770. };
  22771. Camera.prototype._updateWebVRCameraRotationMatrix = function () {
  22772. //Here for WebVR
  22773. };
  22774. /**
  22775. * This function MUST be overwritten by the different WebVR cameras available.
  22776. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  22777. */
  22778. Camera.prototype._getWebVRProjectionMatrix = function () {
  22779. return BABYLON.Matrix.Identity();
  22780. };
  22781. /**
  22782. * This function MUST be overwritten by the different WebVR cameras available.
  22783. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  22784. */
  22785. Camera.prototype._getWebVRViewMatrix = function () {
  22786. return BABYLON.Matrix.Identity();
  22787. };
  22788. Camera.prototype.setCameraRigParameter = function (name, value) {
  22789. if (!this._cameraRigParams) {
  22790. this._cameraRigParams = {};
  22791. }
  22792. this._cameraRigParams[name] = value;
  22793. //provisionnally:
  22794. if (name === "interaxialDistance") {
  22795. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  22796. }
  22797. };
  22798. /**
  22799. * needs to be overridden by children so sub has required properties to be copied
  22800. */
  22801. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  22802. return null;
  22803. };
  22804. /**
  22805. * May need to be overridden by children
  22806. */
  22807. Camera.prototype._updateRigCameras = function () {
  22808. for (var i = 0; i < this._rigCameras.length; i++) {
  22809. this._rigCameras[i].minZ = this.minZ;
  22810. this._rigCameras[i].maxZ = this.maxZ;
  22811. this._rigCameras[i].fov = this.fov;
  22812. }
  22813. // only update viewport when ANAGLYPH
  22814. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  22815. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  22816. }
  22817. };
  22818. Camera.prototype._setupInputs = function () {
  22819. };
  22820. Camera.prototype.serialize = function () {
  22821. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  22822. // Type
  22823. serializationObject.type = this.getClassName();
  22824. // Parent
  22825. if (this.parent) {
  22826. serializationObject.parentId = this.parent.id;
  22827. }
  22828. if (this.inputs) {
  22829. this.inputs.serialize(serializationObject);
  22830. }
  22831. // Animations
  22832. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  22833. serializationObject.ranges = this.serializeAnimationRanges();
  22834. return serializationObject;
  22835. };
  22836. Camera.prototype.clone = function (name) {
  22837. return BABYLON.SerializationHelper.Clone(Camera.GetConstructorFromName(this.getClassName(), name, this.getScene(), this.interaxialDistance, this.isStereoscopicSideBySide), this);
  22838. };
  22839. Camera.prototype.getDirection = function (localAxis) {
  22840. var result = BABYLON.Vector3.Zero();
  22841. this.getDirectionToRef(localAxis, result);
  22842. return result;
  22843. };
  22844. Camera.prototype.getDirectionToRef = function (localAxis, result) {
  22845. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  22846. };
  22847. Camera.GetConstructorFromName = function (type, name, scene, interaxial_distance, isStereoscopicSideBySide) {
  22848. if (interaxial_distance === void 0) { interaxial_distance = 0; }
  22849. if (isStereoscopicSideBySide === void 0) { isStereoscopicSideBySide = true; }
  22850. switch (type) {
  22851. case "ArcRotateCamera":
  22852. return function () { return new BABYLON.ArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  22853. case "DeviceOrientationCamera":
  22854. return function () { return new BABYLON.DeviceOrientationCamera(name, BABYLON.Vector3.Zero(), scene); };
  22855. case "FollowCamera":
  22856. return function () { return new BABYLON.FollowCamera(name, BABYLON.Vector3.Zero(), scene); };
  22857. case "ArcFollowCamera":
  22858. return function () { return new BABYLON.ArcFollowCamera(name, 0, 0, 1.0, null, scene); };
  22859. case "GamepadCamera":
  22860. return function () { return new BABYLON.GamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  22861. case "TouchCamera":
  22862. return function () { return new BABYLON.TouchCamera(name, BABYLON.Vector3.Zero(), scene); };
  22863. case "VirtualJoysticksCamera":
  22864. return function () { return new BABYLON.VirtualJoysticksCamera(name, BABYLON.Vector3.Zero(), scene); };
  22865. case "WebVRFreeCamera":
  22866. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  22867. case "WebVRGamepadCamera":
  22868. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  22869. case "VRDeviceOrientationFreeCamera":
  22870. return function () { return new BABYLON.VRDeviceOrientationFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  22871. case "VRDeviceOrientationGamepadCamera":
  22872. return function () { return new BABYLON.VRDeviceOrientationGamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  22873. case "AnaglyphArcRotateCamera":
  22874. return function () { return new BABYLON.AnaglyphArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  22875. case "AnaglyphFreeCamera":
  22876. return function () { return new BABYLON.AnaglyphFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  22877. case "AnaglyphGamepadCamera":
  22878. return function () { return new BABYLON.AnaglyphGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  22879. case "AnaglyphUniversalCamera":
  22880. return function () { return new BABYLON.AnaglyphUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  22881. case "StereoscopicArcRotateCamera":
  22882. return function () { return new BABYLON.StereoscopicArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  22883. case "StereoscopicFreeCamera":
  22884. return function () { return new BABYLON.StereoscopicFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  22885. case "StereoscopicGamepadCamera":
  22886. return function () { return new BABYLON.StereoscopicGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  22887. case "StereoscopicUniversalCamera":
  22888. return function () { return new BABYLON.StereoscopicUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  22889. case "FreeCamera": // Forcing Universal here
  22890. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  22891. default: // Universal Camera is the default value
  22892. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  22893. }
  22894. };
  22895. Camera.prototype.computeWorldMatrix = function () {
  22896. return this.getWorldMatrix();
  22897. };
  22898. Camera.Parse = function (parsedCamera, scene) {
  22899. var type = parsedCamera.type;
  22900. var construct = Camera.GetConstructorFromName(type, parsedCamera.name, scene, parsedCamera.interaxial_distance, parsedCamera.isStereoscopicSideBySide);
  22901. var camera = BABYLON.SerializationHelper.Parse(construct, parsedCamera, scene);
  22902. // Parent
  22903. if (parsedCamera.parentId) {
  22904. camera._waitingParentId = parsedCamera.parentId;
  22905. }
  22906. //If camera has an input manager, let it parse inputs settings
  22907. if (camera.inputs) {
  22908. camera.inputs.parse(parsedCamera);
  22909. camera._setupInputs();
  22910. }
  22911. if (camera.setPosition) { // need to force position
  22912. camera.position.copyFromFloats(0, 0, 0);
  22913. camera.setPosition(BABYLON.Vector3.FromArray(parsedCamera.position));
  22914. }
  22915. // Target
  22916. if (parsedCamera.target) {
  22917. if (camera.setTarget) {
  22918. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  22919. }
  22920. }
  22921. // Apply 3d rig, when found
  22922. if (parsedCamera.cameraRigMode) {
  22923. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  22924. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  22925. }
  22926. // Animations
  22927. if (parsedCamera.animations) {
  22928. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  22929. var parsedAnimation = parsedCamera.animations[animationIndex];
  22930. camera.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  22931. }
  22932. BABYLON.Node.ParseAnimationRanges(camera, parsedCamera, scene);
  22933. }
  22934. if (parsedCamera.autoAnimate) {
  22935. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, parsedCamera.autoAnimateSpeed || 1.0);
  22936. }
  22937. return camera;
  22938. };
  22939. // Statics
  22940. Camera._PERSPECTIVE_CAMERA = 0;
  22941. Camera._ORTHOGRAPHIC_CAMERA = 1;
  22942. Camera._FOVMODE_VERTICAL_FIXED = 0;
  22943. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  22944. Camera._RIG_MODE_NONE = 0;
  22945. Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  22946. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  22947. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  22948. Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  22949. Camera._RIG_MODE_VR = 20;
  22950. Camera._RIG_MODE_WEBVR = 21;
  22951. Camera.ForceAttachControlToAlwaysPreventDefault = false;
  22952. Camera.UseAlternateWebVRRendering = false;
  22953. __decorate([
  22954. BABYLON.serializeAsVector3()
  22955. ], Camera.prototype, "position", void 0);
  22956. __decorate([
  22957. BABYLON.serializeAsVector3()
  22958. ], Camera.prototype, "upVector", void 0);
  22959. __decorate([
  22960. BABYLON.serialize()
  22961. ], Camera.prototype, "orthoLeft", void 0);
  22962. __decorate([
  22963. BABYLON.serialize()
  22964. ], Camera.prototype, "orthoRight", void 0);
  22965. __decorate([
  22966. BABYLON.serialize()
  22967. ], Camera.prototype, "orthoBottom", void 0);
  22968. __decorate([
  22969. BABYLON.serialize()
  22970. ], Camera.prototype, "orthoTop", void 0);
  22971. __decorate([
  22972. BABYLON.serialize()
  22973. ], Camera.prototype, "fov", void 0);
  22974. __decorate([
  22975. BABYLON.serialize()
  22976. ], Camera.prototype, "minZ", void 0);
  22977. __decorate([
  22978. BABYLON.serialize()
  22979. ], Camera.prototype, "maxZ", void 0);
  22980. __decorate([
  22981. BABYLON.serialize()
  22982. ], Camera.prototype, "inertia", void 0);
  22983. __decorate([
  22984. BABYLON.serialize()
  22985. ], Camera.prototype, "mode", void 0);
  22986. __decorate([
  22987. BABYLON.serialize()
  22988. ], Camera.prototype, "layerMask", void 0);
  22989. __decorate([
  22990. BABYLON.serialize()
  22991. ], Camera.prototype, "fovMode", void 0);
  22992. __decorate([
  22993. BABYLON.serialize()
  22994. ], Camera.prototype, "cameraRigMode", void 0);
  22995. __decorate([
  22996. BABYLON.serialize()
  22997. ], Camera.prototype, "interaxialDistance", void 0);
  22998. __decorate([
  22999. BABYLON.serialize()
  23000. ], Camera.prototype, "isStereoscopicSideBySide", void 0);
  23001. return Camera;
  23002. }(BABYLON.Node));
  23003. BABYLON.Camera = Camera;
  23004. })(BABYLON || (BABYLON = {}));
  23005. //# sourceMappingURL=babylon.camera.js.map
  23006. var BABYLON;
  23007. (function (BABYLON) {
  23008. var RenderingManager = /** @class */ (function () {
  23009. function RenderingManager(scene) {
  23010. this._renderingGroups = new Array();
  23011. this._autoClearDepthStencil = {};
  23012. this._customOpaqueSortCompareFn = {};
  23013. this._customAlphaTestSortCompareFn = {};
  23014. this._customTransparentSortCompareFn = {};
  23015. this._renderinGroupInfo = null;
  23016. this._scene = scene;
  23017. for (var i = RenderingManager.MIN_RENDERINGGROUPS; i < RenderingManager.MAX_RENDERINGGROUPS; i++) {
  23018. this._autoClearDepthStencil[i] = { autoClear: true, depth: true, stencil: true };
  23019. }
  23020. }
  23021. RenderingManager.prototype._clearDepthStencilBuffer = function (depth, stencil) {
  23022. if (depth === void 0) { depth = true; }
  23023. if (stencil === void 0) { stencil = true; }
  23024. if (this._depthStencilBufferAlreadyCleaned) {
  23025. return;
  23026. }
  23027. this._scene.getEngine().clear(null, false, depth, stencil);
  23028. this._depthStencilBufferAlreadyCleaned = true;
  23029. };
  23030. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  23031. // Check if there's at least on observer on the onRenderingGroupObservable and initialize things to fire it
  23032. var observable = this._scene.onRenderingGroupObservable.hasObservers() ? this._scene.onRenderingGroupObservable : null;
  23033. var info = null;
  23034. if (observable) {
  23035. if (!this._renderinGroupInfo) {
  23036. this._renderinGroupInfo = new BABYLON.RenderingGroupInfo();
  23037. }
  23038. info = this._renderinGroupInfo;
  23039. info.scene = this._scene;
  23040. info.camera = this._scene.activeCamera;
  23041. }
  23042. // Dispatch sprites
  23043. if (renderSprites) {
  23044. for (var index = 0; index < this._scene.spriteManagers.length; index++) {
  23045. var manager = this._scene.spriteManagers[index];
  23046. this.dispatchSprites(manager);
  23047. }
  23048. }
  23049. // Render
  23050. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  23051. this._depthStencilBufferAlreadyCleaned = index === RenderingManager.MIN_RENDERINGGROUPS;
  23052. var renderingGroup = this._renderingGroups[index];
  23053. if (!renderingGroup && !observable)
  23054. continue;
  23055. var renderingGroupMask = 0;
  23056. // Fire PRECLEAR stage
  23057. if (observable && info) {
  23058. renderingGroupMask = Math.pow(2, index);
  23059. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRECLEAR;
  23060. info.renderingGroupId = index;
  23061. observable.notifyObservers(info, renderingGroupMask);
  23062. }
  23063. // Clear depth/stencil if needed
  23064. if (RenderingManager.AUTOCLEAR) {
  23065. var autoClear = this._autoClearDepthStencil[index];
  23066. if (autoClear && autoClear.autoClear) {
  23067. this._clearDepthStencilBuffer(autoClear.depth, autoClear.stencil);
  23068. }
  23069. }
  23070. if (observable && info) {
  23071. // Fire PREOPAQUE stage
  23072. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PREOPAQUE;
  23073. observable.notifyObservers(info, renderingGroupMask);
  23074. // Fire PRETRANSPARENT stage
  23075. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRETRANSPARENT;
  23076. observable.notifyObservers(info, renderingGroupMask);
  23077. }
  23078. if (renderingGroup)
  23079. renderingGroup.render(customRenderFunction, renderSprites, renderParticles, activeMeshes);
  23080. // Fire POSTTRANSPARENT stage
  23081. if (observable && info) {
  23082. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_POSTTRANSPARENT;
  23083. observable.notifyObservers(info, renderingGroupMask);
  23084. }
  23085. }
  23086. };
  23087. RenderingManager.prototype.reset = function () {
  23088. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  23089. var renderingGroup = this._renderingGroups[index];
  23090. if (renderingGroup) {
  23091. renderingGroup.prepare();
  23092. }
  23093. }
  23094. };
  23095. RenderingManager.prototype.dispose = function () {
  23096. this.freeRenderingGroups();
  23097. this._renderingGroups.length = 0;
  23098. };
  23099. /**
  23100. * Clear the info related to rendering groups preventing retention points during dispose.
  23101. */
  23102. RenderingManager.prototype.freeRenderingGroups = function () {
  23103. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  23104. var renderingGroup = this._renderingGroups[index];
  23105. if (renderingGroup) {
  23106. renderingGroup.dispose();
  23107. }
  23108. }
  23109. };
  23110. RenderingManager.prototype._prepareRenderingGroup = function (renderingGroupId) {
  23111. if (this._renderingGroups[renderingGroupId] === undefined) {
  23112. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene, this._customOpaqueSortCompareFn[renderingGroupId], this._customAlphaTestSortCompareFn[renderingGroupId], this._customTransparentSortCompareFn[renderingGroupId]);
  23113. }
  23114. };
  23115. RenderingManager.prototype.dispatchSprites = function (spriteManager) {
  23116. var renderingGroupId = spriteManager.renderingGroupId || 0;
  23117. this._prepareRenderingGroup(renderingGroupId);
  23118. this._renderingGroups[renderingGroupId].dispatchSprites(spriteManager);
  23119. };
  23120. RenderingManager.prototype.dispatchParticles = function (particleSystem) {
  23121. var renderingGroupId = particleSystem.renderingGroupId || 0;
  23122. this._prepareRenderingGroup(renderingGroupId);
  23123. this._renderingGroups[renderingGroupId].dispatchParticles(particleSystem);
  23124. };
  23125. /**
  23126. * @param subMesh The submesh to dispatch
  23127. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  23128. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  23129. */
  23130. RenderingManager.prototype.dispatch = function (subMesh, mesh, material) {
  23131. if (mesh === undefined) {
  23132. mesh = subMesh.getMesh();
  23133. }
  23134. var renderingGroupId = mesh.renderingGroupId || 0;
  23135. this._prepareRenderingGroup(renderingGroupId);
  23136. this._renderingGroups[renderingGroupId].dispatch(subMesh, mesh, material);
  23137. };
  23138. /**
  23139. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  23140. * This allowed control for front to back rendering or reversly depending of the special needs.
  23141. *
  23142. * @param renderingGroupId The rendering group id corresponding to its index
  23143. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  23144. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  23145. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  23146. */
  23147. RenderingManager.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  23148. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  23149. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  23150. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  23151. this._customOpaqueSortCompareFn[renderingGroupId] = opaqueSortCompareFn;
  23152. this._customAlphaTestSortCompareFn[renderingGroupId] = alphaTestSortCompareFn;
  23153. this._customTransparentSortCompareFn[renderingGroupId] = transparentSortCompareFn;
  23154. if (this._renderingGroups[renderingGroupId]) {
  23155. var group = this._renderingGroups[renderingGroupId];
  23156. group.opaqueSortCompareFn = this._customOpaqueSortCompareFn[renderingGroupId];
  23157. group.alphaTestSortCompareFn = this._customAlphaTestSortCompareFn[renderingGroupId];
  23158. group.transparentSortCompareFn = this._customTransparentSortCompareFn[renderingGroupId];
  23159. }
  23160. };
  23161. /**
  23162. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  23163. *
  23164. * @param renderingGroupId The rendering group id corresponding to its index
  23165. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  23166. * @param depth Automatically clears depth between groups if true and autoClear is true.
  23167. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  23168. */
  23169. RenderingManager.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  23170. if (depth === void 0) { depth = true; }
  23171. if (stencil === void 0) { stencil = true; }
  23172. this._autoClearDepthStencil[renderingGroupId] = {
  23173. autoClear: autoClearDepthStencil,
  23174. depth: depth,
  23175. stencil: stencil
  23176. };
  23177. };
  23178. /**
  23179. * The max id used for rendering groups (not included)
  23180. */
  23181. RenderingManager.MAX_RENDERINGGROUPS = 4;
  23182. /**
  23183. * The min id used for rendering groups (included)
  23184. */
  23185. RenderingManager.MIN_RENDERINGGROUPS = 0;
  23186. /**
  23187. * Used to globally prevent autoclearing scenes.
  23188. */
  23189. RenderingManager.AUTOCLEAR = true;
  23190. return RenderingManager;
  23191. }());
  23192. BABYLON.RenderingManager = RenderingManager;
  23193. })(BABYLON || (BABYLON = {}));
  23194. //# sourceMappingURL=babylon.renderingManager.js.map
  23195. var BABYLON;
  23196. (function (BABYLON) {
  23197. var RenderingGroup = /** @class */ (function () {
  23198. /**
  23199. * Creates a new rendering group.
  23200. * @param index The rendering group index
  23201. * @param opaqueSortCompareFn The opaque sort comparison function. If null no order is applied
  23202. * @param alphaTestSortCompareFn The alpha test sort comparison function. If null no order is applied
  23203. * @param transparentSortCompareFn The transparent sort comparison function. If null back to front + alpha index sort is applied
  23204. */
  23205. function RenderingGroup(index, scene, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  23206. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  23207. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  23208. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  23209. this.index = index;
  23210. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  23211. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  23212. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  23213. this._depthOnlySubMeshes = new BABYLON.SmartArray(256);
  23214. this._particleSystems = new BABYLON.SmartArray(256);
  23215. this._spriteManagers = new BABYLON.SmartArray(256);
  23216. this._edgesRenderers = new BABYLON.SmartArray(16);
  23217. this._scene = scene;
  23218. this.opaqueSortCompareFn = opaqueSortCompareFn;
  23219. this.alphaTestSortCompareFn = alphaTestSortCompareFn;
  23220. this.transparentSortCompareFn = transparentSortCompareFn;
  23221. }
  23222. Object.defineProperty(RenderingGroup.prototype, "opaqueSortCompareFn", {
  23223. /**
  23224. * Set the opaque sort comparison function.
  23225. * If null the sub meshes will be render in the order they were created
  23226. */
  23227. set: function (value) {
  23228. this._opaqueSortCompareFn = value;
  23229. if (value) {
  23230. this._renderOpaque = this.renderOpaqueSorted;
  23231. }
  23232. else {
  23233. this._renderOpaque = RenderingGroup.renderUnsorted;
  23234. }
  23235. },
  23236. enumerable: true,
  23237. configurable: true
  23238. });
  23239. Object.defineProperty(RenderingGroup.prototype, "alphaTestSortCompareFn", {
  23240. /**
  23241. * Set the alpha test sort comparison function.
  23242. * If null the sub meshes will be render in the order they were created
  23243. */
  23244. set: function (value) {
  23245. this._alphaTestSortCompareFn = value;
  23246. if (value) {
  23247. this._renderAlphaTest = this.renderAlphaTestSorted;
  23248. }
  23249. else {
  23250. this._renderAlphaTest = RenderingGroup.renderUnsorted;
  23251. }
  23252. },
  23253. enumerable: true,
  23254. configurable: true
  23255. });
  23256. Object.defineProperty(RenderingGroup.prototype, "transparentSortCompareFn", {
  23257. /**
  23258. * Set the transparent sort comparison function.
  23259. * If null the sub meshes will be render in the order they were created
  23260. */
  23261. set: function (value) {
  23262. if (value) {
  23263. this._transparentSortCompareFn = value;
  23264. }
  23265. else {
  23266. this._transparentSortCompareFn = RenderingGroup.defaultTransparentSortCompare;
  23267. }
  23268. this._renderTransparent = this.renderTransparentSorted;
  23269. },
  23270. enumerable: true,
  23271. configurable: true
  23272. });
  23273. /**
  23274. * Render all the sub meshes contained in the group.
  23275. * @param customRenderFunction Used to override the default render behaviour of the group.
  23276. * @returns true if rendered some submeshes.
  23277. */
  23278. RenderingGroup.prototype.render = function (customRenderFunction, renderSprites, renderParticles, activeMeshes) {
  23279. if (customRenderFunction) {
  23280. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes, this._depthOnlySubMeshes);
  23281. return;
  23282. }
  23283. var engine = this._scene.getEngine();
  23284. // Depth only
  23285. if (this._depthOnlySubMeshes.length !== 0) {
  23286. engine.setColorWrite(false);
  23287. this._renderAlphaTest(this._depthOnlySubMeshes);
  23288. engine.setColorWrite(true);
  23289. }
  23290. // Opaque
  23291. if (this._opaqueSubMeshes.length !== 0) {
  23292. this._renderOpaque(this._opaqueSubMeshes);
  23293. }
  23294. // Alpha test
  23295. if (this._alphaTestSubMeshes.length !== 0) {
  23296. this._renderAlphaTest(this._alphaTestSubMeshes);
  23297. }
  23298. var stencilState = engine.getStencilBuffer();
  23299. engine.setStencilBuffer(false);
  23300. // Sprites
  23301. if (renderSprites) {
  23302. this._renderSprites();
  23303. }
  23304. // Particles
  23305. if (renderParticles) {
  23306. this._renderParticles(activeMeshes);
  23307. }
  23308. if (this.onBeforeTransparentRendering) {
  23309. this.onBeforeTransparentRendering();
  23310. }
  23311. // Transparent
  23312. if (this._transparentSubMeshes.length !== 0) {
  23313. this._renderTransparent(this._transparentSubMeshes);
  23314. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  23315. }
  23316. // Set back stencil to false in case it changes before the edge renderer.
  23317. engine.setStencilBuffer(false);
  23318. // Edges
  23319. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  23320. this._edgesRenderers.data[edgesRendererIndex].render();
  23321. }
  23322. // Restore Stencil state.
  23323. engine.setStencilBuffer(stencilState);
  23324. };
  23325. /**
  23326. * Renders the opaque submeshes in the order from the opaqueSortCompareFn.
  23327. * @param subMeshes The submeshes to render
  23328. */
  23329. RenderingGroup.prototype.renderOpaqueSorted = function (subMeshes) {
  23330. return RenderingGroup.renderSorted(subMeshes, this._opaqueSortCompareFn, this._scene.activeCamera, false);
  23331. };
  23332. /**
  23333. * Renders the opaque submeshes in the order from the alphatestSortCompareFn.
  23334. * @param subMeshes The submeshes to render
  23335. */
  23336. RenderingGroup.prototype.renderAlphaTestSorted = function (subMeshes) {
  23337. return RenderingGroup.renderSorted(subMeshes, this._alphaTestSortCompareFn, this._scene.activeCamera, false);
  23338. };
  23339. /**
  23340. * Renders the opaque submeshes in the order from the transparentSortCompareFn.
  23341. * @param subMeshes The submeshes to render
  23342. */
  23343. RenderingGroup.prototype.renderTransparentSorted = function (subMeshes) {
  23344. return RenderingGroup.renderSorted(subMeshes, this._transparentSortCompareFn, this._scene.activeCamera, true);
  23345. };
  23346. /**
  23347. * Renders the submeshes in a specified order.
  23348. * @param subMeshes The submeshes to sort before render
  23349. * @param sortCompareFn The comparison function use to sort
  23350. * @param cameraPosition The camera position use to preprocess the submeshes to help sorting
  23351. * @param transparent Specifies to activate blending if true
  23352. */
  23353. RenderingGroup.renderSorted = function (subMeshes, sortCompareFn, camera, transparent) {
  23354. var subIndex = 0;
  23355. var subMesh;
  23356. var cameraPosition = camera ? camera.globalPosition : BABYLON.Vector3.Zero();
  23357. for (; subIndex < subMeshes.length; subIndex++) {
  23358. subMesh = subMeshes.data[subIndex];
  23359. subMesh._alphaIndex = subMesh.getMesh().alphaIndex;
  23360. subMesh._distanceToCamera = subMesh.getBoundingInfo().boundingSphere.centerWorld.subtract(cameraPosition).length();
  23361. }
  23362. var sortedArray = subMeshes.data.slice(0, subMeshes.length);
  23363. if (sortCompareFn) {
  23364. sortedArray.sort(sortCompareFn);
  23365. }
  23366. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  23367. subMesh = sortedArray[subIndex];
  23368. if (transparent) {
  23369. var material = subMesh.getMaterial();
  23370. if (material && material.needDepthPrePass) {
  23371. var engine = material.getScene().getEngine();
  23372. engine.setColorWrite(false);
  23373. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  23374. subMesh.render(false);
  23375. engine.setColorWrite(true);
  23376. }
  23377. }
  23378. subMesh.render(transparent);
  23379. }
  23380. };
  23381. /**
  23382. * Renders the submeshes in the order they were dispatched (no sort applied).
  23383. * @param subMeshes The submeshes to render
  23384. */
  23385. RenderingGroup.renderUnsorted = function (subMeshes) {
  23386. for (var subIndex = 0; subIndex < subMeshes.length; subIndex++) {
  23387. var submesh = subMeshes.data[subIndex];
  23388. submesh.render(false);
  23389. }
  23390. };
  23391. /**
  23392. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  23393. * are rendered back to front if in the same alpha index.
  23394. *
  23395. * @param a The first submesh
  23396. * @param b The second submesh
  23397. * @returns The result of the comparison
  23398. */
  23399. RenderingGroup.defaultTransparentSortCompare = function (a, b) {
  23400. // Alpha index first
  23401. if (a._alphaIndex > b._alphaIndex) {
  23402. return 1;
  23403. }
  23404. if (a._alphaIndex < b._alphaIndex) {
  23405. return -1;
  23406. }
  23407. // Then distance to camera
  23408. return RenderingGroup.backToFrontSortCompare(a, b);
  23409. };
  23410. /**
  23411. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  23412. * are rendered back to front.
  23413. *
  23414. * @param a The first submesh
  23415. * @param b The second submesh
  23416. * @returns The result of the comparison
  23417. */
  23418. RenderingGroup.backToFrontSortCompare = function (a, b) {
  23419. // Then distance to camera
  23420. if (a._distanceToCamera < b._distanceToCamera) {
  23421. return 1;
  23422. }
  23423. if (a._distanceToCamera > b._distanceToCamera) {
  23424. return -1;
  23425. }
  23426. return 0;
  23427. };
  23428. /**
  23429. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  23430. * are rendered front to back (prevent overdraw).
  23431. *
  23432. * @param a The first submesh
  23433. * @param b The second submesh
  23434. * @returns The result of the comparison
  23435. */
  23436. RenderingGroup.frontToBackSortCompare = function (a, b) {
  23437. // Then distance to camera
  23438. if (a._distanceToCamera < b._distanceToCamera) {
  23439. return -1;
  23440. }
  23441. if (a._distanceToCamera > b._distanceToCamera) {
  23442. return 1;
  23443. }
  23444. return 0;
  23445. };
  23446. /**
  23447. * Resets the different lists of submeshes to prepare a new frame.
  23448. */
  23449. RenderingGroup.prototype.prepare = function () {
  23450. this._opaqueSubMeshes.reset();
  23451. this._transparentSubMeshes.reset();
  23452. this._alphaTestSubMeshes.reset();
  23453. this._depthOnlySubMeshes.reset();
  23454. this._particleSystems.reset();
  23455. this._spriteManagers.reset();
  23456. this._edgesRenderers.reset();
  23457. };
  23458. RenderingGroup.prototype.dispose = function () {
  23459. this._opaqueSubMeshes.dispose();
  23460. this._transparentSubMeshes.dispose();
  23461. this._alphaTestSubMeshes.dispose();
  23462. this._depthOnlySubMeshes.dispose();
  23463. this._particleSystems.dispose();
  23464. this._spriteManagers.dispose();
  23465. this._edgesRenderers.dispose();
  23466. };
  23467. /**
  23468. * Inserts the submesh in its correct queue depending on its material.
  23469. * @param subMesh The submesh to dispatch
  23470. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  23471. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  23472. */
  23473. RenderingGroup.prototype.dispatch = function (subMesh, mesh, material) {
  23474. // Get mesh and materials if not provided
  23475. if (mesh === undefined) {
  23476. mesh = subMesh.getMesh();
  23477. }
  23478. if (material === undefined) {
  23479. material = subMesh.getMaterial();
  23480. }
  23481. if (material === null || material === undefined) {
  23482. return;
  23483. }
  23484. if (material.needAlphaBlendingForMesh(mesh)) { // Transparent
  23485. this._transparentSubMeshes.push(subMesh);
  23486. }
  23487. else if (material.needAlphaTesting()) { // Alpha test
  23488. if (material.needDepthPrePass) {
  23489. this._depthOnlySubMeshes.push(subMesh);
  23490. }
  23491. this._alphaTestSubMeshes.push(subMesh);
  23492. }
  23493. else {
  23494. if (material.needDepthPrePass) {
  23495. this._depthOnlySubMeshes.push(subMesh);
  23496. }
  23497. this._opaqueSubMeshes.push(subMesh); // Opaque
  23498. }
  23499. if (mesh._edgesRenderer !== null && mesh._edgesRenderer !== undefined && mesh._edgesRenderer.isEnabled) {
  23500. this._edgesRenderers.push(mesh._edgesRenderer);
  23501. }
  23502. };
  23503. RenderingGroup.prototype.dispatchSprites = function (spriteManager) {
  23504. this._spriteManagers.push(spriteManager);
  23505. };
  23506. RenderingGroup.prototype.dispatchParticles = function (particleSystem) {
  23507. this._particleSystems.push(particleSystem);
  23508. };
  23509. RenderingGroup.prototype._renderParticles = function (activeMeshes) {
  23510. if (this._particleSystems.length === 0) {
  23511. return;
  23512. }
  23513. // Particles
  23514. var activeCamera = this._scene.activeCamera;
  23515. this._scene.onBeforeParticlesRenderingObservable.notifyObservers(this._scene);
  23516. for (var particleIndex = 0; particleIndex < this._particleSystems.length; particleIndex++) {
  23517. var particleSystem = this._particleSystems.data[particleIndex];
  23518. if ((activeCamera && activeCamera.layerMask & particleSystem.layerMask) === 0) {
  23519. continue;
  23520. }
  23521. var emitter = particleSystem.emitter;
  23522. if (!emitter.position || !activeMeshes || activeMeshes.indexOf(emitter) !== -1) {
  23523. this._scene._activeParticles.addCount(particleSystem.render(), false);
  23524. }
  23525. }
  23526. this._scene.onAfterParticlesRenderingObservable.notifyObservers(this._scene);
  23527. };
  23528. RenderingGroup.prototype._renderSprites = function () {
  23529. if (!this._scene.spritesEnabled || this._spriteManagers.length === 0) {
  23530. return;
  23531. }
  23532. // Sprites
  23533. var activeCamera = this._scene.activeCamera;
  23534. this._scene.onBeforeSpritesRenderingObservable.notifyObservers(this._scene);
  23535. for (var id = 0; id < this._spriteManagers.length; id++) {
  23536. var spriteManager = this._spriteManagers.data[id];
  23537. if (((activeCamera && activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  23538. spriteManager.render();
  23539. }
  23540. }
  23541. this._scene.onAfterSpritesRenderingObservable.notifyObservers(this._scene);
  23542. };
  23543. return RenderingGroup;
  23544. }());
  23545. BABYLON.RenderingGroup = RenderingGroup;
  23546. })(BABYLON || (BABYLON = {}));
  23547. //# sourceMappingURL=babylon.renderingGroup.js.map
  23548. var BABYLON;
  23549. (function (BABYLON) {
  23550. /** @hidden */
  23551. var ClickInfo = /** @class */ (function () {
  23552. function ClickInfo() {
  23553. this._singleClick = false;
  23554. this._doubleClick = false;
  23555. this._hasSwiped = false;
  23556. this._ignore = false;
  23557. }
  23558. Object.defineProperty(ClickInfo.prototype, "singleClick", {
  23559. get: function () {
  23560. return this._singleClick;
  23561. },
  23562. set: function (b) {
  23563. this._singleClick = b;
  23564. },
  23565. enumerable: true,
  23566. configurable: true
  23567. });
  23568. Object.defineProperty(ClickInfo.prototype, "doubleClick", {
  23569. get: function () {
  23570. return this._doubleClick;
  23571. },
  23572. set: function (b) {
  23573. this._doubleClick = b;
  23574. },
  23575. enumerable: true,
  23576. configurable: true
  23577. });
  23578. Object.defineProperty(ClickInfo.prototype, "hasSwiped", {
  23579. get: function () {
  23580. return this._hasSwiped;
  23581. },
  23582. set: function (b) {
  23583. this._hasSwiped = b;
  23584. },
  23585. enumerable: true,
  23586. configurable: true
  23587. });
  23588. Object.defineProperty(ClickInfo.prototype, "ignore", {
  23589. get: function () {
  23590. return this._ignore;
  23591. },
  23592. set: function (b) {
  23593. this._ignore = b;
  23594. },
  23595. enumerable: true,
  23596. configurable: true
  23597. });
  23598. return ClickInfo;
  23599. }());
  23600. /**
  23601. * This class is used by the onRenderingGroupObservable
  23602. */
  23603. var RenderingGroupInfo = /** @class */ (function () {
  23604. function RenderingGroupInfo() {
  23605. }
  23606. /**
  23607. * Stage corresponding to the very first hook in the renderingGroup phase: before the render buffer may be cleared
  23608. * This stage will be fired no matter what
  23609. */
  23610. RenderingGroupInfo.STAGE_PRECLEAR = 1;
  23611. /**
  23612. * Called before opaque object are rendered.
  23613. * This stage will be fired only if there's 3D Opaque content to render
  23614. */
  23615. RenderingGroupInfo.STAGE_PREOPAQUE = 2;
  23616. /**
  23617. * Called after the opaque objects are rendered and before the transparent ones
  23618. * This stage will be fired only if there's 3D transparent content to render
  23619. */
  23620. RenderingGroupInfo.STAGE_PRETRANSPARENT = 3;
  23621. /**
  23622. * Called after the transparent object are rendered, last hook of the renderingGroup phase
  23623. * This stage will be fired no matter what
  23624. */
  23625. RenderingGroupInfo.STAGE_POSTTRANSPARENT = 4;
  23626. return RenderingGroupInfo;
  23627. }());
  23628. BABYLON.RenderingGroupInfo = RenderingGroupInfo;
  23629. /**
  23630. * Represents a scene to be rendered by the engine.
  23631. * @see http://doc.babylonjs.com/features/scene
  23632. */
  23633. var Scene = /** @class */ (function () {
  23634. /**
  23635. * Creates a new Scene
  23636. * @param engine defines the engine to use to render this scene
  23637. */
  23638. function Scene(engine) {
  23639. // Members
  23640. /**
  23641. * Gets or sets a boolean that indicates if the scene must clear the render buffer before rendering a frame
  23642. */
  23643. this.autoClear = true;
  23644. /**
  23645. * Gets or sets a boolean that indicates if the scene must clear the depth and stencil buffers before rendering a frame
  23646. */
  23647. this.autoClearDepthAndStencil = true;
  23648. /**
  23649. * Defines the color used to clear the render buffer (Default is (0.2, 0.2, 0.3, 1.0))
  23650. */
  23651. this.clearColor = new BABYLON.Color4(0.2, 0.2, 0.3, 1.0);
  23652. /**
  23653. * Defines the color used to simulate the ambient color (Default is (0, 0, 0))
  23654. */
  23655. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  23656. this._forceWireframe = false;
  23657. this._forcePointsCloud = false;
  23658. /**
  23659. * Gets or sets a boolean indicating if all bounding boxes must be rendered
  23660. */
  23661. this.forceShowBoundingBoxes = false;
  23662. /**
  23663. * Gets or sets a boolean indicating if animations are enabled
  23664. */
  23665. this.animationsEnabled = true;
  23666. this._animationPropertiesOverride = null;
  23667. /**
  23668. * Gets or sets a boolean indicating if a constant deltatime has to be used
  23669. * This is mostly useful for testing purposes when you do not want the animations to scale with the framerate
  23670. */
  23671. this.useConstantAnimationDeltaTime = false;
  23672. /**
  23673. * Gets or sets a boolean indicating if the scene must keep the meshUnderPointer property updated
  23674. * Please note that it requires to run a ray cast through the scene on every frame
  23675. */
  23676. this.constantlyUpdateMeshUnderPointer = false;
  23677. /**
  23678. * Defines the HTML cursor to use when hovering over interactive elements
  23679. */
  23680. this.hoverCursor = "pointer";
  23681. /**
  23682. * Defines the HTML default cursor to use (empty by default)
  23683. */
  23684. this.defaultCursor = "";
  23685. /**
  23686. * This is used to call preventDefault() on pointer down
  23687. * in order to block unwanted artifacts like system double clicks
  23688. */
  23689. this.preventDefaultOnPointerDown = true;
  23690. // Metadata
  23691. /**
  23692. * Gets or sets user defined metadata
  23693. */
  23694. this.metadata = null;
  23695. /**
  23696. * Use this array to add regular expressions used to disable offline support for specific urls
  23697. */
  23698. this.disableOfflineSupportExceptionRules = new Array();
  23699. /**
  23700. * An event triggered when the scene is disposed.
  23701. */
  23702. this.onDisposeObservable = new BABYLON.Observable();
  23703. this._onDisposeObserver = null;
  23704. /**
  23705. * An event triggered before rendering the scene (right after animations and physics)
  23706. */
  23707. this.onBeforeRenderObservable = new BABYLON.Observable();
  23708. this._onBeforeRenderObserver = null;
  23709. /**
  23710. * An event triggered after rendering the scene
  23711. */
  23712. this.onAfterRenderObservable = new BABYLON.Observable();
  23713. this._onAfterRenderObserver = null;
  23714. /**
  23715. * An event triggered before animating the scene
  23716. */
  23717. this.onBeforeAnimationsObservable = new BABYLON.Observable();
  23718. /**
  23719. * An event triggered after animations processing
  23720. */
  23721. this.onAfterAnimationsObservable = new BABYLON.Observable();
  23722. /**
  23723. * An event triggered before draw calls are ready to be sent
  23724. */
  23725. this.onBeforeDrawPhaseObservable = new BABYLON.Observable();
  23726. /**
  23727. * An event triggered after draw calls have been sent
  23728. */
  23729. this.onAfterDrawPhaseObservable = new BABYLON.Observable();
  23730. /**
  23731. * An event triggered when physic simulation is about to be run
  23732. */
  23733. this.onBeforePhysicsObservable = new BABYLON.Observable();
  23734. /**
  23735. * An event triggered when physic simulation has been done
  23736. */
  23737. this.onAfterPhysicsObservable = new BABYLON.Observable();
  23738. /**
  23739. * An event triggered when the scene is ready
  23740. */
  23741. this.onReadyObservable = new BABYLON.Observable();
  23742. /**
  23743. * An event triggered before rendering a camera
  23744. */
  23745. this.onBeforeCameraRenderObservable = new BABYLON.Observable();
  23746. this._onBeforeCameraRenderObserver = null;
  23747. /**
  23748. * An event triggered after rendering a camera
  23749. */
  23750. this.onAfterCameraRenderObservable = new BABYLON.Observable();
  23751. this._onAfterCameraRenderObserver = null;
  23752. /**
  23753. * An event triggered when active meshes evaluation is about to start
  23754. */
  23755. this.onBeforeActiveMeshesEvaluationObservable = new BABYLON.Observable();
  23756. /**
  23757. * An event triggered when active meshes evaluation is done
  23758. */
  23759. this.onAfterActiveMeshesEvaluationObservable = new BABYLON.Observable();
  23760. /**
  23761. * An event triggered when particles rendering is about to start
  23762. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  23763. */
  23764. this.onBeforeParticlesRenderingObservable = new BABYLON.Observable();
  23765. /**
  23766. * An event triggered when particles rendering is done
  23767. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  23768. */
  23769. this.onAfterParticlesRenderingObservable = new BABYLON.Observable();
  23770. /**
  23771. * An event triggered when sprites rendering is about to start
  23772. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  23773. */
  23774. this.onBeforeSpritesRenderingObservable = new BABYLON.Observable();
  23775. /**
  23776. * An event triggered when sprites rendering is done
  23777. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  23778. */
  23779. this.onAfterSpritesRenderingObservable = new BABYLON.Observable();
  23780. /**
  23781. * An event triggered when SceneLoader.Append or SceneLoader.Load or SceneLoader.ImportMesh were successfully executed
  23782. */
  23783. this.onDataLoadedObservable = new BABYLON.Observable();
  23784. /**
  23785. * An event triggered when a camera is created
  23786. */
  23787. this.onNewCameraAddedObservable = new BABYLON.Observable();
  23788. /**
  23789. * An event triggered when a camera is removed
  23790. */
  23791. this.onCameraRemovedObservable = new BABYLON.Observable();
  23792. /**
  23793. * An event triggered when a light is created
  23794. */
  23795. this.onNewLightAddedObservable = new BABYLON.Observable();
  23796. /**
  23797. * An event triggered when a light is removed
  23798. */
  23799. this.onLightRemovedObservable = new BABYLON.Observable();
  23800. /**
  23801. * An event triggered when a geometry is created
  23802. */
  23803. this.onNewGeometryAddedObservable = new BABYLON.Observable();
  23804. /**
  23805. * An event triggered when a geometry is removed
  23806. */
  23807. this.onGeometryRemovedObservable = new BABYLON.Observable();
  23808. /**
  23809. * An event triggered when a transform node is created
  23810. */
  23811. this.onNewTransformNodeAddedObservable = new BABYLON.Observable();
  23812. /**
  23813. * An event triggered when a transform node is removed
  23814. */
  23815. this.onTransformNodeRemovedObservable = new BABYLON.Observable();
  23816. /**
  23817. * An event triggered when a mesh is created
  23818. */
  23819. this.onNewMeshAddedObservable = new BABYLON.Observable();
  23820. /**
  23821. * An event triggered when a mesh is removed
  23822. */
  23823. this.onMeshRemovedObservable = new BABYLON.Observable();
  23824. /**
  23825. * An event triggered when render targets are about to be rendered
  23826. * Can happen multiple times per frame.
  23827. */
  23828. this.onBeforeRenderTargetsRenderObservable = new BABYLON.Observable();
  23829. /**
  23830. * An event triggered when render targets were rendered.
  23831. * Can happen multiple times per frame.
  23832. */
  23833. this.onAfterRenderTargetsRenderObservable = new BABYLON.Observable();
  23834. /**
  23835. * An event triggered before calculating deterministic simulation step
  23836. */
  23837. this.onBeforeStepObservable = new BABYLON.Observable();
  23838. /**
  23839. * An event triggered after calculating deterministic simulation step
  23840. */
  23841. this.onAfterStepObservable = new BABYLON.Observable();
  23842. /**
  23843. * This Observable will be triggered for each stage of each renderingGroup of each rendered camera.
  23844. * The RenderinGroupInfo class contains all the information about the context in which the observable is called
  23845. * 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)
  23846. */
  23847. this.onRenderingGroupObservable = new BABYLON.Observable();
  23848. // Animations
  23849. /**
  23850. * Gets a list of Animations associated with the scene
  23851. */
  23852. this.animations = [];
  23853. this._registeredForLateAnimationBindings = new BABYLON.SmartArrayNoDuplicate(256);
  23854. /**
  23855. * 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).
  23856. * You have the possibility to skip the process and the call to onPointerObservable by setting PointerInfoPre.skipOnPointerObservable to true
  23857. */
  23858. this.onPrePointerObservable = new BABYLON.Observable();
  23859. /**
  23860. * Observable event triggered each time an input event is received from the rendering canvas
  23861. */
  23862. this.onPointerObservable = new BABYLON.Observable();
  23863. this._meshPickProceed = false;
  23864. this._currentPickResult = null;
  23865. this._previousPickResult = null;
  23866. this._totalPointersPressed = 0;
  23867. this._doubleClickOccured = false;
  23868. /** Define this parameter if you are using multiple cameras and you want to specify which one should be used for pointer position */
  23869. this.cameraToUseForPointers = null;
  23870. this._startingPointerPosition = new BABYLON.Vector2(0, 0);
  23871. this._previousStartingPointerPosition = new BABYLON.Vector2(0, 0);
  23872. this._startingPointerTime = 0;
  23873. this._previousStartingPointerTime = 0;
  23874. this._pointerCaptures = {};
  23875. // Deterministic lockstep
  23876. this._timeAccumulator = 0;
  23877. this._currentStepId = 0;
  23878. this._currentInternalStep = 0;
  23879. // Keyboard
  23880. /**
  23881. * This observable event is triggered when any keyboard event si raised and registered during Scene.attachControl()
  23882. * You have the possibility to skip the process and the call to onKeyboardObservable by setting KeyboardInfoPre.skipOnPointerObservable to true
  23883. */
  23884. this.onPreKeyboardObservable = new BABYLON.Observable();
  23885. /**
  23886. * Observable event triggered each time an keyboard event is received from the hosting window
  23887. */
  23888. this.onKeyboardObservable = new BABYLON.Observable();
  23889. // Coordinates system
  23890. this._useRightHandedSystem = false;
  23891. // Fog
  23892. this._fogEnabled = true;
  23893. this._fogMode = Scene.FOGMODE_NONE;
  23894. /**
  23895. * Gets or sets the fog color to use
  23896. * @see http://doc.babylonjs.com/babylon101/environment#fog
  23897. */
  23898. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  23899. /**
  23900. * Gets or sets the fog density to use
  23901. * @see http://doc.babylonjs.com/babylon101/environment#fog
  23902. */
  23903. this.fogDensity = 0.1;
  23904. /**
  23905. * Gets or sets the fog start distance to use
  23906. * @see http://doc.babylonjs.com/babylon101/environment#fog
  23907. */
  23908. this.fogStart = 0;
  23909. /**
  23910. * Gets or sets the fog end distance to use
  23911. * @see http://doc.babylonjs.com/babylon101/environment#fog
  23912. */
  23913. this.fogEnd = 1000.0;
  23914. // Lights
  23915. this._shadowsEnabled = true;
  23916. this._lightsEnabled = true;
  23917. /**
  23918. * All of the lights added to this scene
  23919. * @see http://doc.babylonjs.com/babylon101/lights
  23920. */
  23921. this.lights = new Array();
  23922. // Cameras
  23923. /** All of the cameras added to this scene.
  23924. * @see http://doc.babylonjs.com/babylon101/cameras
  23925. */
  23926. this.cameras = new Array();
  23927. /** All of the active cameras added to this scene. */
  23928. this.activeCameras = new Array();
  23929. // Meshes
  23930. /**
  23931. * All of the tranform nodes added to this scene
  23932. * @see http://doc.babylonjs.com/how_to/transformnode
  23933. */
  23934. this.transformNodes = new Array();
  23935. /**
  23936. * All of the (abstract) meshes added to this scene
  23937. */
  23938. this.meshes = new Array();
  23939. /**
  23940. * All of the animation groups added to this scene
  23941. * @see http://doc.babylonjs.com/how_to/group
  23942. */
  23943. this.animationGroups = new Array();
  23944. // Geometries
  23945. this._geometries = new Array();
  23946. /**
  23947. * All of the materials added to this scene
  23948. * @see http://doc.babylonjs.com/babylon101/materials
  23949. */
  23950. this.materials = new Array();
  23951. /**
  23952. * All of the multi-materials added to this scene
  23953. * @see http://doc.babylonjs.com/how_to/multi_materials
  23954. */
  23955. this.multiMaterials = new Array();
  23956. // Textures
  23957. this._texturesEnabled = true;
  23958. /**
  23959. * All of the textures added to this scene
  23960. */
  23961. this.textures = new Array();
  23962. // Particles
  23963. /**
  23964. * Gets or sets a boolean indicating if particles are enabled on this scene
  23965. */
  23966. this.particlesEnabled = true;
  23967. /**
  23968. * All of the particle systems added to this scene
  23969. * @see http://doc.babylonjs.com/babylon101/particles
  23970. */
  23971. this.particleSystems = new Array();
  23972. // Sprites
  23973. /**
  23974. * Gets or sets a boolean indicating if sprites are enabled on this scene
  23975. */
  23976. this.spritesEnabled = true;
  23977. /**
  23978. * All of the sprite managers added to this scene
  23979. * @see http://doc.babylonjs.com/babylon101/sprites
  23980. */
  23981. this.spriteManagers = new Array();
  23982. /**
  23983. * The list of layers (background and foreground) of the scene
  23984. */
  23985. this.layers = new Array();
  23986. /**
  23987. * The list of effect layers (highlights/glow) added to the scene
  23988. * @see http://doc.babylonjs.com/how_to/highlight_layer
  23989. * @see http://doc.babylonjs.com/how_to/glow_layer
  23990. */
  23991. this.effectLayers = new Array();
  23992. // Skeletons
  23993. this._skeletonsEnabled = true;
  23994. /**
  23995. * The list of skeletons added to the scene
  23996. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  23997. */
  23998. this.skeletons = new Array();
  23999. // Morph targets
  24000. /**
  24001. * The list of morph target managers added to the scene
  24002. * @see http://doc.babylonjs.com/how_to/how_to_dynamically_morph_a_mesh
  24003. */
  24004. this.morphTargetManagers = new Array();
  24005. // Lens flares
  24006. /**
  24007. * Gets or sets a boolean indicating if lens flares are enabled on this scene
  24008. */
  24009. this.lensFlaresEnabled = true;
  24010. /**
  24011. * The list of lens flare system added to the scene
  24012. * @see http://doc.babylonjs.com/how_to/how_to_use_lens_flares
  24013. */
  24014. this.lensFlareSystems = new Array();
  24015. // Collisions
  24016. /**
  24017. * Gets or sets a boolean indicating if collisions are enabled on this scene
  24018. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  24019. */
  24020. this.collisionsEnabled = true;
  24021. /**
  24022. * Defines the gravity applied to this scene (used only for collisions)
  24023. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  24024. */
  24025. this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  24026. // Postprocesses
  24027. /**
  24028. * Gets or sets a boolean indicating if postprocesses are enabled on this scene
  24029. */
  24030. this.postProcessesEnabled = true;
  24031. /**
  24032. * The list of postprocesses added to the scene
  24033. */
  24034. this.postProcesses = new Array();
  24035. // Customs render targets
  24036. /**
  24037. * Gets or sets a boolean indicating if render targets are enabled on this scene
  24038. */
  24039. this.renderTargetsEnabled = true;
  24040. /**
  24041. * Gets or sets a boolean indicating if next render targets must be dumped as image for debugging purposes
  24042. * We recommend not using it and instead rely on Spector.js: http://spector.babylonjs.com
  24043. */
  24044. this.dumpNextRenderTargets = false;
  24045. /**
  24046. * The list of user defined render targets added to the scene
  24047. */
  24048. this.customRenderTargets = new Array();
  24049. /**
  24050. * Gets the list of meshes imported to the scene through SceneLoader
  24051. */
  24052. this.importedMeshesFiles = new Array();
  24053. // Probes
  24054. /**
  24055. * Gets or sets a boolean indicating if probes are enabled on this scene
  24056. */
  24057. this.probesEnabled = true;
  24058. /**
  24059. * The list of reflection probes added to the scene
  24060. * @see http://doc.babylonjs.com/how_to/how_to_use_reflection_probes
  24061. */
  24062. this.reflectionProbes = new Array();
  24063. /** @hidden */
  24064. this._actionManagers = new Array();
  24065. this._meshesForIntersections = new BABYLON.SmartArrayNoDuplicate(256);
  24066. // Procedural textures
  24067. /**
  24068. * Gets or sets a boolean indicating if procedural textures are enabled on this scene
  24069. */
  24070. this.proceduralTexturesEnabled = true;
  24071. /**
  24072. * The list of procedural textures added to the scene
  24073. * @see http://doc.babylonjs.com/how_to/how_to_use_procedural_textures
  24074. */
  24075. this.proceduralTextures = new Array();
  24076. /**
  24077. * The list of sound tracks added to the scene
  24078. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  24079. */
  24080. this.soundTracks = new Array();
  24081. this._audioEnabled = true;
  24082. this._headphone = false;
  24083. // Performance counters
  24084. this._totalVertices = new BABYLON.PerfCounter();
  24085. /** @hidden */
  24086. this._activeIndices = new BABYLON.PerfCounter();
  24087. /** @hidden */
  24088. this._activeParticles = new BABYLON.PerfCounter();
  24089. /** @hidden */
  24090. this._activeBones = new BABYLON.PerfCounter();
  24091. this._animationTime = 0;
  24092. /**
  24093. * Gets or sets a general scale for animation speed
  24094. * @see https://www.babylonjs-playground.com/#IBU2W7#3
  24095. */
  24096. this.animationTimeScale = 1;
  24097. this._renderId = 0;
  24098. this._executeWhenReadyTimeoutId = -1;
  24099. this._intermediateRendering = false;
  24100. this._viewUpdateFlag = -1;
  24101. this._projectionUpdateFlag = -1;
  24102. this._alternateViewUpdateFlag = -1;
  24103. this._alternateProjectionUpdateFlag = -1;
  24104. /** @hidden */
  24105. this._toBeDisposed = new BABYLON.SmartArray(256);
  24106. this._activeRequests = new Array();
  24107. this._pendingData = new Array();
  24108. this._isDisposed = false;
  24109. /**
  24110. * Gets or sets a boolean indicating that all submeshes of active meshes must be rendered
  24111. * Use this boolean to avoid computing frustum clipping on submeshes (This could help when you are CPU bound)
  24112. */
  24113. this.dispatchAllSubMeshesOfActiveMeshes = false;
  24114. this._activeMeshes = new BABYLON.SmartArray(256);
  24115. this._processedMaterials = new BABYLON.SmartArray(256);
  24116. this._renderTargets = new BABYLON.SmartArrayNoDuplicate(256);
  24117. /** @hidden */
  24118. this._activeParticleSystems = new BABYLON.SmartArray(256);
  24119. this._activeSkeletons = new BABYLON.SmartArrayNoDuplicate(32);
  24120. this._softwareSkinnedMeshes = new BABYLON.SmartArrayNoDuplicate(32);
  24121. /** @hidden */
  24122. this._activeAnimatables = new Array();
  24123. this._transformMatrix = BABYLON.Matrix.Zero();
  24124. this._useAlternateCameraConfiguration = false;
  24125. this._alternateRendering = false;
  24126. /**
  24127. * Gets or sets a boolean indicating if lights must be sorted by priority (off by default)
  24128. * This is useful if there are more lights that the maximum simulteanous authorized
  24129. */
  24130. this.requireLightSorting = false;
  24131. this._depthRenderer = {};
  24132. this._activeMeshesFrozen = false;
  24133. this._tempPickingRay = BABYLON.Ray ? BABYLON.Ray.Zero() : null;
  24134. this._engine = engine || BABYLON.Engine.LastCreatedEngine;
  24135. this._engine.scenes.push(this);
  24136. this._uid = null;
  24137. this._renderingManager = new BABYLON.RenderingManager(this);
  24138. this.postProcessManager = new BABYLON.PostProcessManager(this);
  24139. if (BABYLON.OutlineRenderer) {
  24140. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  24141. }
  24142. if (BABYLON.Tools.IsWindowObjectExist()) {
  24143. this.attachControl();
  24144. }
  24145. //simplification queue
  24146. if (BABYLON.SimplificationQueue) {
  24147. this.simplificationQueue = new BABYLON.SimplificationQueue();
  24148. }
  24149. //collision coordinator initialization. For now legacy per default.
  24150. this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  24151. // Uniform Buffer
  24152. this._createUbo();
  24153. // Default Image processing definition.
  24154. this._imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  24155. }
  24156. Object.defineProperty(Scene, "FOGMODE_NONE", {
  24157. /** The fog is deactivated */
  24158. get: function () {
  24159. return Scene._FOGMODE_NONE;
  24160. },
  24161. enumerable: true,
  24162. configurable: true
  24163. });
  24164. Object.defineProperty(Scene, "FOGMODE_EXP", {
  24165. /** The fog density is following an exponential function */
  24166. get: function () {
  24167. return Scene._FOGMODE_EXP;
  24168. },
  24169. enumerable: true,
  24170. configurable: true
  24171. });
  24172. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  24173. /** The fog density is following an exponential function faster than FOGMODE_EXP */
  24174. get: function () {
  24175. return Scene._FOGMODE_EXP2;
  24176. },
  24177. enumerable: true,
  24178. configurable: true
  24179. });
  24180. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  24181. /** The fog density is following a linear function. */
  24182. get: function () {
  24183. return Scene._FOGMODE_LINEAR;
  24184. },
  24185. enumerable: true,
  24186. configurable: true
  24187. });
  24188. Object.defineProperty(Scene.prototype, "environmentTexture", {
  24189. /**
  24190. * Texture used in all pbr material as the reflection texture.
  24191. * As in the majority of the scene they are the same (exception for multi room and so on),
  24192. * this is easier to reference from here than from all the materials.
  24193. */
  24194. get: function () {
  24195. return this._environmentTexture;
  24196. },
  24197. /**
  24198. * Texture used in all pbr material as the reflection texture.
  24199. * As in the majority of the scene they are the same (exception for multi room and so on),
  24200. * this is easier to set here than in all the materials.
  24201. */
  24202. set: function (value) {
  24203. if (this._environmentTexture === value) {
  24204. return;
  24205. }
  24206. this._environmentTexture = value;
  24207. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  24208. },
  24209. enumerable: true,
  24210. configurable: true
  24211. });
  24212. Object.defineProperty(Scene.prototype, "imageProcessingConfiguration", {
  24213. /**
  24214. * Default image processing configuration used either in the rendering
  24215. * Forward main pass or through the imageProcessingPostProcess if present.
  24216. * As in the majority of the scene they are the same (exception for multi camera),
  24217. * this is easier to reference from here than from all the materials and post process.
  24218. *
  24219. * No setter as we it is a shared configuration, you can set the values instead.
  24220. */
  24221. get: function () {
  24222. return this._imageProcessingConfiguration;
  24223. },
  24224. enumerable: true,
  24225. configurable: true
  24226. });
  24227. Object.defineProperty(Scene.prototype, "forceWireframe", {
  24228. get: function () {
  24229. return this._forceWireframe;
  24230. },
  24231. /**
  24232. * Gets or sets a boolean indicating if all rendering must be done in wireframe
  24233. */
  24234. set: function (value) {
  24235. if (this._forceWireframe === value) {
  24236. return;
  24237. }
  24238. this._forceWireframe = value;
  24239. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24240. },
  24241. enumerable: true,
  24242. configurable: true
  24243. });
  24244. Object.defineProperty(Scene.prototype, "forcePointsCloud", {
  24245. get: function () {
  24246. return this._forcePointsCloud;
  24247. },
  24248. /**
  24249. * Gets or sets a boolean indicating if all rendering must be done in point cloud
  24250. */
  24251. set: function (value) {
  24252. if (this._forcePointsCloud === value) {
  24253. return;
  24254. }
  24255. this._forcePointsCloud = value;
  24256. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24257. },
  24258. enumerable: true,
  24259. configurable: true
  24260. });
  24261. Object.defineProperty(Scene.prototype, "animationPropertiesOverride", {
  24262. /**
  24263. * Gets or sets the animation properties override
  24264. */
  24265. get: function () {
  24266. return this._animationPropertiesOverride;
  24267. },
  24268. set: function (value) {
  24269. this._animationPropertiesOverride = value;
  24270. },
  24271. enumerable: true,
  24272. configurable: true
  24273. });
  24274. Object.defineProperty(Scene.prototype, "onDispose", {
  24275. /** Sets a function to be executed when this scene is disposed. */
  24276. set: function (callback) {
  24277. if (this._onDisposeObserver) {
  24278. this.onDisposeObservable.remove(this._onDisposeObserver);
  24279. }
  24280. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  24281. },
  24282. enumerable: true,
  24283. configurable: true
  24284. });
  24285. Object.defineProperty(Scene.prototype, "beforeRender", {
  24286. /** Sets a function to be executed before rendering this scene */
  24287. set: function (callback) {
  24288. if (this._onBeforeRenderObserver) {
  24289. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  24290. }
  24291. if (callback) {
  24292. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  24293. }
  24294. },
  24295. enumerable: true,
  24296. configurable: true
  24297. });
  24298. Object.defineProperty(Scene.prototype, "afterRender", {
  24299. /** Sets a function to be executed after rendering this scene */
  24300. set: function (callback) {
  24301. if (this._onAfterRenderObserver) {
  24302. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  24303. }
  24304. if (callback) {
  24305. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  24306. }
  24307. },
  24308. enumerable: true,
  24309. configurable: true
  24310. });
  24311. Object.defineProperty(Scene.prototype, "beforeCameraRender", {
  24312. /** Sets a function to be executed before rendering a camera*/
  24313. set: function (callback) {
  24314. if (this._onBeforeCameraRenderObserver) {
  24315. this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  24316. }
  24317. this._onBeforeCameraRenderObserver = this.onBeforeCameraRenderObservable.add(callback);
  24318. },
  24319. enumerable: true,
  24320. configurable: true
  24321. });
  24322. Object.defineProperty(Scene.prototype, "afterCameraRender", {
  24323. /** Sets a function to be executed after rendering a camera*/
  24324. set: function (callback) {
  24325. if (this._onAfterCameraRenderObserver) {
  24326. this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  24327. }
  24328. this._onAfterCameraRenderObserver = this.onAfterCameraRenderObservable.add(callback);
  24329. },
  24330. enumerable: true,
  24331. configurable: true
  24332. });
  24333. Object.defineProperty(Scene.prototype, "gamepadManager", {
  24334. /**
  24335. * Gets the gamepad manager associated with the scene
  24336. * @see http://doc.babylonjs.com/how_to/how_to_use_gamepads
  24337. */
  24338. get: function () {
  24339. if (!this._gamepadManager) {
  24340. this._gamepadManager = new BABYLON.GamepadManager(this);
  24341. }
  24342. return this._gamepadManager;
  24343. },
  24344. enumerable: true,
  24345. configurable: true
  24346. });
  24347. Object.defineProperty(Scene.prototype, "unTranslatedPointer", {
  24348. /**
  24349. * Gets the pointer coordinates without any translation (ie. straight out of the pointer event)
  24350. */
  24351. get: function () {
  24352. return new BABYLON.Vector2(this._unTranslatedPointerX, this._unTranslatedPointerY);
  24353. },
  24354. enumerable: true,
  24355. configurable: true
  24356. });
  24357. Object.defineProperty(Scene.prototype, "useRightHandedSystem", {
  24358. get: function () {
  24359. return this._useRightHandedSystem;
  24360. },
  24361. /**
  24362. * Gets or sets a boolean indicating if the scene must use right-handed coordinates system
  24363. */
  24364. set: function (value) {
  24365. if (this._useRightHandedSystem === value) {
  24366. return;
  24367. }
  24368. this._useRightHandedSystem = value;
  24369. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24370. },
  24371. enumerable: true,
  24372. configurable: true
  24373. });
  24374. /**
  24375. * Sets the step Id used by deterministic lock step
  24376. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  24377. * @param newStepId defines the step Id
  24378. */
  24379. Scene.prototype.setStepId = function (newStepId) {
  24380. this._currentStepId = newStepId;
  24381. };
  24382. ;
  24383. /**
  24384. * Gets the step Id used by deterministic lock step
  24385. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  24386. * @returns the step Id
  24387. */
  24388. Scene.prototype.getStepId = function () {
  24389. return this._currentStepId;
  24390. };
  24391. ;
  24392. /**
  24393. * Gets the internal step used by deterministic lock step
  24394. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  24395. * @returns the internal step
  24396. */
  24397. Scene.prototype.getInternalStep = function () {
  24398. return this._currentInternalStep;
  24399. };
  24400. ;
  24401. Object.defineProperty(Scene.prototype, "fogEnabled", {
  24402. get: function () {
  24403. return this._fogEnabled;
  24404. },
  24405. /**
  24406. * Gets or sets a boolean indicating if fog is enabled on this scene
  24407. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24408. */
  24409. set: function (value) {
  24410. if (this._fogEnabled === value) {
  24411. return;
  24412. }
  24413. this._fogEnabled = value;
  24414. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24415. },
  24416. enumerable: true,
  24417. configurable: true
  24418. });
  24419. Object.defineProperty(Scene.prototype, "fogMode", {
  24420. get: function () {
  24421. return this._fogMode;
  24422. },
  24423. /**
  24424. * Gets or sets the fog mode to use
  24425. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24426. */
  24427. set: function (value) {
  24428. if (this._fogMode === value) {
  24429. return;
  24430. }
  24431. this._fogMode = value;
  24432. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24433. },
  24434. enumerable: true,
  24435. configurable: true
  24436. });
  24437. Object.defineProperty(Scene.prototype, "shadowsEnabled", {
  24438. get: function () {
  24439. return this._shadowsEnabled;
  24440. },
  24441. /**
  24442. * Gets or sets a boolean indicating if shadows are enabled on this scene
  24443. */
  24444. set: function (value) {
  24445. if (this._shadowsEnabled === value) {
  24446. return;
  24447. }
  24448. this._shadowsEnabled = value;
  24449. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  24450. },
  24451. enumerable: true,
  24452. configurable: true
  24453. });
  24454. Object.defineProperty(Scene.prototype, "lightsEnabled", {
  24455. get: function () {
  24456. return this._lightsEnabled;
  24457. },
  24458. /**
  24459. * Gets or sets a boolean indicating if lights are enabled on this scene
  24460. */
  24461. set: function (value) {
  24462. if (this._lightsEnabled === value) {
  24463. return;
  24464. }
  24465. this._lightsEnabled = value;
  24466. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  24467. },
  24468. enumerable: true,
  24469. configurable: true
  24470. });
  24471. Object.defineProperty(Scene.prototype, "defaultMaterial", {
  24472. /** The default material used on meshes when no material is affected */
  24473. get: function () {
  24474. if (!this._defaultMaterial) {
  24475. this._defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  24476. }
  24477. return this._defaultMaterial;
  24478. },
  24479. /** The default material used on meshes when no material is affected */
  24480. set: function (value) {
  24481. this._defaultMaterial = value;
  24482. },
  24483. enumerable: true,
  24484. configurable: true
  24485. });
  24486. Object.defineProperty(Scene.prototype, "texturesEnabled", {
  24487. get: function () {
  24488. return this._texturesEnabled;
  24489. },
  24490. /**
  24491. * Gets or sets a boolean indicating if textures are enabled on this scene
  24492. */
  24493. set: function (value) {
  24494. if (this._texturesEnabled === value) {
  24495. return;
  24496. }
  24497. this._texturesEnabled = value;
  24498. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  24499. },
  24500. enumerable: true,
  24501. configurable: true
  24502. });
  24503. Object.defineProperty(Scene.prototype, "skeletonsEnabled", {
  24504. get: function () {
  24505. return this._skeletonsEnabled;
  24506. },
  24507. /**
  24508. * Gets or sets a boolean indicating if skeletons are enabled on this scene
  24509. */
  24510. set: function (value) {
  24511. if (this._skeletonsEnabled === value) {
  24512. return;
  24513. }
  24514. this._skeletonsEnabled = value;
  24515. this.markAllMaterialsAsDirty(BABYLON.Material.AttributesDirtyFlag);
  24516. },
  24517. enumerable: true,
  24518. configurable: true
  24519. });
  24520. Object.defineProperty(Scene.prototype, "postProcessRenderPipelineManager", {
  24521. /**
  24522. * Gets the postprocess render pipeline manager
  24523. * @see http://doc.babylonjs.com/how_to/how_to_use_postprocessrenderpipeline
  24524. * @see http://doc.babylonjs.com/how_to/using_default_rendering_pipeline
  24525. */
  24526. get: function () {
  24527. if (!this._postProcessRenderPipelineManager) {
  24528. this._postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  24529. }
  24530. return this._postProcessRenderPipelineManager;
  24531. },
  24532. enumerable: true,
  24533. configurable: true
  24534. });
  24535. Object.defineProperty(Scene.prototype, "mainSoundTrack", {
  24536. /**
  24537. * Gets the main soundtrack associated with the scene
  24538. */
  24539. get: function () {
  24540. if (!this._mainSoundTrack) {
  24541. this._mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  24542. }
  24543. return this._mainSoundTrack;
  24544. },
  24545. enumerable: true,
  24546. configurable: true
  24547. });
  24548. Object.defineProperty(Scene.prototype, "_isAlternateRenderingEnabled", {
  24549. /** @hidden */
  24550. get: function () {
  24551. return this._alternateRendering;
  24552. },
  24553. enumerable: true,
  24554. configurable: true
  24555. });
  24556. Object.defineProperty(Scene.prototype, "frustumPlanes", {
  24557. /**
  24558. * Gets the list of frustum planes (built from the active camera)
  24559. */
  24560. get: function () {
  24561. return this._frustumPlanes;
  24562. },
  24563. enumerable: true,
  24564. configurable: true
  24565. });
  24566. Object.defineProperty(Scene.prototype, "geometryBufferRenderer", {
  24567. /**
  24568. * Gets the current geometry buffer associated to the scene.
  24569. */
  24570. get: function () {
  24571. return this._geometryBufferRenderer;
  24572. },
  24573. /**
  24574. * Sets the current geometry buffer for the scene.
  24575. */
  24576. set: function (geometryBufferRenderer) {
  24577. if (geometryBufferRenderer && geometryBufferRenderer.isSupported) {
  24578. this._geometryBufferRenderer = geometryBufferRenderer;
  24579. }
  24580. },
  24581. enumerable: true,
  24582. configurable: true
  24583. });
  24584. Object.defineProperty(Scene.prototype, "debugLayer", {
  24585. /**
  24586. * Gets the debug layer associated with the scene
  24587. * @see http://doc.babylonjs.com/features/playground_debuglayer
  24588. */
  24589. get: function () {
  24590. if (!this._debugLayer) {
  24591. this._debugLayer = new BABYLON.DebugLayer(this);
  24592. }
  24593. return this._debugLayer;
  24594. },
  24595. enumerable: true,
  24596. configurable: true
  24597. });
  24598. Object.defineProperty(Scene.prototype, "workerCollisions", {
  24599. /**
  24600. * Gets a boolean indicating if collisions are processed on a web worker
  24601. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity#web-worker-based-collision-system-since-21
  24602. */
  24603. get: function () {
  24604. return this._workerCollisions;
  24605. },
  24606. set: function (enabled) {
  24607. if (!BABYLON.CollisionCoordinatorLegacy) {
  24608. return;
  24609. }
  24610. enabled = (enabled && !!Worker && !!BABYLON.CollisionWorker);
  24611. this._workerCollisions = enabled;
  24612. if (this.collisionCoordinator) {
  24613. this.collisionCoordinator.destroy();
  24614. }
  24615. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  24616. this.collisionCoordinator.init(this);
  24617. },
  24618. enumerable: true,
  24619. configurable: true
  24620. });
  24621. Object.defineProperty(Scene.prototype, "selectionOctree", {
  24622. /**
  24623. * Gets the octree used to boost mesh selection (picking)
  24624. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees
  24625. */
  24626. get: function () {
  24627. return this._selectionOctree;
  24628. },
  24629. enumerable: true,
  24630. configurable: true
  24631. });
  24632. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  24633. /**
  24634. * Gets the mesh that is currently under the pointer
  24635. */
  24636. get: function () {
  24637. return this._pointerOverMesh;
  24638. },
  24639. enumerable: true,
  24640. configurable: true
  24641. });
  24642. Object.defineProperty(Scene.prototype, "pointerX", {
  24643. /**
  24644. * Gets the current on-screen X position of the pointer
  24645. */
  24646. get: function () {
  24647. return this._pointerX;
  24648. },
  24649. enumerable: true,
  24650. configurable: true
  24651. });
  24652. Object.defineProperty(Scene.prototype, "pointerY", {
  24653. /**
  24654. * Gets the current on-screen Y position of the pointer
  24655. */
  24656. get: function () {
  24657. return this._pointerY;
  24658. },
  24659. enumerable: true,
  24660. configurable: true
  24661. });
  24662. /**
  24663. * Gets the cached material (ie. the latest rendered one)
  24664. * @returns the cached material
  24665. */
  24666. Scene.prototype.getCachedMaterial = function () {
  24667. return this._cachedMaterial;
  24668. };
  24669. /**
  24670. * Gets the cached effect (ie. the latest rendered one)
  24671. * @returns the cached effect
  24672. */
  24673. Scene.prototype.getCachedEffect = function () {
  24674. return this._cachedEffect;
  24675. };
  24676. /**
  24677. * Gets the cached visibility state (ie. the latest rendered one)
  24678. * @returns the cached visibility state
  24679. */
  24680. Scene.prototype.getCachedVisibility = function () {
  24681. return this._cachedVisibility;
  24682. };
  24683. /**
  24684. * Gets a boolean indicating if the current material / effect / visibility must be bind again
  24685. * @param material defines the current material
  24686. * @param effect defines the current effect
  24687. * @param visibility defines the current visibility state
  24688. * @returns true if one parameter is not cached
  24689. */
  24690. Scene.prototype.isCachedMaterialInvalid = function (material, effect, visibility) {
  24691. if (visibility === void 0) { visibility = 1; }
  24692. return this._cachedEffect !== effect || this._cachedMaterial !== material || this._cachedVisibility !== visibility;
  24693. };
  24694. /**
  24695. * Gets the bounding box renderer associated with the scene
  24696. * @returns a BoundingBoxRenderer
  24697. */
  24698. Scene.prototype.getBoundingBoxRenderer = function () {
  24699. if (!this._boundingBoxRenderer) {
  24700. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  24701. }
  24702. return this._boundingBoxRenderer;
  24703. };
  24704. /**
  24705. * Gets the outline renderer associated with the scene
  24706. * @returns a OutlineRenderer
  24707. */
  24708. Scene.prototype.getOutlineRenderer = function () {
  24709. return this._outlineRenderer;
  24710. };
  24711. /**
  24712. * Gets the engine associated with the scene
  24713. * @returns an Engine
  24714. */
  24715. Scene.prototype.getEngine = function () {
  24716. return this._engine;
  24717. };
  24718. /**
  24719. * Gets the total number of vertices rendered per frame
  24720. * @returns the total number of vertices rendered per frame
  24721. */
  24722. Scene.prototype.getTotalVertices = function () {
  24723. return this._totalVertices.current;
  24724. };
  24725. Object.defineProperty(Scene.prototype, "totalVerticesPerfCounter", {
  24726. /**
  24727. * Gets the performance counter for total vertices
  24728. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  24729. */
  24730. get: function () {
  24731. return this._totalVertices;
  24732. },
  24733. enumerable: true,
  24734. configurable: true
  24735. });
  24736. /**
  24737. * Gets the total number of active indices rendered per frame (You can deduce the number of rendered triangles by dividing this number by 3)
  24738. * @returns the total number of active indices rendered per frame
  24739. */
  24740. Scene.prototype.getActiveIndices = function () {
  24741. return this._activeIndices.current;
  24742. };
  24743. Object.defineProperty(Scene.prototype, "totalActiveIndicesPerfCounter", {
  24744. /**
  24745. * Gets the performance counter for active indices
  24746. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  24747. */
  24748. get: function () {
  24749. return this._activeIndices;
  24750. },
  24751. enumerable: true,
  24752. configurable: true
  24753. });
  24754. /**
  24755. * Gets the total number of active particles rendered per frame
  24756. * @returns the total number of active particles rendered per frame
  24757. */
  24758. Scene.prototype.getActiveParticles = function () {
  24759. return this._activeParticles.current;
  24760. };
  24761. Object.defineProperty(Scene.prototype, "activeParticlesPerfCounter", {
  24762. /**
  24763. * Gets the performance counter for active particles
  24764. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  24765. */
  24766. get: function () {
  24767. return this._activeParticles;
  24768. },
  24769. enumerable: true,
  24770. configurable: true
  24771. });
  24772. /**
  24773. * Gets the total number of active bones rendered per frame
  24774. * @returns the total number of active bones rendered per frame
  24775. */
  24776. Scene.prototype.getActiveBones = function () {
  24777. return this._activeBones.current;
  24778. };
  24779. Object.defineProperty(Scene.prototype, "activeBonesPerfCounter", {
  24780. /**
  24781. * Gets the performance counter for active bones
  24782. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  24783. */
  24784. get: function () {
  24785. return this._activeBones;
  24786. },
  24787. enumerable: true,
  24788. configurable: true
  24789. });
  24790. /** @hidden */
  24791. Scene.prototype.getInterFramePerfCounter = function () {
  24792. BABYLON.Tools.Warn("getInterFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  24793. return 0;
  24794. };
  24795. Object.defineProperty(Scene.prototype, "interFramePerfCounter", {
  24796. /** @hidden */
  24797. get: function () {
  24798. BABYLON.Tools.Warn("interFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  24799. return null;
  24800. },
  24801. enumerable: true,
  24802. configurable: true
  24803. });
  24804. /** @hidden */
  24805. Scene.prototype.getLastFrameDuration = function () {
  24806. BABYLON.Tools.Warn("getLastFrameDuration is deprecated. Please use SceneInstrumentation class");
  24807. return 0;
  24808. };
  24809. Object.defineProperty(Scene.prototype, "lastFramePerfCounter", {
  24810. /** @hidden */
  24811. get: function () {
  24812. BABYLON.Tools.Warn("lastFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  24813. return null;
  24814. },
  24815. enumerable: true,
  24816. configurable: true
  24817. });
  24818. /** @hidden */
  24819. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  24820. BABYLON.Tools.Warn("getEvaluateActiveMeshesDuration is deprecated. Please use SceneInstrumentation class");
  24821. return 0;
  24822. };
  24823. Object.defineProperty(Scene.prototype, "evaluateActiveMeshesDurationPerfCounter", {
  24824. /** @hidden */
  24825. get: function () {
  24826. BABYLON.Tools.Warn("evaluateActiveMeshesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  24827. return null;
  24828. },
  24829. enumerable: true,
  24830. configurable: true
  24831. });
  24832. /**
  24833. * Gets the array of active meshes
  24834. * @returns an array of AbstractMesh
  24835. */
  24836. Scene.prototype.getActiveMeshes = function () {
  24837. return this._activeMeshes;
  24838. };
  24839. /** @hidden */
  24840. Scene.prototype.getRenderTargetsDuration = function () {
  24841. BABYLON.Tools.Warn("getRenderTargetsDuration is deprecated. Please use SceneInstrumentation class");
  24842. return 0;
  24843. };
  24844. /** @hidden */
  24845. Scene.prototype.getRenderDuration = function () {
  24846. BABYLON.Tools.Warn("getRenderDuration is deprecated. Please use SceneInstrumentation class");
  24847. return 0;
  24848. };
  24849. Object.defineProperty(Scene.prototype, "renderDurationPerfCounter", {
  24850. /** @hidden */
  24851. get: function () {
  24852. BABYLON.Tools.Warn("renderDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  24853. return null;
  24854. },
  24855. enumerable: true,
  24856. configurable: true
  24857. });
  24858. /** @hidden */
  24859. Scene.prototype.getParticlesDuration = function () {
  24860. BABYLON.Tools.Warn("getParticlesDuration is deprecated. Please use SceneInstrumentation class");
  24861. return 0;
  24862. };
  24863. Object.defineProperty(Scene.prototype, "particlesDurationPerfCounter", {
  24864. /** @hidden */
  24865. get: function () {
  24866. BABYLON.Tools.Warn("particlesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  24867. return null;
  24868. },
  24869. enumerable: true,
  24870. configurable: true
  24871. });
  24872. /** @hidden */
  24873. Scene.prototype.getSpritesDuration = function () {
  24874. BABYLON.Tools.Warn("getSpritesDuration is deprecated. Please use SceneInstrumentation class");
  24875. return 0;
  24876. };
  24877. Object.defineProperty(Scene.prototype, "spriteDuractionPerfCounter", {
  24878. /** @hidden */
  24879. get: function () {
  24880. BABYLON.Tools.Warn("spriteDuractionPerfCounter is deprecated. Please use SceneInstrumentation class");
  24881. return null;
  24882. },
  24883. enumerable: true,
  24884. configurable: true
  24885. });
  24886. /**
  24887. * Gets the animation ratio (which is 1.0 is the scene renders at 60fps and 2 if the scene renders at 30fps, etc.)
  24888. * @returns a number
  24889. */
  24890. Scene.prototype.getAnimationRatio = function () {
  24891. return this._animationRatio;
  24892. };
  24893. /**
  24894. * Gets an unique Id for the current frame
  24895. * @returns a number
  24896. */
  24897. Scene.prototype.getRenderId = function () {
  24898. return this._renderId;
  24899. };
  24900. /** Call this function if you want to manually increment the render Id*/
  24901. Scene.prototype.incrementRenderId = function () {
  24902. this._renderId++;
  24903. };
  24904. Scene.prototype._updatePointerPosition = function (evt) {
  24905. var canvasRect = this._engine.getRenderingCanvasClientRect();
  24906. if (!canvasRect) {
  24907. return;
  24908. }
  24909. this._pointerX = evt.clientX - canvasRect.left;
  24910. this._pointerY = evt.clientY - canvasRect.top;
  24911. this._unTranslatedPointerX = this._pointerX;
  24912. this._unTranslatedPointerY = this._pointerY;
  24913. };
  24914. Scene.prototype._createUbo = function () {
  24915. this._sceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  24916. this._sceneUbo.addUniform("viewProjection", 16);
  24917. this._sceneUbo.addUniform("view", 16);
  24918. };
  24919. Scene.prototype._createAlternateUbo = function () {
  24920. this._alternateSceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  24921. this._alternateSceneUbo.addUniform("viewProjection", 16);
  24922. this._alternateSceneUbo.addUniform("view", 16);
  24923. };
  24924. // Pointers handling
  24925. Scene.prototype._pickSpriteButKeepRay = function (originalPointerInfo, x, y, predicate, fastCheck, camera) {
  24926. var result = this.pickSprite(x, y, predicate, fastCheck, camera);
  24927. if (result) {
  24928. result.ray = originalPointerInfo ? originalPointerInfo.ray : null;
  24929. }
  24930. return result;
  24931. };
  24932. Scene.prototype._setRayOnPointerInfo = function (pointerInfo) {
  24933. if (pointerInfo.pickInfo) {
  24934. if (!pointerInfo.pickInfo.ray) {
  24935. pointerInfo.pickInfo.ray = this.createPickingRay(pointerInfo.event.offsetX, pointerInfo.event.offsetY, BABYLON.Matrix.Identity(), this.activeCamera);
  24936. }
  24937. }
  24938. };
  24939. /**
  24940. * Use this method to simulate a pointer move on a mesh
  24941. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  24942. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  24943. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  24944. * @returns the current scene
  24945. */
  24946. Scene.prototype.simulatePointerMove = function (pickResult, pointerEventInit) {
  24947. var evt = new PointerEvent("pointermove", pointerEventInit);
  24948. if (this._checkPrePointerObservable(pickResult, evt, BABYLON.PointerEventTypes.POINTERMOVE)) {
  24949. return this;
  24950. }
  24951. return this._processPointerMove(pickResult, evt);
  24952. };
  24953. Scene.prototype._processPointerMove = function (pickResult, evt) {
  24954. var canvas = this._engine.getRenderingCanvas();
  24955. if (!canvas) {
  24956. return this;
  24957. }
  24958. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  24959. this.setPointerOverSprite(null);
  24960. this.setPointerOverMesh(pickResult.pickedMesh);
  24961. if (this._pointerOverMesh && this._pointerOverMesh.actionManager && this._pointerOverMesh.actionManager.hasPointerTriggers) {
  24962. if (this._pointerOverMesh.actionManager.hoverCursor) {
  24963. canvas.style.cursor = this._pointerOverMesh.actionManager.hoverCursor;
  24964. }
  24965. else {
  24966. canvas.style.cursor = this.hoverCursor;
  24967. }
  24968. }
  24969. else {
  24970. canvas.style.cursor = this.defaultCursor;
  24971. }
  24972. }
  24973. else {
  24974. this.setPointerOverMesh(null);
  24975. // Sprites
  24976. pickResult = this._pickSpriteButKeepRay(pickResult, this._unTranslatedPointerX, this._unTranslatedPointerY, this._spritePredicate, false, this.cameraToUseForPointers || undefined);
  24977. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  24978. this.setPointerOverSprite(pickResult.pickedSprite);
  24979. if (this._pointerOverSprite && this._pointerOverSprite.actionManager && this._pointerOverSprite.actionManager.hoverCursor) {
  24980. canvas.style.cursor = this._pointerOverSprite.actionManager.hoverCursor;
  24981. }
  24982. else {
  24983. canvas.style.cursor = this.hoverCursor;
  24984. }
  24985. }
  24986. else {
  24987. this.setPointerOverSprite(null);
  24988. // Restore pointer
  24989. canvas.style.cursor = this.defaultCursor;
  24990. }
  24991. }
  24992. if (pickResult) {
  24993. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  24994. if (this.onPointerMove) {
  24995. this.onPointerMove(evt, pickResult, type);
  24996. }
  24997. if (this.onPointerObservable.hasObservers()) {
  24998. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  24999. this._setRayOnPointerInfo(pi);
  25000. this.onPointerObservable.notifyObservers(pi, type);
  25001. }
  25002. }
  25003. return this;
  25004. };
  25005. Scene.prototype._checkPrePointerObservable = function (pickResult, evt, type) {
  25006. var pi = new BABYLON.PointerInfoPre(type, evt, this._unTranslatedPointerX, this._unTranslatedPointerY);
  25007. if (pickResult) {
  25008. pi.ray = pickResult.ray;
  25009. }
  25010. this.onPrePointerObservable.notifyObservers(pi, type);
  25011. if (pi.skipOnPointerObservable) {
  25012. return true;
  25013. }
  25014. else {
  25015. return false;
  25016. }
  25017. };
  25018. /**
  25019. * Use this method to simulate a pointer down on a mesh
  25020. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  25021. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  25022. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  25023. * @returns the current scene
  25024. */
  25025. Scene.prototype.simulatePointerDown = function (pickResult, pointerEventInit) {
  25026. var evt = new PointerEvent("pointerdown", pointerEventInit);
  25027. if (this._checkPrePointerObservable(pickResult, evt, BABYLON.PointerEventTypes.POINTERDOWN)) {
  25028. return this;
  25029. }
  25030. return this._processPointerDown(pickResult, evt);
  25031. };
  25032. Scene.prototype._processPointerDown = function (pickResult, evt) {
  25033. var _this = this;
  25034. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  25035. this._pickedDownMesh = pickResult.pickedMesh;
  25036. var actionManager = pickResult.pickedMesh.actionManager;
  25037. if (actionManager) {
  25038. if (actionManager.hasPickTriggers) {
  25039. actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25040. switch (evt.button) {
  25041. case 0:
  25042. actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25043. break;
  25044. case 1:
  25045. actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25046. break;
  25047. case 2:
  25048. actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25049. break;
  25050. }
  25051. }
  25052. if (actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  25053. window.setTimeout(function () {
  25054. 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);
  25055. if (pickResult && pickResult.hit && pickResult.pickedMesh && actionManager) {
  25056. if (_this._totalPointersPressed !== 0 &&
  25057. ((Date.now() - _this._startingPointerTime) > Scene.LongPressDelay) &&
  25058. (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold &&
  25059. Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold)) {
  25060. _this._startingPointerTime = 0;
  25061. actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25062. }
  25063. }
  25064. }, Scene.LongPressDelay);
  25065. }
  25066. }
  25067. }
  25068. if (pickResult) {
  25069. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  25070. if (this.onPointerDown) {
  25071. this.onPointerDown(evt, pickResult, type);
  25072. }
  25073. if (this.onPointerObservable.hasObservers()) {
  25074. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  25075. this._setRayOnPointerInfo(pi);
  25076. this.onPointerObservable.notifyObservers(pi, type);
  25077. }
  25078. }
  25079. return this;
  25080. };
  25081. /**
  25082. * Use this method to simulate a pointer up on a mesh
  25083. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  25084. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  25085. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  25086. * @returns the current scene
  25087. */
  25088. Scene.prototype.simulatePointerUp = function (pickResult, pointerEventInit) {
  25089. var evt = new PointerEvent("pointerup", pointerEventInit);
  25090. var clickInfo = new ClickInfo();
  25091. clickInfo.singleClick = true;
  25092. clickInfo.ignore = true;
  25093. if (this._checkPrePointerObservable(pickResult, evt, BABYLON.PointerEventTypes.POINTERUP)) {
  25094. return this;
  25095. }
  25096. return this._processPointerUp(pickResult, evt, clickInfo);
  25097. };
  25098. Scene.prototype._processPointerUp = function (pickResult, evt, clickInfo) {
  25099. if (pickResult && pickResult && pickResult.pickedMesh) {
  25100. this._pickedUpMesh = pickResult.pickedMesh;
  25101. if (this._pickedDownMesh === this._pickedUpMesh) {
  25102. if (this.onPointerPick) {
  25103. this.onPointerPick(evt, pickResult);
  25104. }
  25105. if (clickInfo.singleClick && !clickInfo.ignore && this.onPointerObservable.hasObservers()) {
  25106. var type_1 = BABYLON.PointerEventTypes.POINTERPICK;
  25107. var pi = new BABYLON.PointerInfo(type_1, evt, pickResult);
  25108. this._setRayOnPointerInfo(pi);
  25109. this.onPointerObservable.notifyObservers(pi, type_1);
  25110. }
  25111. }
  25112. if (pickResult.pickedMesh.actionManager) {
  25113. if (clickInfo.ignore) {
  25114. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25115. }
  25116. if (!clickInfo.hasSwiped && !clickInfo.ignore && clickInfo.singleClick) {
  25117. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25118. }
  25119. if (clickInfo.doubleClick && !clickInfo.ignore && pickResult.pickedMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  25120. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnDoublePickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25121. }
  25122. }
  25123. }
  25124. if (this._pickedDownMesh &&
  25125. this._pickedDownMesh.actionManager &&
  25126. this._pickedDownMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnPickOutTrigger) &&
  25127. this._pickedDownMesh !== this._pickedUpMesh) {
  25128. this._pickedDownMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNew(this._pickedDownMesh, evt));
  25129. }
  25130. var type = BABYLON.PointerEventTypes.POINTERUP;
  25131. if (this.onPointerObservable.hasObservers()) {
  25132. if (!clickInfo.ignore) {
  25133. if (!clickInfo.hasSwiped) {
  25134. if (clickInfo.singleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  25135. var type_2 = BABYLON.PointerEventTypes.POINTERTAP;
  25136. var pi = new BABYLON.PointerInfo(type_2, evt, pickResult);
  25137. this._setRayOnPointerInfo(pi);
  25138. this.onPointerObservable.notifyObservers(pi, type_2);
  25139. }
  25140. if (clickInfo.doubleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  25141. var type_3 = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  25142. var pi = new BABYLON.PointerInfo(type_3, evt, pickResult);
  25143. this._setRayOnPointerInfo(pi);
  25144. this.onPointerObservable.notifyObservers(pi, type_3);
  25145. }
  25146. }
  25147. }
  25148. else {
  25149. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  25150. this._setRayOnPointerInfo(pi);
  25151. this.onPointerObservable.notifyObservers(pi, type);
  25152. }
  25153. }
  25154. if (this.onPointerUp) {
  25155. this.onPointerUp(evt, pickResult, type);
  25156. }
  25157. return this;
  25158. };
  25159. /**
  25160. * Gets a boolean indicating if the current pointer event is captured (meaning that the scene has already handled the pointer down)
  25161. * @param pointerId defines the pointer id to use in a multi-touch scenario (0 by default)
  25162. * @returns true if the pointer was captured
  25163. */
  25164. Scene.prototype.isPointerCaptured = function (pointerId) {
  25165. if (pointerId === void 0) { pointerId = 0; }
  25166. return this._pointerCaptures[pointerId];
  25167. };
  25168. /**
  25169. * Attach events to the canvas (To handle actionManagers triggers and raise onPointerMove, onPointerDown and onPointerUp
  25170. * @param attachUp defines if you want to attach events to pointerup
  25171. * @param attachDown defines if you want to attach events to pointerdown
  25172. * @param attachMove defines if you want to attach events to pointermove
  25173. */
  25174. Scene.prototype.attachControl = function (attachUp, attachDown, attachMove) {
  25175. var _this = this;
  25176. if (attachUp === void 0) { attachUp = true; }
  25177. if (attachDown === void 0) { attachDown = true; }
  25178. if (attachMove === void 0) { attachMove = true; }
  25179. this._initActionManager = function (act, clickInfo) {
  25180. if (!_this._meshPickProceed) {
  25181. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  25182. _this._currentPickResult = pickResult;
  25183. if (pickResult) {
  25184. act = (pickResult.hit && pickResult.pickedMesh) ? pickResult.pickedMesh.actionManager : null;
  25185. }
  25186. _this._meshPickProceed = true;
  25187. }
  25188. return act;
  25189. };
  25190. this._delayedSimpleClick = function (btn, clickInfo, cb) {
  25191. // double click delay is over and that no double click has been raised since, or the 2 consecutive keys pressed are different
  25192. if ((Date.now() - _this._previousStartingPointerTime > Scene.DoubleClickDelay && !_this._doubleClickOccured) ||
  25193. btn !== _this._previousButtonPressed) {
  25194. _this._doubleClickOccured = false;
  25195. clickInfo.singleClick = true;
  25196. clickInfo.ignore = false;
  25197. cb(clickInfo, _this._currentPickResult);
  25198. }
  25199. };
  25200. this._initClickEvent = function (obs1, obs2, evt, cb) {
  25201. var clickInfo = new ClickInfo();
  25202. _this._currentPickResult = null;
  25203. var act = null;
  25204. var checkPicking = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK)
  25205. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)
  25206. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  25207. if (!checkPicking && BABYLON.ActionManager && BABYLON.ActionManager.HasPickTriggers) {
  25208. act = _this._initActionManager(act, clickInfo);
  25209. if (act)
  25210. checkPicking = act.hasPickTriggers;
  25211. }
  25212. if (checkPicking) {
  25213. var btn = evt.button;
  25214. clickInfo.hasSwiped = Math.abs(_this._startingPointerPosition.x - _this._pointerX) > Scene.DragMovementThreshold ||
  25215. Math.abs(_this._startingPointerPosition.y - _this._pointerY) > Scene.DragMovementThreshold;
  25216. if (!clickInfo.hasSwiped) {
  25217. var checkSingleClickImmediately = !Scene.ExclusiveDoubleClickMode;
  25218. if (!checkSingleClickImmediately) {
  25219. checkSingleClickImmediately = !obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) &&
  25220. !obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  25221. if (checkSingleClickImmediately && !BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  25222. act = _this._initActionManager(act, clickInfo);
  25223. if (act)
  25224. checkSingleClickImmediately = !act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  25225. }
  25226. }
  25227. if (checkSingleClickImmediately) {
  25228. // single click detected if double click delay is over or two different successive keys pressed without exclusive double click or no double click required
  25229. if (Date.now() - _this._previousStartingPointerTime > Scene.DoubleClickDelay ||
  25230. btn !== _this._previousButtonPressed) {
  25231. clickInfo.singleClick = true;
  25232. cb(clickInfo, _this._currentPickResult);
  25233. }
  25234. }
  25235. // at least one double click is required to be check and exclusive double click is enabled
  25236. else {
  25237. // wait that no double click has been raised during the double click delay
  25238. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  25239. _this._delayedSimpleClickTimeout = window.setTimeout(_this._delayedSimpleClick.bind(_this, btn, clickInfo, cb), Scene.DoubleClickDelay);
  25240. }
  25241. var checkDoubleClick = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) ||
  25242. obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  25243. if (!checkDoubleClick && BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  25244. act = _this._initActionManager(act, clickInfo);
  25245. if (act)
  25246. checkDoubleClick = act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  25247. }
  25248. if (checkDoubleClick) {
  25249. // two successive keys pressed are equal, double click delay is not over and double click has not just occurred
  25250. if (btn === _this._previousButtonPressed &&
  25251. Date.now() - _this._previousStartingPointerTime < Scene.DoubleClickDelay &&
  25252. !_this._doubleClickOccured) {
  25253. // pointer has not moved for 2 clicks, it's a double click
  25254. if (!clickInfo.hasSwiped &&
  25255. Math.abs(_this._previousStartingPointerPosition.x - _this._startingPointerPosition.x) < Scene.DragMovementThreshold &&
  25256. Math.abs(_this._previousStartingPointerPosition.y - _this._startingPointerPosition.y) < Scene.DragMovementThreshold) {
  25257. _this._previousStartingPointerTime = 0;
  25258. _this._doubleClickOccured = true;
  25259. clickInfo.doubleClick = true;
  25260. clickInfo.ignore = false;
  25261. if (Scene.ExclusiveDoubleClickMode && _this._previousDelayedSimpleClickTimeout) {
  25262. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  25263. }
  25264. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  25265. cb(clickInfo, _this._currentPickResult);
  25266. }
  25267. // if the two successive clicks are too far, it's just two simple clicks
  25268. else {
  25269. _this._doubleClickOccured = false;
  25270. _this._previousStartingPointerTime = _this._startingPointerTime;
  25271. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  25272. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  25273. _this._previousButtonPressed = btn;
  25274. if (Scene.ExclusiveDoubleClickMode) {
  25275. if (_this._previousDelayedSimpleClickTimeout) {
  25276. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  25277. }
  25278. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  25279. cb(clickInfo, _this._previousPickResult);
  25280. }
  25281. else {
  25282. cb(clickInfo, _this._currentPickResult);
  25283. }
  25284. }
  25285. }
  25286. // just the first click of the double has been raised
  25287. else {
  25288. _this._doubleClickOccured = false;
  25289. _this._previousStartingPointerTime = _this._startingPointerTime;
  25290. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  25291. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  25292. _this._previousButtonPressed = btn;
  25293. }
  25294. }
  25295. }
  25296. }
  25297. clickInfo.ignore = true;
  25298. cb(clickInfo, _this._currentPickResult);
  25299. };
  25300. this._spritePredicate = function (sprite) {
  25301. return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPointerTriggers;
  25302. };
  25303. this._onPointerMove = function (evt) {
  25304. _this._updatePointerPosition(evt);
  25305. // PreObservable support
  25306. if (_this._checkPrePointerObservable(null, evt, evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE)) {
  25307. return;
  25308. }
  25309. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  25310. return;
  25311. }
  25312. if (!_this.pointerMovePredicate) {
  25313. _this.pointerMovePredicate = function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled() && (mesh.enablePointerMoveEvents || _this.constantlyUpdateMeshUnderPointer || (mesh.actionManager !== null && mesh.actionManager !== undefined)); };
  25314. }
  25315. // Meshes
  25316. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerMovePredicate, false, _this.cameraToUseForPointers);
  25317. _this._processPointerMove(pickResult, evt);
  25318. };
  25319. this._onPointerDown = function (evt) {
  25320. _this._totalPointersPressed++;
  25321. _this._pickedDownMesh = null;
  25322. _this._meshPickProceed = false;
  25323. _this._updatePointerPosition(evt);
  25324. if (_this.preventDefaultOnPointerDown && canvas) {
  25325. evt.preventDefault();
  25326. canvas.focus();
  25327. }
  25328. // PreObservable support
  25329. if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERDOWN)) {
  25330. return;
  25331. }
  25332. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  25333. return;
  25334. }
  25335. _this._pointerCaptures[evt.pointerId] = true;
  25336. _this._startingPointerPosition.x = _this._pointerX;
  25337. _this._startingPointerPosition.y = _this._pointerY;
  25338. _this._startingPointerTime = Date.now();
  25339. if (!_this.pointerDownPredicate) {
  25340. _this.pointerDownPredicate = function (mesh) {
  25341. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  25342. };
  25343. }
  25344. // Meshes
  25345. _this._pickedDownMesh = null;
  25346. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  25347. _this._processPointerDown(pickResult, evt);
  25348. // Sprites
  25349. _this._pickedDownSprite = null;
  25350. if (_this.spriteManagers.length > 0) {
  25351. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  25352. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  25353. if (pickResult.pickedSprite.actionManager) {
  25354. _this._pickedDownSprite = pickResult.pickedSprite;
  25355. switch (evt.button) {
  25356. case 0:
  25357. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  25358. break;
  25359. case 1:
  25360. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  25361. break;
  25362. case 2:
  25363. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  25364. break;
  25365. }
  25366. if (pickResult.pickedSprite.actionManager) {
  25367. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  25368. }
  25369. }
  25370. }
  25371. }
  25372. };
  25373. this._onPointerUp = function (evt) {
  25374. if (_this._totalPointersPressed === 0) { // We are attaching the pointer up to windows because of a bug in FF
  25375. return; // So we need to test it the pointer down was pressed before.
  25376. }
  25377. _this._totalPointersPressed--;
  25378. _this._pickedUpMesh = null;
  25379. _this._meshPickProceed = false;
  25380. _this._updatePointerPosition(evt);
  25381. _this._initClickEvent(_this.onPrePointerObservable, _this.onPointerObservable, evt, function (clickInfo, pickResult) {
  25382. // PreObservable support
  25383. if (_this.onPrePointerObservable.hasObservers()) {
  25384. if (!clickInfo.ignore) {
  25385. if (!clickInfo.hasSwiped) {
  25386. if (clickInfo.singleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  25387. if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERTAP)) {
  25388. return;
  25389. }
  25390. }
  25391. if (clickInfo.doubleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  25392. if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  25393. return;
  25394. }
  25395. }
  25396. }
  25397. }
  25398. else {
  25399. if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERUP)) {
  25400. return;
  25401. }
  25402. }
  25403. }
  25404. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  25405. return;
  25406. }
  25407. _this._pointerCaptures[evt.pointerId] = false;
  25408. if (!_this.pointerUpPredicate) {
  25409. _this.pointerUpPredicate = function (mesh) {
  25410. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  25411. };
  25412. }
  25413. // Meshes
  25414. if (!_this._meshPickProceed && (BABYLON.ActionManager && BABYLON.ActionManager.HasTriggers || _this.onPointerObservable.hasObservers())) {
  25415. _this._initActionManager(null, clickInfo);
  25416. }
  25417. if (!pickResult) {
  25418. pickResult = _this._currentPickResult;
  25419. }
  25420. _this._processPointerUp(pickResult, evt, clickInfo);
  25421. // Sprites
  25422. if (!clickInfo.ignore) {
  25423. if (_this.spriteManagers.length > 0) {
  25424. var spritePickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  25425. if (spritePickResult) {
  25426. if (spritePickResult.hit && spritePickResult.pickedSprite) {
  25427. if (spritePickResult.pickedSprite.actionManager) {
  25428. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  25429. if (spritePickResult.pickedSprite.actionManager) {
  25430. if (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold && Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold) {
  25431. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  25432. }
  25433. }
  25434. }
  25435. }
  25436. if (_this._pickedDownSprite && _this._pickedDownSprite.actionManager && _this._pickedDownSprite !== spritePickResult.pickedSprite) {
  25437. _this._pickedDownSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(_this._pickedDownSprite, _this, evt));
  25438. }
  25439. }
  25440. }
  25441. }
  25442. _this._previousPickResult = _this._currentPickResult;
  25443. });
  25444. };
  25445. this._onKeyDown = function (evt) {
  25446. var type = BABYLON.KeyboardEventTypes.KEYDOWN;
  25447. if (_this.onPreKeyboardObservable.hasObservers()) {
  25448. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  25449. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  25450. if (pi.skipOnPointerObservable) {
  25451. return;
  25452. }
  25453. }
  25454. if (_this.onKeyboardObservable.hasObservers()) {
  25455. var pi = new BABYLON.KeyboardInfo(type, evt);
  25456. _this.onKeyboardObservable.notifyObservers(pi, type);
  25457. }
  25458. if (_this.actionManager) {
  25459. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  25460. }
  25461. };
  25462. this._onKeyUp = function (evt) {
  25463. var type = BABYLON.KeyboardEventTypes.KEYUP;
  25464. if (_this.onPreKeyboardObservable.hasObservers()) {
  25465. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  25466. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  25467. if (pi.skipOnPointerObservable) {
  25468. return;
  25469. }
  25470. }
  25471. if (_this.onKeyboardObservable.hasObservers()) {
  25472. var pi = new BABYLON.KeyboardInfo(type, evt);
  25473. _this.onKeyboardObservable.notifyObservers(pi, type);
  25474. }
  25475. if (_this.actionManager) {
  25476. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  25477. }
  25478. };
  25479. var engine = this.getEngine();
  25480. this._onCanvasFocusObserver = engine.onCanvasFocusObservable.add(function () {
  25481. if (!canvas) {
  25482. return;
  25483. }
  25484. canvas.addEventListener("keydown", _this._onKeyDown, false);
  25485. canvas.addEventListener("keyup", _this._onKeyUp, false);
  25486. });
  25487. this._onCanvasBlurObserver = engine.onCanvasBlurObservable.add(function () {
  25488. if (!canvas) {
  25489. return;
  25490. }
  25491. canvas.removeEventListener("keydown", _this._onKeyDown);
  25492. canvas.removeEventListener("keyup", _this._onKeyUp);
  25493. });
  25494. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  25495. var canvas = this._engine.getRenderingCanvas();
  25496. if (!canvas) {
  25497. return;
  25498. }
  25499. if (attachMove) {
  25500. canvas.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  25501. // Wheel
  25502. canvas.addEventListener('mousewheel', this._onPointerMove, false);
  25503. canvas.addEventListener('DOMMouseScroll', this._onPointerMove, false);
  25504. }
  25505. if (attachDown) {
  25506. canvas.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  25507. }
  25508. if (attachUp) {
  25509. window.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  25510. }
  25511. canvas.tabIndex = 1;
  25512. };
  25513. /** Detaches all event handlers*/
  25514. Scene.prototype.detachControl = function () {
  25515. var engine = this.getEngine();
  25516. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  25517. var canvas = engine.getRenderingCanvas();
  25518. if (!canvas) {
  25519. return;
  25520. }
  25521. canvas.removeEventListener(eventPrefix + "move", this._onPointerMove);
  25522. canvas.removeEventListener(eventPrefix + "down", this._onPointerDown);
  25523. window.removeEventListener(eventPrefix + "up", this._onPointerUp);
  25524. if (this._onCanvasBlurObserver) {
  25525. engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  25526. }
  25527. if (this._onCanvasFocusObserver) {
  25528. engine.onCanvasFocusObservable.remove(this._onCanvasFocusObserver);
  25529. }
  25530. // Wheel
  25531. canvas.removeEventListener('mousewheel', this._onPointerMove);
  25532. canvas.removeEventListener('DOMMouseScroll', this._onPointerMove);
  25533. // Keyboard
  25534. canvas.removeEventListener("keydown", this._onKeyDown);
  25535. canvas.removeEventListener("keyup", this._onKeyUp);
  25536. // Observables
  25537. this.onKeyboardObservable.clear();
  25538. this.onPreKeyboardObservable.clear();
  25539. this.onPointerObservable.clear();
  25540. this.onPrePointerObservable.clear();
  25541. };
  25542. /**
  25543. * This function will check if the scene can be rendered (textures are loaded, shaders are compiled)
  25544. * Delay loaded resources are not taking in account
  25545. * @return true if all required resources are ready
  25546. */
  25547. Scene.prototype.isReady = function () {
  25548. if (this._isDisposed) {
  25549. return false;
  25550. }
  25551. if (this._pendingData.length > 0) {
  25552. return false;
  25553. }
  25554. var index;
  25555. var engine = this.getEngine();
  25556. // Geometries
  25557. for (index = 0; index < this._geometries.length; index++) {
  25558. var geometry = this._geometries[index];
  25559. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  25560. return false;
  25561. }
  25562. }
  25563. // Meshes
  25564. for (index = 0; index < this.meshes.length; index++) {
  25565. var mesh = this.meshes[index];
  25566. if (!mesh.isEnabled()) {
  25567. continue;
  25568. }
  25569. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  25570. continue;
  25571. }
  25572. if (!mesh.isReady(true)) {
  25573. return false;
  25574. }
  25575. // Effect layers
  25576. var hardwareInstancedRendering = mesh.getClassName() === "InstancedMesh" || engine.getCaps().instancedArrays && mesh.instances.length > 0;
  25577. for (var _i = 0, _a = this.effectLayers; _i < _a.length; _i++) {
  25578. var layer = _a[_i];
  25579. if (!layer.hasMesh(mesh)) {
  25580. continue;
  25581. }
  25582. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  25583. var subMesh = _c[_b];
  25584. if (!layer.isReady(subMesh, hardwareInstancedRendering)) {
  25585. return false;
  25586. }
  25587. }
  25588. }
  25589. }
  25590. // Post-processes
  25591. if (this.activeCameras && this.activeCameras.length > 0) {
  25592. for (var _d = 0, _e = this.activeCameras; _d < _e.length; _d++) {
  25593. var camera = _e[_d];
  25594. if (!camera.isReady(true)) {
  25595. return false;
  25596. }
  25597. }
  25598. }
  25599. else if (this.activeCamera) {
  25600. if (!this.activeCamera.isReady(true)) {
  25601. return false;
  25602. }
  25603. }
  25604. // Particles
  25605. for (var _f = 0, _g = this.particleSystems; _f < _g.length; _f++) {
  25606. var particleSystem = _g[_f];
  25607. if (!particleSystem.isReady()) {
  25608. return false;
  25609. }
  25610. }
  25611. return true;
  25612. };
  25613. /** Resets all cached information relative to material (including effect and visibility) */
  25614. Scene.prototype.resetCachedMaterial = function () {
  25615. this._cachedMaterial = null;
  25616. this._cachedEffect = null;
  25617. this._cachedVisibility = null;
  25618. };
  25619. /**
  25620. * Registers a function to be called before every frame render
  25621. * @param func defines the function to register
  25622. */
  25623. Scene.prototype.registerBeforeRender = function (func) {
  25624. this.onBeforeRenderObservable.add(func);
  25625. };
  25626. /**
  25627. * Unregisters a function called before every frame render
  25628. * @param func defines the function to unregister
  25629. */
  25630. Scene.prototype.unregisterBeforeRender = function (func) {
  25631. this.onBeforeRenderObservable.removeCallback(func);
  25632. };
  25633. /**
  25634. * Registers a function to be called after every frame render
  25635. * @param func defines the function to register
  25636. */
  25637. Scene.prototype.registerAfterRender = function (func) {
  25638. this.onAfterRenderObservable.add(func);
  25639. };
  25640. /**
  25641. * Unregisters a function called after every frame render
  25642. * @param func defines the function to unregister
  25643. */
  25644. Scene.prototype.unregisterAfterRender = function (func) {
  25645. this.onAfterRenderObservable.removeCallback(func);
  25646. };
  25647. Scene.prototype._executeOnceBeforeRender = function (func) {
  25648. var _this = this;
  25649. var execFunc = function () {
  25650. func();
  25651. setTimeout(function () {
  25652. _this.unregisterBeforeRender(execFunc);
  25653. });
  25654. };
  25655. this.registerBeforeRender(execFunc);
  25656. };
  25657. /**
  25658. * The provided function will run before render once and will be disposed afterwards.
  25659. * A timeout delay can be provided so that the function will be executed in N ms.
  25660. * The timeout is using the browser's native setTimeout so time percision cannot be guaranteed.
  25661. * @param func The function to be executed.
  25662. * @param timeout optional delay in ms
  25663. */
  25664. Scene.prototype.executeOnceBeforeRender = function (func, timeout) {
  25665. var _this = this;
  25666. if (timeout !== undefined) {
  25667. setTimeout(function () {
  25668. _this._executeOnceBeforeRender(func);
  25669. }, timeout);
  25670. }
  25671. else {
  25672. this._executeOnceBeforeRender(func);
  25673. }
  25674. };
  25675. /** @hidden */
  25676. Scene.prototype._addPendingData = function (data) {
  25677. this._pendingData.push(data);
  25678. };
  25679. /** @hidden */
  25680. Scene.prototype._removePendingData = function (data) {
  25681. var wasLoading = this.isLoading;
  25682. var index = this._pendingData.indexOf(data);
  25683. if (index !== -1) {
  25684. this._pendingData.splice(index, 1);
  25685. }
  25686. if (wasLoading && !this.isLoading) {
  25687. this.onDataLoadedObservable.notifyObservers(this);
  25688. }
  25689. };
  25690. /**
  25691. * Returns the number of items waiting to be loaded
  25692. * @returns the number of items waiting to be loaded
  25693. */
  25694. Scene.prototype.getWaitingItemsCount = function () {
  25695. return this._pendingData.length;
  25696. };
  25697. Object.defineProperty(Scene.prototype, "isLoading", {
  25698. /**
  25699. * Returns a boolean indicating if the scene is still loading data
  25700. */
  25701. get: function () {
  25702. return this._pendingData.length > 0;
  25703. },
  25704. enumerable: true,
  25705. configurable: true
  25706. });
  25707. /**
  25708. * Registers a function to be executed when the scene is ready
  25709. * @param {Function} func - the function to be executed
  25710. */
  25711. Scene.prototype.executeWhenReady = function (func) {
  25712. var _this = this;
  25713. this.onReadyObservable.add(func);
  25714. if (this._executeWhenReadyTimeoutId !== -1) {
  25715. return;
  25716. }
  25717. this._executeWhenReadyTimeoutId = setTimeout(function () {
  25718. _this._checkIsReady();
  25719. }, 150);
  25720. };
  25721. /**
  25722. * Returns a promise that resolves when the scene is ready
  25723. * @returns A promise that resolves when the scene is ready
  25724. */
  25725. Scene.prototype.whenReadyAsync = function () {
  25726. var _this = this;
  25727. return new Promise(function (resolve) {
  25728. _this.executeWhenReady(function () {
  25729. resolve();
  25730. });
  25731. });
  25732. };
  25733. /** @hidden */
  25734. Scene.prototype._checkIsReady = function () {
  25735. var _this = this;
  25736. if (this.isReady()) {
  25737. this.onReadyObservable.notifyObservers(this);
  25738. this.onReadyObservable.clear();
  25739. this._executeWhenReadyTimeoutId = -1;
  25740. return;
  25741. }
  25742. this._executeWhenReadyTimeoutId = setTimeout(function () {
  25743. _this._checkIsReady();
  25744. }, 150);
  25745. };
  25746. // Animations
  25747. /**
  25748. * Will start the animation sequence of a given target
  25749. * @param target defines the target
  25750. * @param from defines from which frame should animation start
  25751. * @param to defines until which frame should animation run.
  25752. * @param weight defines the weight to apply to the animation (1.0 by default)
  25753. * @param loop defines if the animation loops
  25754. * @param speedRatio defines the speed in which to run the animation (1.0 by default)
  25755. * @param onAnimationEnd defines the function to be executed when the animation ends
  25756. * @param animatable defines an animatable object. If not provided a new one will be created from the given params
  25757. * @returns the animatable object created for this animation
  25758. */
  25759. Scene.prototype.beginWeightedAnimation = function (target, from, to, weight, loop, speedRatio, onAnimationEnd, animatable) {
  25760. if (weight === void 0) { weight = 1.0; }
  25761. if (speedRatio === void 0) { speedRatio = 1.0; }
  25762. var returnedAnimatable = this.beginAnimation(target, from, to, loop, speedRatio, onAnimationEnd, animatable, false);
  25763. returnedAnimatable.weight = weight;
  25764. return returnedAnimatable;
  25765. };
  25766. /**
  25767. * Will start the animation sequence of a given target
  25768. * @param target defines the target
  25769. * @param from defines from which frame should animation start
  25770. * @param to defines until which frame should animation run.
  25771. * @param loop defines if the animation loops
  25772. * @param speedRatio defines the speed in which to run the animation (1.0 by default)
  25773. * @param onAnimationEnd defines the function to be executed when the animation ends
  25774. * @param animatable defines an animatable object. If not provided a new one will be created from the given params
  25775. * @param stopCurrent defines if the current animations must be stopped first (true by default)
  25776. * @returns the animatable object created for this animation
  25777. */
  25778. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable, stopCurrent) {
  25779. if (speedRatio === void 0) { speedRatio = 1.0; }
  25780. if (stopCurrent === void 0) { stopCurrent = true; }
  25781. if (from > to && speedRatio > 0) {
  25782. speedRatio *= -1;
  25783. }
  25784. if (stopCurrent) {
  25785. this.stopAnimation(target);
  25786. }
  25787. if (!animatable) {
  25788. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  25789. }
  25790. // Local animations
  25791. if (target.animations) {
  25792. animatable.appendAnimations(target, target.animations);
  25793. }
  25794. // Children animations
  25795. if (target.getAnimatables) {
  25796. var animatables = target.getAnimatables();
  25797. for (var index = 0; index < animatables.length; index++) {
  25798. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable, stopCurrent);
  25799. }
  25800. }
  25801. animatable.reset();
  25802. return animatable;
  25803. };
  25804. /**
  25805. * Begin a new animation on a given node
  25806. * @param target defines the target where the animation will take place
  25807. * @param animations defines the list of animations to start
  25808. * @param from defines the initial value
  25809. * @param to defines the final value
  25810. * @param loop defines if you want animation to loop (off by default)
  25811. * @param speedRatio defines the speed ratio to apply to all animations
  25812. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  25813. * @returns the list of created animatables
  25814. */
  25815. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  25816. if (speedRatio === undefined) {
  25817. speedRatio = 1.0;
  25818. }
  25819. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  25820. return animatable;
  25821. };
  25822. /**
  25823. * Begin a new animation on a given node and its hierarchy
  25824. * @param target defines the root node where the animation will take place
  25825. * @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.
  25826. * @param animations defines the list of animations to start
  25827. * @param from defines the initial value
  25828. * @param to defines the final value
  25829. * @param loop defines if you want animation to loop (off by default)
  25830. * @param speedRatio defines the speed ratio to apply to all animations
  25831. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  25832. * @returns the list of animatables created for all nodes
  25833. */
  25834. Scene.prototype.beginDirectHierarchyAnimation = function (target, directDescendantsOnly, animations, from, to, loop, speedRatio, onAnimationEnd) {
  25835. var children = target.getDescendants(directDescendantsOnly);
  25836. var result = [];
  25837. result.push(this.beginDirectAnimation(target, animations, from, to, loop, speedRatio, onAnimationEnd));
  25838. for (var _i = 0, children_1 = children; _i < children_1.length; _i++) {
  25839. var child = children_1[_i];
  25840. result.push(this.beginDirectAnimation(child, animations, from, to, loop, speedRatio, onAnimationEnd));
  25841. }
  25842. return result;
  25843. };
  25844. /**
  25845. * Gets the animatable associated with a specific target
  25846. * @param target defines the target of the animatable
  25847. * @returns the required animatable if found
  25848. */
  25849. Scene.prototype.getAnimatableByTarget = function (target) {
  25850. for (var index = 0; index < this._activeAnimatables.length; index++) {
  25851. if (this._activeAnimatables[index].target === target) {
  25852. return this._activeAnimatables[index];
  25853. }
  25854. }
  25855. return null;
  25856. };
  25857. /**
  25858. * Gets all animatables associated with a given target
  25859. * @param target defines the target to look animatables for
  25860. * @returns an array of Animatables
  25861. */
  25862. Scene.prototype.getAllAnimatablesByTarget = function (target) {
  25863. var result = [];
  25864. for (var index = 0; index < this._activeAnimatables.length; index++) {
  25865. if (this._activeAnimatables[index].target === target) {
  25866. result.push(this._activeAnimatables[index]);
  25867. }
  25868. }
  25869. return result;
  25870. };
  25871. Object.defineProperty(Scene.prototype, "animatables", {
  25872. /**
  25873. * Gets all animatable attached to the scene
  25874. */
  25875. get: function () {
  25876. return this._activeAnimatables;
  25877. },
  25878. enumerable: true,
  25879. configurable: true
  25880. });
  25881. /**
  25882. * Will stop the animation of the given target
  25883. * @param target - the target
  25884. * @param animationName - the name of the animation to stop (all animations will be stopped if empty)
  25885. */
  25886. Scene.prototype.stopAnimation = function (target, animationName) {
  25887. var animatables = this.getAllAnimatablesByTarget(target);
  25888. for (var _i = 0, animatables_1 = animatables; _i < animatables_1.length; _i++) {
  25889. var animatable = animatables_1[_i];
  25890. animatable.stop(animationName);
  25891. }
  25892. };
  25893. /**
  25894. * Stops and removes all animations that have been applied to the scene
  25895. */
  25896. Scene.prototype.stopAllAnimations = function () {
  25897. if (this._activeAnimatables) {
  25898. for (var i = 0; i < this._activeAnimatables.length; i++) {
  25899. this._activeAnimatables[i].stop();
  25900. }
  25901. this._activeAnimatables = [];
  25902. }
  25903. for (var _i = 0, _a = this.animationGroups; _i < _a.length; _i++) {
  25904. var group = _a[_i];
  25905. group.stop();
  25906. }
  25907. };
  25908. Scene.prototype._animate = function () {
  25909. if (!this.animationsEnabled || this._activeAnimatables.length === 0) {
  25910. return;
  25911. }
  25912. // Getting time
  25913. var now = BABYLON.Tools.Now;
  25914. if (!this._animationTimeLast) {
  25915. if (this._pendingData.length > 0) {
  25916. return;
  25917. }
  25918. this._animationTimeLast = now;
  25919. }
  25920. var deltaTime = this.useConstantAnimationDeltaTime ? 16.0 : (now - this._animationTimeLast) * this.animationTimeScale;
  25921. this._animationTime += deltaTime;
  25922. this._animationTimeLast = now;
  25923. for (var index = 0; index < this._activeAnimatables.length; index++) {
  25924. this._activeAnimatables[index]._animate(this._animationTime);
  25925. }
  25926. // Late animation bindings
  25927. this._processLateAnimationBindings();
  25928. };
  25929. /** @hidden */
  25930. Scene.prototype._registerTargetForLateAnimationBinding = function (runtimeAnimation, originalValue) {
  25931. var target = runtimeAnimation.target;
  25932. this._registeredForLateAnimationBindings.pushNoDuplicate(target);
  25933. if (!target._lateAnimationHolders) {
  25934. target._lateAnimationHolders = {};
  25935. }
  25936. if (!target._lateAnimationHolders[runtimeAnimation.targetPath]) {
  25937. target._lateAnimationHolders[runtimeAnimation.targetPath] = {
  25938. totalWeight: 0,
  25939. animations: [],
  25940. originalValue: originalValue
  25941. };
  25942. }
  25943. target._lateAnimationHolders[runtimeAnimation.targetPath].animations.push(runtimeAnimation);
  25944. target._lateAnimationHolders[runtimeAnimation.targetPath].totalWeight += runtimeAnimation.weight;
  25945. };
  25946. Scene.prototype._processLateAnimationBindingsForMatrices = function (holder) {
  25947. var normalizer = 1.0;
  25948. var finalPosition = BABYLON.Tmp.Vector3[0];
  25949. var finalScaling = BABYLON.Tmp.Vector3[1];
  25950. var finalQuaternion = BABYLON.Tmp.Quaternion[0];
  25951. var startIndex = 0;
  25952. var originalAnimation = holder.animations[0];
  25953. var originalValue = holder.originalValue;
  25954. var scale = 1;
  25955. if (holder.totalWeight < 1.0) {
  25956. // We need to mix the original value in
  25957. originalValue.decompose(finalScaling, finalQuaternion, finalPosition);
  25958. scale = 1.0 - holder.totalWeight;
  25959. }
  25960. else {
  25961. startIndex = 1;
  25962. // We need to normalize the weights
  25963. normalizer = holder.totalWeight;
  25964. originalAnimation.currentValue.decompose(finalScaling, finalQuaternion, finalPosition);
  25965. scale = originalAnimation.weight / normalizer;
  25966. if (scale == 1) {
  25967. return originalAnimation.currentValue;
  25968. }
  25969. }
  25970. finalScaling.scaleInPlace(scale);
  25971. finalPosition.scaleInPlace(scale);
  25972. finalQuaternion.scaleInPlace(scale);
  25973. for (var animIndex = startIndex; animIndex < holder.animations.length; animIndex++) {
  25974. var runtimeAnimation = holder.animations[animIndex];
  25975. var scale = runtimeAnimation.weight / normalizer;
  25976. var currentPosition = BABYLON.Tmp.Vector3[2];
  25977. var currentScaling = BABYLON.Tmp.Vector3[3];
  25978. var currentQuaternion = BABYLON.Tmp.Quaternion[1];
  25979. runtimeAnimation.currentValue.decompose(currentScaling, currentQuaternion, currentPosition);
  25980. currentScaling.scaleAndAddToRef(scale, finalScaling);
  25981. currentQuaternion.scaleAndAddToRef(scale, finalQuaternion);
  25982. currentPosition.scaleAndAddToRef(scale, finalPosition);
  25983. }
  25984. BABYLON.Matrix.ComposeToRef(finalScaling, finalQuaternion, finalPosition, originalAnimation._workValue);
  25985. return originalAnimation._workValue;
  25986. };
  25987. Scene.prototype._processLateAnimationBindingsForQuaternions = function (holder) {
  25988. var originalAnimation = holder.animations[0];
  25989. var originalValue = holder.originalValue;
  25990. if (holder.animations.length === 1) {
  25991. return BABYLON.Quaternion.Slerp(originalValue, originalAnimation.currentValue, Math.min(1.0, holder.totalWeight));
  25992. }
  25993. var normalizer = 1.0;
  25994. var quaternions;
  25995. var weights;
  25996. if (holder.totalWeight < 1.0) {
  25997. var scale = 1.0 - holder.totalWeight;
  25998. quaternions = [];
  25999. weights = [];
  26000. quaternions.push(originalValue);
  26001. weights.push(scale);
  26002. }
  26003. else {
  26004. if (holder.animations.length === 2) { // Slerp as soon as we can
  26005. return BABYLON.Quaternion.Slerp(holder.animations[0].currentValue, holder.animations[1].currentValue, holder.animations[1].weight / holder.totalWeight);
  26006. }
  26007. quaternions = [];
  26008. weights = [];
  26009. normalizer = holder.totalWeight;
  26010. }
  26011. for (var animIndex = 0; animIndex < holder.animations.length; animIndex++) {
  26012. var runtimeAnimation = holder.animations[animIndex];
  26013. quaternions.push(runtimeAnimation.currentValue);
  26014. weights.push(runtimeAnimation.weight / normalizer);
  26015. }
  26016. // https://gamedev.stackexchange.com/questions/62354/method-for-interpolation-between-3-quaternions
  26017. var cumulativeAmount = 0;
  26018. var cumulativeQuaternion = null;
  26019. for (var index = 0; index < quaternions.length;) {
  26020. if (!cumulativeQuaternion) {
  26021. cumulativeQuaternion = BABYLON.Quaternion.Slerp(quaternions[index], quaternions[index + 1], weights[index + 1] / (weights[index] + weights[index + 1]));
  26022. cumulativeAmount = weights[index] + weights[index + 1];
  26023. index += 2;
  26024. continue;
  26025. }
  26026. cumulativeAmount += weights[index];
  26027. BABYLON.Quaternion.SlerpToRef(cumulativeQuaternion, quaternions[index], weights[index] / cumulativeAmount, cumulativeQuaternion);
  26028. index++;
  26029. }
  26030. return cumulativeQuaternion;
  26031. };
  26032. Scene.prototype._processLateAnimationBindings = function () {
  26033. if (!this._registeredForLateAnimationBindings.length) {
  26034. return;
  26035. }
  26036. for (var index = 0; index < this._registeredForLateAnimationBindings.length; index++) {
  26037. var target = this._registeredForLateAnimationBindings.data[index];
  26038. for (var path in target._lateAnimationHolders) {
  26039. var holder = target._lateAnimationHolders[path];
  26040. var originalAnimation = holder.animations[0];
  26041. var originalValue = holder.originalValue;
  26042. var matrixDecomposeMode = BABYLON.Animation.AllowMatrixDecomposeForInterpolation && originalValue.m; // ie. data is matrix
  26043. var finalValue = void 0;
  26044. if (matrixDecomposeMode) {
  26045. finalValue = this._processLateAnimationBindingsForMatrices(holder);
  26046. }
  26047. else {
  26048. var quaternionMode = originalValue.w !== undefined;
  26049. if (quaternionMode) {
  26050. finalValue = this._processLateAnimationBindingsForQuaternions(holder);
  26051. }
  26052. else {
  26053. var startIndex = 0;
  26054. var normalizer = 1.0;
  26055. if (holder.totalWeight < 1.0) {
  26056. // We need to mix the original value in
  26057. if (originalValue.scale) {
  26058. finalValue = originalValue.scale(1.0 - holder.totalWeight);
  26059. }
  26060. else {
  26061. finalValue = originalValue * (1.0 - holder.totalWeight);
  26062. }
  26063. }
  26064. else {
  26065. // We need to normalize the weights
  26066. normalizer = holder.totalWeight;
  26067. var scale_1 = originalAnimation.weight / normalizer;
  26068. if (scale_1 !== 1) {
  26069. if (originalAnimation.currentValue.scale) {
  26070. finalValue = originalAnimation.currentValue.scale(scale_1);
  26071. }
  26072. else {
  26073. finalValue = originalAnimation.currentValue * scale_1;
  26074. }
  26075. }
  26076. else {
  26077. finalValue = originalAnimation.currentValue;
  26078. }
  26079. startIndex = 1;
  26080. }
  26081. for (var animIndex = startIndex; animIndex < holder.animations.length; animIndex++) {
  26082. var runtimeAnimation = holder.animations[animIndex];
  26083. var scale = runtimeAnimation.weight / normalizer;
  26084. if (runtimeAnimation.currentValue.scaleAndAddToRef) {
  26085. runtimeAnimation.currentValue.scaleAndAddToRef(scale, finalValue);
  26086. }
  26087. else {
  26088. finalValue += runtimeAnimation.currentValue * scale;
  26089. }
  26090. }
  26091. }
  26092. }
  26093. target[path] = finalValue;
  26094. }
  26095. target._lateAnimationHolders = {};
  26096. }
  26097. this._registeredForLateAnimationBindings.reset();
  26098. };
  26099. // Matrix
  26100. /** @hidden */
  26101. Scene.prototype._switchToAlternateCameraConfiguration = function (active) {
  26102. this._useAlternateCameraConfiguration = active;
  26103. };
  26104. /**
  26105. * Gets the current view matrix
  26106. * @returns a Matrix
  26107. */
  26108. Scene.prototype.getViewMatrix = function () {
  26109. return this._useAlternateCameraConfiguration ? this._alternateViewMatrix : this._viewMatrix;
  26110. };
  26111. /**
  26112. * Gets the current projection matrix
  26113. * @returns a Matrix
  26114. */
  26115. Scene.prototype.getProjectionMatrix = function () {
  26116. return this._useAlternateCameraConfiguration ? this._alternateProjectionMatrix : this._projectionMatrix;
  26117. };
  26118. /**
  26119. * Gets the current transform matrix
  26120. * @returns a Matrix made of View * Projection
  26121. */
  26122. Scene.prototype.getTransformMatrix = function () {
  26123. return this._useAlternateCameraConfiguration ? this._alternateTransformMatrix : this._transformMatrix;
  26124. };
  26125. /**
  26126. * Sets the current transform matrix
  26127. * @param view defines the View matrix to use
  26128. * @param projection defines the Projection matrix to use
  26129. */
  26130. Scene.prototype.setTransformMatrix = function (view, projection) {
  26131. if (this._viewUpdateFlag === view.updateFlag && this._projectionUpdateFlag === projection.updateFlag) {
  26132. return;
  26133. }
  26134. this._viewUpdateFlag = view.updateFlag;
  26135. this._projectionUpdateFlag = projection.updateFlag;
  26136. this._viewMatrix = view;
  26137. this._projectionMatrix = projection;
  26138. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  26139. // Update frustum
  26140. if (!this._frustumPlanes) {
  26141. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  26142. }
  26143. else {
  26144. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  26145. }
  26146. if (this.activeCamera && this.activeCamera._alternateCamera) {
  26147. var otherCamera = this.activeCamera._alternateCamera;
  26148. otherCamera.getViewMatrix().multiplyToRef(otherCamera.getProjectionMatrix(), BABYLON.Tmp.Matrix[0]);
  26149. BABYLON.Frustum.GetRightPlaneToRef(BABYLON.Tmp.Matrix[0], this._frustumPlanes[3]); // Replace right plane by second camera right plane
  26150. }
  26151. if (this._sceneUbo.useUbo) {
  26152. this._sceneUbo.updateMatrix("viewProjection", this._transformMatrix);
  26153. this._sceneUbo.updateMatrix("view", this._viewMatrix);
  26154. this._sceneUbo.update();
  26155. }
  26156. };
  26157. /** @hidden */
  26158. Scene.prototype._setAlternateTransformMatrix = function (view, projection) {
  26159. if (this._alternateViewUpdateFlag === view.updateFlag && this._alternateProjectionUpdateFlag === projection.updateFlag) {
  26160. return;
  26161. }
  26162. this._alternateViewUpdateFlag = view.updateFlag;
  26163. this._alternateProjectionUpdateFlag = projection.updateFlag;
  26164. this._alternateViewMatrix = view;
  26165. this._alternateProjectionMatrix = projection;
  26166. if (!this._alternateTransformMatrix) {
  26167. this._alternateTransformMatrix = BABYLON.Matrix.Zero();
  26168. }
  26169. this._alternateViewMatrix.multiplyToRef(this._alternateProjectionMatrix, this._alternateTransformMatrix);
  26170. if (!this._alternateSceneUbo) {
  26171. this._createAlternateUbo();
  26172. }
  26173. if (this._alternateSceneUbo.useUbo) {
  26174. this._alternateSceneUbo.updateMatrix("viewProjection", this._alternateTransformMatrix);
  26175. this._alternateSceneUbo.updateMatrix("view", this._alternateViewMatrix);
  26176. this._alternateSceneUbo.update();
  26177. }
  26178. };
  26179. /**
  26180. * Gets the uniform buffer used to store scene data
  26181. * @returns a UniformBuffer
  26182. */
  26183. Scene.prototype.getSceneUniformBuffer = function () {
  26184. return this._useAlternateCameraConfiguration ? this._alternateSceneUbo : this._sceneUbo;
  26185. };
  26186. /**
  26187. * Gets an unique (relatively to the current scene) Id
  26188. * @returns an unique number for the scene
  26189. */
  26190. Scene.prototype.getUniqueId = function () {
  26191. var result = Scene._uniqueIdCounter;
  26192. Scene._uniqueIdCounter++;
  26193. return result;
  26194. };
  26195. /**
  26196. * Add a mesh to the list of scene's meshes
  26197. * @param newMesh defines the mesh to add
  26198. * @param recursive if all child meshes should also be added to the scene
  26199. */
  26200. Scene.prototype.addMesh = function (newMesh, recursive) {
  26201. var _this = this;
  26202. if (recursive === void 0) { recursive = false; }
  26203. this.meshes.push(newMesh);
  26204. //notify the collision coordinator
  26205. if (this.collisionCoordinator) {
  26206. this.collisionCoordinator.onMeshAdded(newMesh);
  26207. }
  26208. newMesh._resyncLightSources();
  26209. this.onNewMeshAddedObservable.notifyObservers(newMesh);
  26210. if (recursive) {
  26211. newMesh.getChildMeshes().forEach(function (m) {
  26212. _this.addMesh(m);
  26213. });
  26214. }
  26215. };
  26216. /**
  26217. * Remove a mesh for the list of scene's meshes
  26218. * @param toRemove defines the mesh to remove
  26219. * @param recursive if all child meshes should also be removed from the scene
  26220. * @returns the index where the mesh was in the mesh list
  26221. */
  26222. Scene.prototype.removeMesh = function (toRemove, recursive) {
  26223. var _this = this;
  26224. if (recursive === void 0) { recursive = false; }
  26225. var index = this.meshes.indexOf(toRemove);
  26226. if (index !== -1) {
  26227. // Remove from the scene if mesh found
  26228. this.meshes.splice(index, 1);
  26229. }
  26230. this.onMeshRemovedObservable.notifyObservers(toRemove);
  26231. if (recursive) {
  26232. toRemove.getChildMeshes().forEach(function (m) {
  26233. _this.removeMesh(m);
  26234. });
  26235. }
  26236. return index;
  26237. };
  26238. /**
  26239. * Add a transform node to the list of scene's transform nodes
  26240. * @param newTransformNode defines the transform node to add
  26241. */
  26242. Scene.prototype.addTransformNode = function (newTransformNode) {
  26243. this.transformNodes.push(newTransformNode);
  26244. this.onNewTransformNodeAddedObservable.notifyObservers(newTransformNode);
  26245. };
  26246. /**
  26247. * Remove a transform node for the list of scene's transform nodes
  26248. * @param toRemove defines the transform node to remove
  26249. * @returns the index where the transform node was in the transform node list
  26250. */
  26251. Scene.prototype.removeTransformNode = function (toRemove) {
  26252. var index = this.transformNodes.indexOf(toRemove);
  26253. if (index !== -1) {
  26254. // Remove from the scene if found
  26255. this.transformNodes.splice(index, 1);
  26256. }
  26257. this.onTransformNodeRemovedObservable.notifyObservers(toRemove);
  26258. return index;
  26259. };
  26260. /**
  26261. * Remove a skeleton for the list of scene's skeletons
  26262. * @param toRemove defines the skeleton to remove
  26263. * @returns the index where the skeleton was in the skeleton list
  26264. */
  26265. Scene.prototype.removeSkeleton = function (toRemove) {
  26266. var index = this.skeletons.indexOf(toRemove);
  26267. if (index !== -1) {
  26268. // Remove from the scene if found
  26269. this.skeletons.splice(index, 1);
  26270. }
  26271. return index;
  26272. };
  26273. /**
  26274. * Remove a morph target for the list of scene's morph targets
  26275. * @param toRemove defines the morph target to remove
  26276. * @returns the index where the morph target was in the morph target list
  26277. */
  26278. Scene.prototype.removeMorphTargetManager = function (toRemove) {
  26279. var index = this.morphTargetManagers.indexOf(toRemove);
  26280. if (index !== -1) {
  26281. // Remove from the scene if found
  26282. this.morphTargetManagers.splice(index, 1);
  26283. }
  26284. return index;
  26285. };
  26286. /**
  26287. * Remove a light for the list of scene's lights
  26288. * @param toRemove defines the light to remove
  26289. * @returns the index where the light was in the light list
  26290. */
  26291. Scene.prototype.removeLight = function (toRemove) {
  26292. var index = this.lights.indexOf(toRemove);
  26293. if (index !== -1) {
  26294. // Remove from meshes
  26295. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  26296. var mesh = _a[_i];
  26297. mesh._removeLightSource(toRemove);
  26298. }
  26299. // Remove from the scene if mesh found
  26300. this.lights.splice(index, 1);
  26301. this.sortLightsByPriority();
  26302. }
  26303. this.onLightRemovedObservable.notifyObservers(toRemove);
  26304. return index;
  26305. };
  26306. /**
  26307. * Remove a camera for the list of scene's cameras
  26308. * @param toRemove defines the camera to remove
  26309. * @returns the index where the camera was in the camera list
  26310. */
  26311. Scene.prototype.removeCamera = function (toRemove) {
  26312. var index = this.cameras.indexOf(toRemove);
  26313. if (index !== -1) {
  26314. // Remove from the scene if mesh found
  26315. this.cameras.splice(index, 1);
  26316. }
  26317. // Remove from activeCameras
  26318. var index2 = this.activeCameras.indexOf(toRemove);
  26319. if (index2 !== -1) {
  26320. // Remove from the scene if mesh found
  26321. this.activeCameras.splice(index2, 1);
  26322. }
  26323. // Reset the activeCamera
  26324. if (this.activeCamera === toRemove) {
  26325. if (this.cameras.length > 0) {
  26326. this.activeCamera = this.cameras[0];
  26327. }
  26328. else {
  26329. this.activeCamera = null;
  26330. }
  26331. }
  26332. this.onCameraRemovedObservable.notifyObservers(toRemove);
  26333. return index;
  26334. };
  26335. /**
  26336. * Remove a particle system for the list of scene's particle systems
  26337. * @param toRemove defines the particle system to remove
  26338. * @returns the index where the particle system was in the particle system list
  26339. */
  26340. Scene.prototype.removeParticleSystem = function (toRemove) {
  26341. var index = this.particleSystems.indexOf(toRemove);
  26342. if (index !== -1) {
  26343. this.particleSystems.splice(index, 1);
  26344. }
  26345. return index;
  26346. };
  26347. /**
  26348. * Remove a animation for the list of scene's animations
  26349. * @param toRemove defines the animation to remove
  26350. * @returns the index where the animation was in the animation list
  26351. */
  26352. Scene.prototype.removeAnimation = function (toRemove) {
  26353. var index = this.animations.indexOf(toRemove);
  26354. if (index !== -1) {
  26355. this.animations.splice(index, 1);
  26356. }
  26357. return index;
  26358. };
  26359. /**
  26360. * Removes the given animation group from this scene.
  26361. * @param toRemove The animation group to remove
  26362. * @returns The index of the removed animation group
  26363. */
  26364. Scene.prototype.removeAnimationGroup = function (toRemove) {
  26365. var index = this.animationGroups.indexOf(toRemove);
  26366. if (index !== -1) {
  26367. this.animationGroups.splice(index, 1);
  26368. }
  26369. return index;
  26370. };
  26371. /**
  26372. * Removes the given multi-material from this scene.
  26373. * @param toRemove The multi-material to remove
  26374. * @returns The index of the removed multi-material
  26375. */
  26376. Scene.prototype.removeMultiMaterial = function (toRemove) {
  26377. var index = this.multiMaterials.indexOf(toRemove);
  26378. if (index !== -1) {
  26379. this.multiMaterials.splice(index, 1);
  26380. }
  26381. return index;
  26382. };
  26383. /**
  26384. * Removes the given material from this scene.
  26385. * @param toRemove The material to remove
  26386. * @returns The index of the removed material
  26387. */
  26388. Scene.prototype.removeMaterial = function (toRemove) {
  26389. var index = this.materials.indexOf(toRemove);
  26390. if (index !== -1) {
  26391. this.materials.splice(index, 1);
  26392. }
  26393. return index;
  26394. };
  26395. /**
  26396. * Removes the given lens flare system from this scene.
  26397. * @param toRemove The lens flare system to remove
  26398. * @returns The index of the removed lens flare system
  26399. */
  26400. Scene.prototype.removeLensFlareSystem = function (toRemove) {
  26401. var index = this.lensFlareSystems.indexOf(toRemove);
  26402. if (index !== -1) {
  26403. this.lensFlareSystems.splice(index, 1);
  26404. }
  26405. return index;
  26406. };
  26407. /**
  26408. * Removes the given action manager from this scene.
  26409. * @param toRemove The action manager to remove
  26410. * @returns The index of the removed action manager
  26411. */
  26412. Scene.prototype.removeActionManager = function (toRemove) {
  26413. var index = this._actionManagers.indexOf(toRemove);
  26414. if (index !== -1) {
  26415. this._actionManagers.splice(index, 1);
  26416. }
  26417. return index;
  26418. };
  26419. /**
  26420. * Removes the given effect layer from this scene.
  26421. * @param toRemove defines the effect layer to remove
  26422. * @returns the index of the removed effect layer
  26423. */
  26424. Scene.prototype.removeEffectLayer = function (toRemove) {
  26425. var index = this.effectLayers.indexOf(toRemove);
  26426. if (index !== -1) {
  26427. this.effectLayers.splice(index, 1);
  26428. }
  26429. return index;
  26430. };
  26431. /**
  26432. * Removes the given texture from this scene.
  26433. * @param toRemove The texture to remove
  26434. * @returns The index of the removed texture
  26435. */
  26436. Scene.prototype.removeTexture = function (toRemove) {
  26437. var index = this.textures.indexOf(toRemove);
  26438. if (index !== -1) {
  26439. this.textures.splice(index, 1);
  26440. }
  26441. return index;
  26442. };
  26443. /**
  26444. * Adds the given light to this scene
  26445. * @param newLight The light to add
  26446. */
  26447. Scene.prototype.addLight = function (newLight) {
  26448. this.lights.push(newLight);
  26449. this.sortLightsByPriority();
  26450. // Add light to all meshes (To support if the light is removed and then readded)
  26451. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  26452. var mesh = _a[_i];
  26453. if (mesh._lightSources.indexOf(newLight) === -1) {
  26454. mesh._lightSources.push(newLight);
  26455. mesh._resyncLightSources();
  26456. }
  26457. }
  26458. this.onNewLightAddedObservable.notifyObservers(newLight);
  26459. };
  26460. /**
  26461. * Sorts the list list based on light priorities
  26462. */
  26463. Scene.prototype.sortLightsByPriority = function () {
  26464. if (this.requireLightSorting) {
  26465. this.lights.sort(BABYLON.Light.CompareLightsPriority);
  26466. }
  26467. };
  26468. /**
  26469. * Adds the given camera to this scene
  26470. * @param newCamera The camera to add
  26471. */
  26472. Scene.prototype.addCamera = function (newCamera) {
  26473. this.cameras.push(newCamera);
  26474. this.onNewCameraAddedObservable.notifyObservers(newCamera);
  26475. };
  26476. /**
  26477. * Adds the given skeleton to this scene
  26478. * @param newSkeleton The skeleton to add
  26479. */
  26480. Scene.prototype.addSkeleton = function (newSkeleton) {
  26481. this.skeletons.push(newSkeleton);
  26482. };
  26483. /**
  26484. * Adds the given particle system to this scene
  26485. * @param newParticleSystem The particle system to add
  26486. */
  26487. Scene.prototype.addParticleSystem = function (newParticleSystem) {
  26488. this.particleSystems.push(newParticleSystem);
  26489. };
  26490. /**
  26491. * Adds the given animation to this scene
  26492. * @param newAnimation The animation to add
  26493. */
  26494. Scene.prototype.addAnimation = function (newAnimation) {
  26495. this.animations.push(newAnimation);
  26496. };
  26497. /**
  26498. * Adds the given animation group to this scene.
  26499. * @param newAnimationGroup The animation group to add
  26500. */
  26501. Scene.prototype.addAnimationGroup = function (newAnimationGroup) {
  26502. this.animationGroups.push(newAnimationGroup);
  26503. };
  26504. /**
  26505. * Adds the given multi-material to this scene
  26506. * @param newMultiMaterial The multi-material to add
  26507. */
  26508. Scene.prototype.addMultiMaterial = function (newMultiMaterial) {
  26509. this.multiMaterials.push(newMultiMaterial);
  26510. };
  26511. /**
  26512. * Adds the given material to this scene
  26513. * @param newMaterial The material to add
  26514. */
  26515. Scene.prototype.addMaterial = function (newMaterial) {
  26516. this.materials.push(newMaterial);
  26517. };
  26518. /**
  26519. * Adds the given morph target to this scene
  26520. * @param newMorphTargetManager The morph target to add
  26521. */
  26522. Scene.prototype.addMorphTargetManager = function (newMorphTargetManager) {
  26523. this.morphTargetManagers.push(newMorphTargetManager);
  26524. };
  26525. /**
  26526. * Adds the given geometry to this scene
  26527. * @param newGeometry The geometry to add
  26528. */
  26529. Scene.prototype.addGeometry = function (newGeometry) {
  26530. this._geometries.push(newGeometry);
  26531. };
  26532. /**
  26533. * Adds the given lens flare system to this scene
  26534. * @param newLensFlareSystem The lens flare system to add
  26535. */
  26536. Scene.prototype.addLensFlareSystem = function (newLensFlareSystem) {
  26537. this.lensFlareSystems.push(newLensFlareSystem);
  26538. };
  26539. /**
  26540. * Adds the given effect layer to this scene
  26541. * @param newEffectLayer defines the effect layer to add
  26542. */
  26543. Scene.prototype.addEffectLayer = function (newEffectLayer) {
  26544. this.effectLayers.push(newEffectLayer);
  26545. };
  26546. /**
  26547. * Adds the given action manager to this scene
  26548. * @param newActionManager The action manager to add
  26549. */
  26550. Scene.prototype.addActionManager = function (newActionManager) {
  26551. this._actionManagers.push(newActionManager);
  26552. };
  26553. /**
  26554. * Adds the given texture to this scene.
  26555. * @param newTexture The texture to add
  26556. */
  26557. Scene.prototype.addTexture = function (newTexture) {
  26558. this.textures.push(newTexture);
  26559. };
  26560. /**
  26561. * Switch active camera
  26562. * @param newCamera defines the new active camera
  26563. * @param attachControl defines if attachControl must be called for the new active camera (default: true)
  26564. */
  26565. Scene.prototype.switchActiveCamera = function (newCamera, attachControl) {
  26566. if (attachControl === void 0) { attachControl = true; }
  26567. var canvas = this._engine.getRenderingCanvas();
  26568. if (!canvas) {
  26569. return;
  26570. }
  26571. if (this.activeCamera) {
  26572. this.activeCamera.detachControl(canvas);
  26573. }
  26574. this.activeCamera = newCamera;
  26575. if (attachControl) {
  26576. newCamera.attachControl(canvas);
  26577. }
  26578. };
  26579. /**
  26580. * sets the active camera of the scene using its ID
  26581. * @param id defines the camera's ID
  26582. * @return the new active camera or null if none found.
  26583. */
  26584. Scene.prototype.setActiveCameraByID = function (id) {
  26585. var camera = this.getCameraByID(id);
  26586. if (camera) {
  26587. this.activeCamera = camera;
  26588. return camera;
  26589. }
  26590. return null;
  26591. };
  26592. /**
  26593. * sets the active camera of the scene using its name
  26594. * @param name defines the camera's name
  26595. * @returns the new active camera or null if none found.
  26596. */
  26597. Scene.prototype.setActiveCameraByName = function (name) {
  26598. var camera = this.getCameraByName(name);
  26599. if (camera) {
  26600. this.activeCamera = camera;
  26601. return camera;
  26602. }
  26603. return null;
  26604. };
  26605. /**
  26606. * get an animation group using its name
  26607. * @param name defines the material's name
  26608. * @return the animation group or null if none found.
  26609. */
  26610. Scene.prototype.getAnimationGroupByName = function (name) {
  26611. for (var index = 0; index < this.animationGroups.length; index++) {
  26612. if (this.animationGroups[index].name === name) {
  26613. return this.animationGroups[index];
  26614. }
  26615. }
  26616. return null;
  26617. };
  26618. /**
  26619. * get a material using its id
  26620. * @param id defines the material's ID
  26621. * @return the material or null if none found.
  26622. */
  26623. Scene.prototype.getMaterialByID = function (id) {
  26624. for (var index = 0; index < this.materials.length; index++) {
  26625. if (this.materials[index].id === id) {
  26626. return this.materials[index];
  26627. }
  26628. }
  26629. return null;
  26630. };
  26631. /**
  26632. * Gets a material using its name
  26633. * @param name defines the material's name
  26634. * @return the material or null if none found.
  26635. */
  26636. Scene.prototype.getMaterialByName = function (name) {
  26637. for (var index = 0; index < this.materials.length; index++) {
  26638. if (this.materials[index].name === name) {
  26639. return this.materials[index];
  26640. }
  26641. }
  26642. return null;
  26643. };
  26644. /**
  26645. * Gets a lens flare system using its name
  26646. * @param name defines the name to look for
  26647. * @returns the lens flare system or null if not found
  26648. */
  26649. Scene.prototype.getLensFlareSystemByName = function (name) {
  26650. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  26651. if (this.lensFlareSystems[index].name === name) {
  26652. return this.lensFlareSystems[index];
  26653. }
  26654. }
  26655. return null;
  26656. };
  26657. /**
  26658. * Gets a lens flare system using its id
  26659. * @param id defines the id to look for
  26660. * @returns the lens flare system or null if not found
  26661. */
  26662. Scene.prototype.getLensFlareSystemByID = function (id) {
  26663. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  26664. if (this.lensFlareSystems[index].id === id) {
  26665. return this.lensFlareSystems[index];
  26666. }
  26667. }
  26668. return null;
  26669. };
  26670. /**
  26671. * Gets a camera using its id
  26672. * @param id defines the id to look for
  26673. * @returns the camera or null if not found
  26674. */
  26675. Scene.prototype.getCameraByID = function (id) {
  26676. for (var index = 0; index < this.cameras.length; index++) {
  26677. if (this.cameras[index].id === id) {
  26678. return this.cameras[index];
  26679. }
  26680. }
  26681. return null;
  26682. };
  26683. /**
  26684. * Gets a camera using its unique id
  26685. * @param uniqueId defines the unique id to look for
  26686. * @returns the camera or null if not found
  26687. */
  26688. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  26689. for (var index = 0; index < this.cameras.length; index++) {
  26690. if (this.cameras[index].uniqueId === uniqueId) {
  26691. return this.cameras[index];
  26692. }
  26693. }
  26694. return null;
  26695. };
  26696. /**
  26697. * Gets a camera using its name
  26698. * @param name defines the camera's name
  26699. * @return the camera or null if none found.
  26700. */
  26701. Scene.prototype.getCameraByName = function (name) {
  26702. for (var index = 0; index < this.cameras.length; index++) {
  26703. if (this.cameras[index].name === name) {
  26704. return this.cameras[index];
  26705. }
  26706. }
  26707. return null;
  26708. };
  26709. /**
  26710. * Gets a bone using its id
  26711. * @param id defines the bone's id
  26712. * @return the bone or null if not found
  26713. */
  26714. Scene.prototype.getBoneByID = function (id) {
  26715. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  26716. var skeleton = this.skeletons[skeletonIndex];
  26717. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  26718. if (skeleton.bones[boneIndex].id === id) {
  26719. return skeleton.bones[boneIndex];
  26720. }
  26721. }
  26722. }
  26723. return null;
  26724. };
  26725. /**
  26726. * Gets a bone using its id
  26727. * @param name defines the bone's name
  26728. * @return the bone or null if not found
  26729. */
  26730. Scene.prototype.getBoneByName = function (name) {
  26731. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  26732. var skeleton = this.skeletons[skeletonIndex];
  26733. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  26734. if (skeleton.bones[boneIndex].name === name) {
  26735. return skeleton.bones[boneIndex];
  26736. }
  26737. }
  26738. }
  26739. return null;
  26740. };
  26741. /**
  26742. * Gets a light node using its name
  26743. * @param name defines the the light's name
  26744. * @return the light or null if none found.
  26745. */
  26746. Scene.prototype.getLightByName = function (name) {
  26747. for (var index = 0; index < this.lights.length; index++) {
  26748. if (this.lights[index].name === name) {
  26749. return this.lights[index];
  26750. }
  26751. }
  26752. return null;
  26753. };
  26754. /**
  26755. * Gets a light node using its id
  26756. * @param id defines the light's id
  26757. * @return the light or null if none found.
  26758. */
  26759. Scene.prototype.getLightByID = function (id) {
  26760. for (var index = 0; index < this.lights.length; index++) {
  26761. if (this.lights[index].id === id) {
  26762. return this.lights[index];
  26763. }
  26764. }
  26765. return null;
  26766. };
  26767. /**
  26768. * Gets a light node using its scene-generated unique ID
  26769. * @param uniqueId defines the light's unique id
  26770. * @return the light or null if none found.
  26771. */
  26772. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  26773. for (var index = 0; index < this.lights.length; index++) {
  26774. if (this.lights[index].uniqueId === uniqueId) {
  26775. return this.lights[index];
  26776. }
  26777. }
  26778. return null;
  26779. };
  26780. /**
  26781. * Gets a particle system by id
  26782. * @param id defines the particle system id
  26783. * @return the corresponding system or null if none found
  26784. */
  26785. Scene.prototype.getParticleSystemByID = function (id) {
  26786. for (var index = 0; index < this.particleSystems.length; index++) {
  26787. if (this.particleSystems[index].id === id) {
  26788. return this.particleSystems[index];
  26789. }
  26790. }
  26791. return null;
  26792. };
  26793. /**
  26794. * Gets a geometry using its ID
  26795. * @param id defines the geometry's id
  26796. * @return the geometry or null if none found.
  26797. */
  26798. Scene.prototype.getGeometryByID = function (id) {
  26799. for (var index = 0; index < this._geometries.length; index++) {
  26800. if (this._geometries[index].id === id) {
  26801. return this._geometries[index];
  26802. }
  26803. }
  26804. return null;
  26805. };
  26806. /**
  26807. * Add a new geometry to this scene
  26808. * @param geometry defines the geometry to be added to the scene.
  26809. * @param force defines if the geometry must be pushed even if a geometry with this id already exists
  26810. * @return a boolean defining if the geometry was added or not
  26811. */
  26812. Scene.prototype.pushGeometry = function (geometry, force) {
  26813. if (!force && this.getGeometryByID(geometry.id)) {
  26814. return false;
  26815. }
  26816. this._geometries.push(geometry);
  26817. //notify the collision coordinator
  26818. if (this.collisionCoordinator) {
  26819. this.collisionCoordinator.onGeometryAdded(geometry);
  26820. }
  26821. this.onNewGeometryAddedObservable.notifyObservers(geometry);
  26822. return true;
  26823. };
  26824. /**
  26825. * Removes an existing geometry
  26826. * @param geometry defines the geometry to be removed from the scene
  26827. * @return a boolean defining if the geometry was removed or not
  26828. */
  26829. Scene.prototype.removeGeometry = function (geometry) {
  26830. var index = this._geometries.indexOf(geometry);
  26831. if (index > -1) {
  26832. this._geometries.splice(index, 1);
  26833. //notify the collision coordinator
  26834. if (this.collisionCoordinator) {
  26835. this.collisionCoordinator.onGeometryDeleted(geometry);
  26836. }
  26837. this.onGeometryRemovedObservable.notifyObservers(geometry);
  26838. return true;
  26839. }
  26840. return false;
  26841. };
  26842. /**
  26843. * Gets the list of geometries attached to the scene
  26844. * @returns an array of Geometry
  26845. */
  26846. Scene.prototype.getGeometries = function () {
  26847. return this._geometries;
  26848. };
  26849. /**
  26850. * Gets the first added mesh found of a given ID
  26851. * @param id defines the id to search for
  26852. * @return the mesh found or null if not found at all
  26853. */
  26854. Scene.prototype.getMeshByID = function (id) {
  26855. for (var index = 0; index < this.meshes.length; index++) {
  26856. if (this.meshes[index].id === id) {
  26857. return this.meshes[index];
  26858. }
  26859. }
  26860. return null;
  26861. };
  26862. /**
  26863. * Gets a list of meshes using their id
  26864. * @param id defines the id to search for
  26865. * @returns a list of meshes
  26866. */
  26867. Scene.prototype.getMeshesByID = function (id) {
  26868. return this.meshes.filter(function (m) {
  26869. return m.id === id;
  26870. });
  26871. };
  26872. /**
  26873. * Gets the first added transform node found of a given ID
  26874. * @param id defines the id to search for
  26875. * @return the found transform node or null if not found at all.
  26876. */
  26877. Scene.prototype.getTransformNodeByID = function (id) {
  26878. for (var index = 0; index < this.transformNodes.length; index++) {
  26879. if (this.transformNodes[index].id === id) {
  26880. return this.transformNodes[index];
  26881. }
  26882. }
  26883. return null;
  26884. };
  26885. /**
  26886. * Gets a list of transform nodes using their id
  26887. * @param id defines the id to search for
  26888. * @returns a list of transform nodes
  26889. */
  26890. Scene.prototype.getTransformNodesByID = function (id) {
  26891. return this.transformNodes.filter(function (m) {
  26892. return m.id === id;
  26893. });
  26894. };
  26895. /**
  26896. * Gets a mesh with its auto-generated unique id
  26897. * @param uniqueId defines the unique id to search for
  26898. * @return the found mesh or null if not found at all.
  26899. */
  26900. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  26901. for (var index = 0; index < this.meshes.length; index++) {
  26902. if (this.meshes[index].uniqueId === uniqueId) {
  26903. return this.meshes[index];
  26904. }
  26905. }
  26906. return null;
  26907. };
  26908. /**
  26909. * Gets a the last added mesh using a given id
  26910. * @param id defines the id to search for
  26911. * @return the found mesh or null if not found at all.
  26912. */
  26913. Scene.prototype.getLastMeshByID = function (id) {
  26914. for (var index = this.meshes.length - 1; index >= 0; index--) {
  26915. if (this.meshes[index].id === id) {
  26916. return this.meshes[index];
  26917. }
  26918. }
  26919. return null;
  26920. };
  26921. /**
  26922. * Gets a the last added node (Mesh, Camera, Light) using a given id
  26923. * @param id defines the id to search for
  26924. * @return the found node or null if not found at all
  26925. */
  26926. Scene.prototype.getLastEntryByID = function (id) {
  26927. var index;
  26928. for (index = this.meshes.length - 1; index >= 0; index--) {
  26929. if (this.meshes[index].id === id) {
  26930. return this.meshes[index];
  26931. }
  26932. }
  26933. for (index = this.transformNodes.length - 1; index >= 0; index--) {
  26934. if (this.transformNodes[index].id === id) {
  26935. return this.transformNodes[index];
  26936. }
  26937. }
  26938. for (index = this.cameras.length - 1; index >= 0; index--) {
  26939. if (this.cameras[index].id === id) {
  26940. return this.cameras[index];
  26941. }
  26942. }
  26943. for (index = this.lights.length - 1; index >= 0; index--) {
  26944. if (this.lights[index].id === id) {
  26945. return this.lights[index];
  26946. }
  26947. }
  26948. return null;
  26949. };
  26950. /**
  26951. * Gets a node (Mesh, Camera, Light) using a given id
  26952. * @param id defines the id to search for
  26953. * @return the found node or null if not found at all
  26954. */
  26955. Scene.prototype.getNodeByID = function (id) {
  26956. var mesh = this.getMeshByID(id);
  26957. if (mesh) {
  26958. return mesh;
  26959. }
  26960. var light = this.getLightByID(id);
  26961. if (light) {
  26962. return light;
  26963. }
  26964. var camera = this.getCameraByID(id);
  26965. if (camera) {
  26966. return camera;
  26967. }
  26968. var bone = this.getBoneByID(id);
  26969. return bone;
  26970. };
  26971. /**
  26972. * Gets a node (Mesh, Camera, Light) using a given name
  26973. * @param name defines the name to search for
  26974. * @return the found node or null if not found at all.
  26975. */
  26976. Scene.prototype.getNodeByName = function (name) {
  26977. var mesh = this.getMeshByName(name);
  26978. if (mesh) {
  26979. return mesh;
  26980. }
  26981. var light = this.getLightByName(name);
  26982. if (light) {
  26983. return light;
  26984. }
  26985. var camera = this.getCameraByName(name);
  26986. if (camera) {
  26987. return camera;
  26988. }
  26989. var bone = this.getBoneByName(name);
  26990. return bone;
  26991. };
  26992. /**
  26993. * Gets a mesh using a given name
  26994. * @param name defines the name to search for
  26995. * @return the found mesh or null if not found at all.
  26996. */
  26997. Scene.prototype.getMeshByName = function (name) {
  26998. for (var index = 0; index < this.meshes.length; index++) {
  26999. if (this.meshes[index].name === name) {
  27000. return this.meshes[index];
  27001. }
  27002. }
  27003. return null;
  27004. };
  27005. /**
  27006. * Gets a transform node using a given name
  27007. * @param name defines the name to search for
  27008. * @return the found transform node or null if not found at all.
  27009. */
  27010. Scene.prototype.getTransformNodeByName = function (name) {
  27011. for (var index = 0; index < this.transformNodes.length; index++) {
  27012. if (this.transformNodes[index].name === name) {
  27013. return this.transformNodes[index];
  27014. }
  27015. }
  27016. return null;
  27017. };
  27018. /**
  27019. * Gets a sound using a given name
  27020. * @param name defines the name to search for
  27021. * @return the found sound or null if not found at all.
  27022. */
  27023. Scene.prototype.getSoundByName = function (name) {
  27024. var index;
  27025. if (BABYLON.AudioEngine) {
  27026. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  27027. if (this.mainSoundTrack.soundCollection[index].name === name) {
  27028. return this.mainSoundTrack.soundCollection[index];
  27029. }
  27030. }
  27031. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  27032. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  27033. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  27034. return this.soundTracks[sdIndex].soundCollection[index];
  27035. }
  27036. }
  27037. }
  27038. }
  27039. return null;
  27040. };
  27041. /**
  27042. * Gets a skeleton using a given id (if many are found, this function will pick the last one)
  27043. * @param id defines the id to search for
  27044. * @return the found skeleton or null if not found at all.
  27045. */
  27046. Scene.prototype.getLastSkeletonByID = function (id) {
  27047. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  27048. if (this.skeletons[index].id === id) {
  27049. return this.skeletons[index];
  27050. }
  27051. }
  27052. return null;
  27053. };
  27054. /**
  27055. * Gets a skeleton using a given id (if many are found, this function will pick the first one)
  27056. * @param id defines the id to search for
  27057. * @return the found skeleton or null if not found at all.
  27058. */
  27059. Scene.prototype.getSkeletonById = function (id) {
  27060. for (var index = 0; index < this.skeletons.length; index++) {
  27061. if (this.skeletons[index].id === id) {
  27062. return this.skeletons[index];
  27063. }
  27064. }
  27065. return null;
  27066. };
  27067. /**
  27068. * Gets a skeleton using a given name
  27069. * @param name defines the name to search for
  27070. * @return the found skeleton or null if not found at all.
  27071. */
  27072. Scene.prototype.getSkeletonByName = function (name) {
  27073. for (var index = 0; index < this.skeletons.length; index++) {
  27074. if (this.skeletons[index].name === name) {
  27075. return this.skeletons[index];
  27076. }
  27077. }
  27078. return null;
  27079. };
  27080. /**
  27081. * Gets a morph target manager using a given id (if many are found, this function will pick the last one)
  27082. * @param id defines the id to search for
  27083. * @return the found morph target manager or null if not found at all.
  27084. */
  27085. Scene.prototype.getMorphTargetManagerById = function (id) {
  27086. for (var index = 0; index < this.morphTargetManagers.length; index++) {
  27087. if (this.morphTargetManagers[index].uniqueId === id) {
  27088. return this.morphTargetManagers[index];
  27089. }
  27090. }
  27091. return null;
  27092. };
  27093. /**
  27094. * Gets a boolean indicating if the given mesh is active
  27095. * @param mesh defines the mesh to look for
  27096. * @returns true if the mesh is in the active list
  27097. */
  27098. Scene.prototype.isActiveMesh = function (mesh) {
  27099. return (this._activeMeshes.indexOf(mesh) !== -1);
  27100. };
  27101. /**
  27102. * Return a the first highlight layer of the scene with a given name.
  27103. * @param name The name of the highlight layer to look for.
  27104. * @return The highlight layer if found otherwise null.
  27105. */
  27106. Scene.prototype.getHighlightLayerByName = function (name) {
  27107. for (var index = 0; index < this.effectLayers.length; index++) {
  27108. if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === BABYLON.HighlightLayer.EffectName) {
  27109. return this.effectLayers[index];
  27110. }
  27111. }
  27112. return null;
  27113. };
  27114. /**
  27115. * Return a the first highlight layer of the scene with a given name.
  27116. * @param name The name of the highlight layer to look for.
  27117. * @return The highlight layer if found otherwise null.
  27118. */
  27119. Scene.prototype.getGlowLayerByName = function (name) {
  27120. for (var index = 0; index < this.effectLayers.length; index++) {
  27121. if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === BABYLON.GlowLayer.EffectName) {
  27122. return this.effectLayers[index];
  27123. }
  27124. }
  27125. return null;
  27126. };
  27127. Object.defineProperty(Scene.prototype, "uid", {
  27128. /**
  27129. * Return a unique id as a string which can serve as an identifier for the scene
  27130. */
  27131. get: function () {
  27132. if (!this._uid) {
  27133. this._uid = BABYLON.Tools.RandomId();
  27134. }
  27135. return this._uid;
  27136. },
  27137. enumerable: true,
  27138. configurable: true
  27139. });
  27140. /**
  27141. * Add an externaly attached data from its key.
  27142. * This method call will fail and return false, if such key already exists.
  27143. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  27144. * @param key the unique key that identifies the data
  27145. * @param data the data object to associate to the key for this Engine instance
  27146. * @return true if no such key were already present and the data was added successfully, false otherwise
  27147. */
  27148. Scene.prototype.addExternalData = function (key, data) {
  27149. if (!this._externalData) {
  27150. this._externalData = new BABYLON.StringDictionary();
  27151. }
  27152. return this._externalData.add(key, data);
  27153. };
  27154. /**
  27155. * Get an externaly attached data from its key
  27156. * @param key the unique key that identifies the data
  27157. * @return the associated data, if present (can be null), or undefined if not present
  27158. */
  27159. Scene.prototype.getExternalData = function (key) {
  27160. if (!this._externalData) {
  27161. return null;
  27162. }
  27163. return this._externalData.get(key);
  27164. };
  27165. /**
  27166. * Get an externaly attached data from its key, create it using a factory if it's not already present
  27167. * @param key the unique key that identifies the data
  27168. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  27169. * @return the associated data, can be null if the factory returned null.
  27170. */
  27171. Scene.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  27172. if (!this._externalData) {
  27173. this._externalData = new BABYLON.StringDictionary();
  27174. }
  27175. return this._externalData.getOrAddWithFactory(key, factory);
  27176. };
  27177. /**
  27178. * Remove an externaly attached data from the Engine instance
  27179. * @param key the unique key that identifies the data
  27180. * @return true if the data was successfully removed, false if it doesn't exist
  27181. */
  27182. Scene.prototype.removeExternalData = function (key) {
  27183. return this._externalData.remove(key);
  27184. };
  27185. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  27186. if (this.dispatchAllSubMeshesOfActiveMeshes || mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  27187. if (mesh.showSubMeshesBoundingBox) {
  27188. var boundingInfo = subMesh.getBoundingInfo();
  27189. if (boundingInfo !== null && boundingInfo !== undefined) {
  27190. this.getBoundingBoxRenderer().renderList.push(boundingInfo.boundingBox);
  27191. }
  27192. }
  27193. var material = subMesh.getMaterial();
  27194. if (material !== null && material !== undefined) {
  27195. // Render targets
  27196. if (material.getRenderTargetTextures !== undefined) {
  27197. if (this._processedMaterials.indexOf(material) === -1) {
  27198. this._processedMaterials.push(material);
  27199. this._renderTargets.concatWithNoDuplicate(material.getRenderTargetTextures());
  27200. }
  27201. }
  27202. // Dispatch
  27203. this._activeIndices.addCount(subMesh.indexCount, false);
  27204. this._renderingManager.dispatch(subMesh, mesh, material);
  27205. }
  27206. }
  27207. };
  27208. /**
  27209. * Clear the processed materials smart array preventing retention point in material dispose.
  27210. */
  27211. Scene.prototype.freeProcessedMaterials = function () {
  27212. this._processedMaterials.dispose();
  27213. };
  27214. /**
  27215. * Clear the active meshes smart array preventing retention point in mesh dispose.
  27216. */
  27217. Scene.prototype.freeActiveMeshes = function () {
  27218. this._activeMeshes.dispose();
  27219. if (this.activeCamera && this.activeCamera._activeMeshes) {
  27220. this.activeCamera._activeMeshes.dispose();
  27221. }
  27222. if (this.activeCameras) {
  27223. for (var i = 0; i < this.activeCameras.length; i++) {
  27224. var activeCamera = this.activeCameras[i];
  27225. if (activeCamera && activeCamera._activeMeshes) {
  27226. activeCamera._activeMeshes.dispose();
  27227. }
  27228. }
  27229. }
  27230. };
  27231. /**
  27232. * Clear the info related to rendering groups preventing retention points during dispose.
  27233. */
  27234. Scene.prototype.freeRenderingGroups = function () {
  27235. if (this._renderingManager) {
  27236. this._renderingManager.freeRenderingGroups();
  27237. }
  27238. if (this.textures) {
  27239. for (var i = 0; i < this.textures.length; i++) {
  27240. var texture = this.textures[i];
  27241. if (texture && texture.renderList) {
  27242. texture.freeRenderingGroups();
  27243. }
  27244. }
  27245. }
  27246. };
  27247. /** @hidden */
  27248. Scene.prototype._isInIntermediateRendering = function () {
  27249. return this._intermediateRendering;
  27250. };
  27251. /**
  27252. * Defines the current active mesh candidate provider
  27253. * @param provider defines the provider to use
  27254. */
  27255. Scene.prototype.setActiveMeshCandidateProvider = function (provider) {
  27256. this._activeMeshCandidateProvider = provider;
  27257. };
  27258. /**
  27259. * Gets the current active mesh candidate provider
  27260. * @returns the current active mesh candidate provider
  27261. */
  27262. Scene.prototype.getActiveMeshCandidateProvider = function () {
  27263. return this._activeMeshCandidateProvider;
  27264. };
  27265. /**
  27266. * Use this function to stop evaluating active meshes. The current list will be keep alive between frames
  27267. * @returns the current scene
  27268. */
  27269. Scene.prototype.freezeActiveMeshes = function () {
  27270. if (!this.activeCamera) {
  27271. return this;
  27272. }
  27273. if (!this._frustumPlanes) {
  27274. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  27275. }
  27276. this._evaluateActiveMeshes();
  27277. this._activeMeshesFrozen = true;
  27278. return this;
  27279. };
  27280. /**
  27281. * Use this function to restart evaluating active meshes on every frame
  27282. * @returns the current scene
  27283. */
  27284. Scene.prototype.unfreezeActiveMeshes = function () {
  27285. this._activeMeshesFrozen = false;
  27286. return this;
  27287. };
  27288. Scene.prototype._evaluateActiveMeshes = function () {
  27289. if (this._activeMeshesFrozen && this._activeMeshes.length) {
  27290. return;
  27291. }
  27292. if (!this.activeCamera) {
  27293. return;
  27294. }
  27295. this.onBeforeActiveMeshesEvaluationObservable.notifyObservers(this);
  27296. this.activeCamera._activeMeshes.reset();
  27297. this._activeMeshes.reset();
  27298. this._renderingManager.reset();
  27299. this._processedMaterials.reset();
  27300. this._activeParticleSystems.reset();
  27301. this._activeSkeletons.reset();
  27302. this._softwareSkinnedMeshes.reset();
  27303. if (this._boundingBoxRenderer) {
  27304. this._boundingBoxRenderer.reset();
  27305. }
  27306. // Meshes
  27307. var meshes;
  27308. var len;
  27309. var checkIsEnabled = true;
  27310. // Determine mesh candidates
  27311. if (this._activeMeshCandidateProvider !== undefined) {
  27312. // Use _activeMeshCandidateProvider
  27313. meshes = this._activeMeshCandidateProvider.getMeshes(this);
  27314. checkIsEnabled = this._activeMeshCandidateProvider.checksIsEnabled === false;
  27315. if (meshes !== undefined) {
  27316. len = meshes.length;
  27317. }
  27318. else {
  27319. len = 0;
  27320. }
  27321. }
  27322. else if (this._selectionOctree !== undefined) {
  27323. // Octree
  27324. var selection = this._selectionOctree.select(this._frustumPlanes);
  27325. meshes = selection.data;
  27326. len = selection.length;
  27327. }
  27328. else {
  27329. // Full scene traversal
  27330. len = this.meshes.length;
  27331. meshes = this.meshes;
  27332. }
  27333. // Check each mesh
  27334. for (var meshIndex = 0, mesh, meshLOD; meshIndex < len; meshIndex++) {
  27335. mesh = meshes[meshIndex];
  27336. if (mesh.isBlocked) {
  27337. continue;
  27338. }
  27339. this._totalVertices.addCount(mesh.getTotalVertices(), false);
  27340. if (!mesh.isReady() || (checkIsEnabled && !mesh.isEnabled())) {
  27341. continue;
  27342. }
  27343. mesh.computeWorldMatrix();
  27344. // Intersections
  27345. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  27346. this._meshesForIntersections.pushNoDuplicate(mesh);
  27347. }
  27348. // Switch to current LOD
  27349. meshLOD = mesh.getLOD(this.activeCamera);
  27350. if (meshLOD === undefined || meshLOD === null) {
  27351. continue;
  27352. }
  27353. mesh._preActivate();
  27354. if (mesh.alwaysSelectAsActiveMesh || mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  27355. this._activeMeshes.push(mesh);
  27356. this.activeCamera._activeMeshes.push(mesh);
  27357. mesh._activate(this._renderId);
  27358. if (meshLOD !== mesh) {
  27359. meshLOD._activate(this._renderId);
  27360. }
  27361. this._activeMesh(mesh, meshLOD);
  27362. }
  27363. }
  27364. this.onAfterActiveMeshesEvaluationObservable.notifyObservers(this);
  27365. // Particle systems
  27366. if (this.particlesEnabled) {
  27367. this.onBeforeParticlesRenderingObservable.notifyObservers(this);
  27368. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  27369. var particleSystem = this.particleSystems[particleIndex];
  27370. if (!particleSystem.isStarted() || !particleSystem.emitter) {
  27371. continue;
  27372. }
  27373. var emitter = particleSystem.emitter;
  27374. if (!emitter.position || emitter.isEnabled()) {
  27375. this._activeParticleSystems.push(particleSystem);
  27376. particleSystem.animate();
  27377. this._renderingManager.dispatchParticles(particleSystem);
  27378. }
  27379. }
  27380. this.onAfterParticlesRenderingObservable.notifyObservers(this);
  27381. }
  27382. };
  27383. Scene.prototype._activeMesh = function (sourceMesh, mesh) {
  27384. if (this.skeletonsEnabled && mesh.skeleton !== null && mesh.skeleton !== undefined) {
  27385. if (this._activeSkeletons.pushNoDuplicate(mesh.skeleton)) {
  27386. mesh.skeleton.prepare();
  27387. }
  27388. if (!mesh.computeBonesUsingShaders) {
  27389. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  27390. }
  27391. }
  27392. if (sourceMesh.showBoundingBox || this.forceShowBoundingBoxes) {
  27393. var boundingInfo = sourceMesh.getBoundingInfo();
  27394. this.getBoundingBoxRenderer().renderList.push(boundingInfo.boundingBox);
  27395. }
  27396. if (mesh !== undefined && mesh !== null
  27397. && mesh.subMeshes !== undefined && mesh.subMeshes !== null && mesh.subMeshes.length > 0) {
  27398. // Submeshes Octrees
  27399. var len;
  27400. var subMeshes;
  27401. if (mesh.useOctreeForRenderingSelection && mesh._submeshesOctree !== undefined && mesh._submeshesOctree !== null) {
  27402. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  27403. len = intersections.length;
  27404. subMeshes = intersections.data;
  27405. }
  27406. else {
  27407. subMeshes = mesh.subMeshes;
  27408. len = subMeshes.length;
  27409. }
  27410. for (var subIndex = 0, subMesh; subIndex < len; subIndex++) {
  27411. subMesh = subMeshes[subIndex];
  27412. this._evaluateSubMesh(subMesh, mesh);
  27413. }
  27414. }
  27415. };
  27416. /**
  27417. * Update the transform matrix to update from the current active camera
  27418. * @param force defines a boolean used to force the update even if cache is up to date
  27419. */
  27420. Scene.prototype.updateTransformMatrix = function (force) {
  27421. if (!this.activeCamera) {
  27422. return;
  27423. }
  27424. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  27425. };
  27426. /**
  27427. * 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)
  27428. * @param alternateCamera defines the camera to use
  27429. */
  27430. Scene.prototype.updateAlternateTransformMatrix = function (alternateCamera) {
  27431. this._setAlternateTransformMatrix(alternateCamera.getViewMatrix(), alternateCamera.getProjectionMatrix());
  27432. };
  27433. Scene.prototype._renderForCamera = function (camera, rigParent) {
  27434. if (camera && camera._skipRendering) {
  27435. return;
  27436. }
  27437. var engine = this._engine;
  27438. this.activeCamera = camera;
  27439. if (!this.activeCamera)
  27440. throw new Error("Active camera not set");
  27441. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  27442. // Viewport
  27443. engine.setViewport(this.activeCamera.viewport);
  27444. // Camera
  27445. this.resetCachedMaterial();
  27446. this._renderId++;
  27447. this.updateTransformMatrix();
  27448. if (camera._alternateCamera) {
  27449. this.updateAlternateTransformMatrix(camera._alternateCamera);
  27450. this._alternateRendering = true;
  27451. }
  27452. this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera);
  27453. // Meshes
  27454. this._evaluateActiveMeshes();
  27455. // Software skinning
  27456. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  27457. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  27458. mesh.applySkeleton(mesh.skeleton);
  27459. }
  27460. // Render targets
  27461. this.onBeforeRenderTargetsRenderObservable.notifyObservers(this);
  27462. var needsRestoreFrameBuffer = false;
  27463. if (camera.customRenderTargets && camera.customRenderTargets.length > 0) {
  27464. this._renderTargets.concatWithNoDuplicate(camera.customRenderTargets);
  27465. }
  27466. if (rigParent && rigParent.customRenderTargets && rigParent.customRenderTargets.length > 0) {
  27467. this._renderTargets.concatWithNoDuplicate(rigParent.customRenderTargets);
  27468. }
  27469. if (this.renderTargetsEnabled && this._renderTargets.length > 0) {
  27470. this._intermediateRendering = true;
  27471. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  27472. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  27473. var renderTarget = this._renderTargets.data[renderIndex];
  27474. if (renderTarget._shouldRender()) {
  27475. this._renderId++;
  27476. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  27477. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  27478. }
  27479. }
  27480. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  27481. this._intermediateRendering = false;
  27482. this._renderId++;
  27483. needsRestoreFrameBuffer = true; // Restore back buffer
  27484. }
  27485. // Render EffecttLayer Texture
  27486. var stencilState = this._engine.getStencilBuffer();
  27487. var renderEffects = false;
  27488. var needStencil = false;
  27489. if (this.renderTargetsEnabled && this.effectLayers && this.effectLayers.length > 0) {
  27490. this._intermediateRendering = true;
  27491. for (var i = 0; i < this.effectLayers.length; i++) {
  27492. var effectLayer = this.effectLayers[i];
  27493. if (effectLayer.shouldRender() &&
  27494. (!effectLayer.camera ||
  27495. (effectLayer.camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE && camera === effectLayer.camera) ||
  27496. (effectLayer.camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE && effectLayer.camera._rigCameras.indexOf(camera) > -1))) {
  27497. renderEffects = true;
  27498. needStencil = needStencil || effectLayer.needStencil();
  27499. var renderTarget = effectLayer._mainTexture;
  27500. if (renderTarget._shouldRender()) {
  27501. this._renderId++;
  27502. renderTarget.render(false, false);
  27503. needsRestoreFrameBuffer = true;
  27504. }
  27505. }
  27506. }
  27507. this._intermediateRendering = false;
  27508. this._renderId++;
  27509. }
  27510. if (needsRestoreFrameBuffer) {
  27511. engine.restoreDefaultFramebuffer(); // Restore back buffer
  27512. }
  27513. this.onAfterRenderTargetsRenderObservable.notifyObservers(this);
  27514. // Prepare Frame
  27515. this.postProcessManager._prepareFrame();
  27516. // Backgrounds
  27517. var layerIndex;
  27518. var layer;
  27519. if (this.layers.length) {
  27520. engine.setDepthBuffer(false);
  27521. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  27522. layer = this.layers[layerIndex];
  27523. if (layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  27524. layer.render();
  27525. }
  27526. }
  27527. engine.setDepthBuffer(true);
  27528. }
  27529. // Activate effect Layer stencil
  27530. if (needStencil) {
  27531. this._engine.setStencilBuffer(true);
  27532. }
  27533. // Render
  27534. this.onBeforeDrawPhaseObservable.notifyObservers(this);
  27535. this._renderingManager.render(null, null, true, true);
  27536. this.onAfterDrawPhaseObservable.notifyObservers(this);
  27537. // Restore effect Layer stencil
  27538. if (needStencil) {
  27539. this._engine.setStencilBuffer(stencilState);
  27540. }
  27541. // Bounding boxes
  27542. if (this._boundingBoxRenderer) {
  27543. this._boundingBoxRenderer.render();
  27544. }
  27545. // Lens flares
  27546. if (this.lensFlaresEnabled) {
  27547. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  27548. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  27549. var lensFlareSystem = this.lensFlareSystems[lensFlareSystemIndex];
  27550. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  27551. lensFlareSystem.render();
  27552. }
  27553. }
  27554. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  27555. }
  27556. // Effect Layer
  27557. if (renderEffects) {
  27558. engine.setDepthBuffer(false);
  27559. for (var i = 0; i < this.effectLayers.length; i++) {
  27560. if (this.effectLayers[i].shouldRender()) {
  27561. this.effectLayers[i].render();
  27562. }
  27563. }
  27564. engine.setDepthBuffer(true);
  27565. }
  27566. // Foregrounds
  27567. if (this.layers.length) {
  27568. engine.setDepthBuffer(false);
  27569. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  27570. layer = this.layers[layerIndex];
  27571. if (!layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  27572. layer.render();
  27573. }
  27574. }
  27575. engine.setDepthBuffer(true);
  27576. }
  27577. // Finalize frame
  27578. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  27579. // Reset some special arrays
  27580. this._renderTargets.reset();
  27581. this._alternateRendering = false;
  27582. this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera);
  27583. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  27584. };
  27585. Scene.prototype._processSubCameras = function (camera) {
  27586. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  27587. this._renderForCamera(camera);
  27588. return;
  27589. }
  27590. // rig cameras
  27591. for (var index = 0; index < camera._rigCameras.length; index++) {
  27592. this._renderForCamera(camera._rigCameras[index], camera);
  27593. }
  27594. this.activeCamera = camera;
  27595. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  27596. };
  27597. Scene.prototype._checkIntersections = function () {
  27598. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  27599. var sourceMesh = this._meshesForIntersections.data[index];
  27600. if (!sourceMesh.actionManager) {
  27601. continue;
  27602. }
  27603. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  27604. var action = sourceMesh.actionManager.actions[actionIndex];
  27605. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27606. var parameters = action.getTriggerParameter();
  27607. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  27608. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  27609. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  27610. if (areIntersecting && currentIntersectionInProgress === -1) {
  27611. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  27612. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  27613. sourceMesh._intersectionsInProgress.push(otherMesh);
  27614. }
  27615. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27616. sourceMesh._intersectionsInProgress.push(otherMesh);
  27617. }
  27618. }
  27619. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  27620. //They intersected, and now they don't.
  27621. //is this trigger an exit trigger? execute an event.
  27622. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27623. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  27624. }
  27625. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  27626. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger, function (parameter) {
  27627. var parameterMesh = parameter instanceof BABYLON.AbstractMesh ? parameter : parameter.mesh;
  27628. return otherMesh === parameterMesh;
  27629. }) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27630. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  27631. }
  27632. }
  27633. }
  27634. }
  27635. }
  27636. };
  27637. /**
  27638. * Render the scene
  27639. * @param updateCameras defines a boolean indicating if cameras must update according to their inputs (true by default)
  27640. */
  27641. Scene.prototype.render = function (updateCameras) {
  27642. if (updateCameras === void 0) { updateCameras = true; }
  27643. if (this.isDisposed) {
  27644. return;
  27645. }
  27646. this._activeParticles.fetchNewFrame();
  27647. this._totalVertices.fetchNewFrame();
  27648. this._activeIndices.fetchNewFrame();
  27649. this._activeBones.fetchNewFrame();
  27650. this._meshesForIntersections.reset();
  27651. this.resetCachedMaterial();
  27652. this.onBeforeAnimationsObservable.notifyObservers(this);
  27653. // Actions
  27654. if (this.actionManager) {
  27655. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger);
  27656. }
  27657. //Simplification Queue
  27658. if (this.simplificationQueue && !this.simplificationQueue.running) {
  27659. this.simplificationQueue.executeNext();
  27660. }
  27661. if (this._engine.isDeterministicLockStep()) {
  27662. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime)) + this._timeAccumulator;
  27663. var defaultFPS = (60.0 / 1000.0);
  27664. var defaultFrameTime = 1000 / 60; // frame time in MS
  27665. if (this._physicsEngine) {
  27666. defaultFrameTime = this._physicsEngine.getTimeStep() * 1000;
  27667. }
  27668. var stepsTaken = 0;
  27669. var maxSubSteps = this._engine.getLockstepMaxSteps();
  27670. var internalSteps = Math.floor(deltaTime / (1000 * defaultFPS));
  27671. internalSteps = Math.min(internalSteps, maxSubSteps);
  27672. do {
  27673. this.onBeforeStepObservable.notifyObservers(this);
  27674. // Animations
  27675. this._animationRatio = defaultFrameTime * defaultFPS;
  27676. this._animate();
  27677. this.onAfterAnimationsObservable.notifyObservers(this);
  27678. // Physics
  27679. if (this._physicsEngine) {
  27680. this.onBeforePhysicsObservable.notifyObservers(this);
  27681. this._physicsEngine._step(defaultFrameTime / 1000);
  27682. this.onAfterPhysicsObservable.notifyObservers(this);
  27683. }
  27684. this.onAfterStepObservable.notifyObservers(this);
  27685. this._currentStepId++;
  27686. stepsTaken++;
  27687. deltaTime -= defaultFrameTime;
  27688. } while (deltaTime > 0 && stepsTaken < internalSteps);
  27689. this._timeAccumulator = deltaTime < 0 ? 0 : deltaTime;
  27690. }
  27691. else {
  27692. // Animations
  27693. var deltaTime = this.useConstantAnimationDeltaTime ? 16 : Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  27694. this._animationRatio = deltaTime * (60.0 / 1000.0);
  27695. this._animate();
  27696. this.onAfterAnimationsObservable.notifyObservers(this);
  27697. // Physics
  27698. if (this._physicsEngine) {
  27699. this.onBeforePhysicsObservable.notifyObservers(this);
  27700. this._physicsEngine._step(deltaTime / 1000.0);
  27701. this.onAfterPhysicsObservable.notifyObservers(this);
  27702. }
  27703. }
  27704. // update gamepad manager
  27705. if (this._gamepadManager && this._gamepadManager._isMonitoring) {
  27706. this._gamepadManager._checkGamepadsStatus();
  27707. }
  27708. // Update Cameras
  27709. if (updateCameras) {
  27710. if (this.activeCameras.length > 0) {
  27711. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  27712. var camera = this.activeCameras[cameraIndex];
  27713. camera.update();
  27714. if (camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  27715. // rig cameras
  27716. for (var index = 0; index < camera._rigCameras.length; index++) {
  27717. camera._rigCameras[index].update();
  27718. }
  27719. }
  27720. }
  27721. }
  27722. else if (this.activeCamera) {
  27723. this.activeCamera.update();
  27724. if (this.activeCamera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  27725. // rig cameras
  27726. for (var index = 0; index < this.activeCamera._rigCameras.length; index++) {
  27727. this.activeCamera._rigCameras[index].update();
  27728. }
  27729. }
  27730. }
  27731. }
  27732. // Before render
  27733. this.onBeforeRenderObservable.notifyObservers(this);
  27734. // Customs render targets
  27735. this.onBeforeRenderTargetsRenderObservable.notifyObservers(this);
  27736. var engine = this.getEngine();
  27737. var currentActiveCamera = this.activeCamera;
  27738. if (this.renderTargetsEnabled) {
  27739. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  27740. this._intermediateRendering = true;
  27741. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  27742. var renderTarget = this.customRenderTargets[customIndex];
  27743. if (renderTarget._shouldRender()) {
  27744. this._renderId++;
  27745. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  27746. if (!this.activeCamera)
  27747. throw new Error("Active camera not set");
  27748. // Viewport
  27749. engine.setViewport(this.activeCamera.viewport);
  27750. // Camera
  27751. this.updateTransformMatrix();
  27752. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  27753. }
  27754. }
  27755. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  27756. this._intermediateRendering = false;
  27757. this._renderId++;
  27758. }
  27759. // Restore back buffer
  27760. if (this.customRenderTargets.length > 0) {
  27761. engine.restoreDefaultFramebuffer();
  27762. }
  27763. this.onAfterRenderTargetsRenderObservable.notifyObservers(this);
  27764. this.activeCamera = currentActiveCamera;
  27765. // Procedural textures
  27766. if (this.proceduralTexturesEnabled) {
  27767. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this.proceduralTextures.length > 0);
  27768. for (var proceduralIndex = 0; proceduralIndex < this.proceduralTextures.length; proceduralIndex++) {
  27769. var proceduralTexture = this.proceduralTextures[proceduralIndex];
  27770. if (proceduralTexture._shouldRender()) {
  27771. proceduralTexture.render();
  27772. }
  27773. }
  27774. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this.proceduralTextures.length > 0);
  27775. }
  27776. // Clear
  27777. if (this.autoClearDepthAndStencil || this.autoClear) {
  27778. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, this.autoClearDepthAndStencil, this.autoClearDepthAndStencil);
  27779. }
  27780. // Shadows
  27781. if (this.shadowsEnabled) {
  27782. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  27783. var light = this.lights[lightIndex];
  27784. var shadowGenerator = light.getShadowGenerator();
  27785. if (light.isEnabled() && light.shadowEnabled && shadowGenerator) {
  27786. var shadowMap = (shadowGenerator.getShadowMap());
  27787. if (this.textures.indexOf(shadowMap) !== -1) {
  27788. this._renderTargets.push(shadowMap);
  27789. }
  27790. }
  27791. }
  27792. }
  27793. // Depth renderer
  27794. for (var key in this._depthRenderer) {
  27795. this._renderTargets.push(this._depthRenderer[key].getDepthMap());
  27796. }
  27797. // Geometry renderer
  27798. if (this._geometryBufferRenderer) {
  27799. this._renderTargets.push(this._geometryBufferRenderer.getGBuffer());
  27800. }
  27801. // RenderPipeline
  27802. if (this._postProcessRenderPipelineManager) {
  27803. this._postProcessRenderPipelineManager.update();
  27804. }
  27805. // Multi-cameras?
  27806. if (this.activeCameras.length > 0) {
  27807. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  27808. if (cameraIndex > 0) {
  27809. this._engine.clear(null, false, true, true);
  27810. }
  27811. this._processSubCameras(this.activeCameras[cameraIndex]);
  27812. }
  27813. }
  27814. else {
  27815. if (!this.activeCamera) {
  27816. throw new Error("No camera defined");
  27817. }
  27818. this._processSubCameras(this.activeCamera);
  27819. }
  27820. // Intersection checks
  27821. this._checkIntersections();
  27822. // Update the audio listener attached to the camera
  27823. if (BABYLON.AudioEngine) {
  27824. this._updateAudioParameters();
  27825. }
  27826. // After render
  27827. if (this.afterRender) {
  27828. this.afterRender();
  27829. }
  27830. this.onAfterRenderObservable.notifyObservers(this);
  27831. // Cleaning
  27832. for (var index = 0; index < this._toBeDisposed.length; index++) {
  27833. var data = this._toBeDisposed.data[index];
  27834. if (data) {
  27835. data.dispose();
  27836. }
  27837. this._toBeDisposed[index] = null;
  27838. }
  27839. this._toBeDisposed.reset();
  27840. if (this.dumpNextRenderTargets) {
  27841. this.dumpNextRenderTargets = false;
  27842. }
  27843. this._activeBones.addCount(0, true);
  27844. this._activeIndices.addCount(0, true);
  27845. this._activeParticles.addCount(0, true);
  27846. };
  27847. Scene.prototype._updateAudioParameters = function () {
  27848. if (!this.audioEnabled || !this._mainSoundTrack || (this._mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 1)) {
  27849. return;
  27850. }
  27851. var listeningCamera;
  27852. var audioEngine = BABYLON.Engine.audioEngine;
  27853. if (this.activeCameras.length > 0) {
  27854. listeningCamera = this.activeCameras[0];
  27855. }
  27856. else {
  27857. listeningCamera = this.activeCamera;
  27858. }
  27859. if (listeningCamera && audioEngine.canUseWebAudio && audioEngine.audioContext) {
  27860. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  27861. // for VR cameras
  27862. if (listeningCamera.rigCameras && listeningCamera.rigCameras.length > 0) {
  27863. listeningCamera = listeningCamera.rigCameras[0];
  27864. }
  27865. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  27866. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  27867. cameraDirection.normalize();
  27868. // To avoid some errors on GearVR
  27869. if (!isNaN(cameraDirection.x) && !isNaN(cameraDirection.y) && !isNaN(cameraDirection.z)) {
  27870. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  27871. }
  27872. var i;
  27873. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  27874. var sound = this.mainSoundTrack.soundCollection[i];
  27875. if (sound.useCustomAttenuation) {
  27876. sound.updateDistanceFromListener();
  27877. }
  27878. }
  27879. for (i = 0; i < this.soundTracks.length; i++) {
  27880. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  27881. sound = this.soundTracks[i].soundCollection[j];
  27882. if (sound.useCustomAttenuation) {
  27883. sound.updateDistanceFromListener();
  27884. }
  27885. }
  27886. }
  27887. }
  27888. };
  27889. Object.defineProperty(Scene.prototype, "audioEnabled", {
  27890. // Audio
  27891. /**
  27892. * Gets or sets if audio support is enabled
  27893. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  27894. */
  27895. get: function () {
  27896. return this._audioEnabled;
  27897. },
  27898. set: function (value) {
  27899. this._audioEnabled = value;
  27900. if (BABYLON.AudioEngine) {
  27901. if (this._audioEnabled) {
  27902. this._enableAudio();
  27903. }
  27904. else {
  27905. this._disableAudio();
  27906. }
  27907. }
  27908. },
  27909. enumerable: true,
  27910. configurable: true
  27911. });
  27912. Scene.prototype._disableAudio = function () {
  27913. var i;
  27914. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  27915. this.mainSoundTrack.soundCollection[i].pause();
  27916. }
  27917. for (i = 0; i < this.soundTracks.length; i++) {
  27918. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  27919. this.soundTracks[i].soundCollection[j].pause();
  27920. }
  27921. }
  27922. };
  27923. Scene.prototype._enableAudio = function () {
  27924. var i;
  27925. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  27926. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  27927. this.mainSoundTrack.soundCollection[i].play();
  27928. }
  27929. }
  27930. for (i = 0; i < this.soundTracks.length; i++) {
  27931. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  27932. if (this.soundTracks[i].soundCollection[j].isPaused) {
  27933. this.soundTracks[i].soundCollection[j].play();
  27934. }
  27935. }
  27936. }
  27937. };
  27938. Object.defineProperty(Scene.prototype, "headphone", {
  27939. /**
  27940. * Gets or sets if audio will be output to headphones
  27941. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  27942. */
  27943. get: function () {
  27944. return this._headphone;
  27945. },
  27946. set: function (value) {
  27947. this._headphone = value;
  27948. if (BABYLON.AudioEngine) {
  27949. if (this._headphone) {
  27950. this._switchAudioModeForHeadphones();
  27951. }
  27952. else {
  27953. this._switchAudioModeForNormalSpeakers();
  27954. }
  27955. }
  27956. },
  27957. enumerable: true,
  27958. configurable: true
  27959. });
  27960. Scene.prototype._switchAudioModeForHeadphones = function () {
  27961. this.mainSoundTrack.switchPanningModelToHRTF();
  27962. for (var i = 0; i < this.soundTracks.length; i++) {
  27963. this.soundTracks[i].switchPanningModelToHRTF();
  27964. }
  27965. };
  27966. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  27967. this.mainSoundTrack.switchPanningModelToEqualPower();
  27968. for (var i = 0; i < this.soundTracks.length; i++) {
  27969. this.soundTracks[i].switchPanningModelToEqualPower();
  27970. }
  27971. };
  27972. /**
  27973. * Creates a depth renderer a given camera which contains a depth map which can be used for post processing.
  27974. * @param camera The camera to create the depth renderer on (default: scene's active camera)
  27975. * @returns the created depth renderer
  27976. */
  27977. Scene.prototype.enableDepthRenderer = function (camera) {
  27978. camera = camera || this.activeCamera;
  27979. if (!camera) {
  27980. throw "No camera available to enable depth renderer";
  27981. }
  27982. if (!this._depthRenderer[camera.id]) {
  27983. var textureType = 0;
  27984. if (this._engine.getCaps().textureHalfFloatRender) {
  27985. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  27986. }
  27987. else if (this._engine.getCaps().textureFloatRender) {
  27988. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  27989. }
  27990. else {
  27991. throw "Depth renderer does not support int texture type";
  27992. }
  27993. this._depthRenderer[camera.id] = new BABYLON.DepthRenderer(this, textureType, camera);
  27994. }
  27995. return this._depthRenderer[camera.id];
  27996. };
  27997. /**
  27998. * Disables a depth renderer for a given camera
  27999. * @param camera The camera to disable the depth renderer on (default: scene's active camera)
  28000. */
  28001. Scene.prototype.disableDepthRenderer = function (camera) {
  28002. camera = camera || this.activeCamera;
  28003. if (!camera || !this._depthRenderer[camera.id]) {
  28004. return;
  28005. }
  28006. this._depthRenderer[camera.id].dispose();
  28007. delete this._depthRenderer[camera.id];
  28008. };
  28009. /**
  28010. * Enables a GeometryBufferRender and associates it with the scene
  28011. * @param ratio defines the scaling ratio to apply to the renderer (1 by default which means same resolution)
  28012. * @returns the GeometryBufferRenderer
  28013. */
  28014. Scene.prototype.enableGeometryBufferRenderer = function (ratio) {
  28015. if (ratio === void 0) { ratio = 1; }
  28016. if (this._geometryBufferRenderer) {
  28017. return this._geometryBufferRenderer;
  28018. }
  28019. this._geometryBufferRenderer = new BABYLON.GeometryBufferRenderer(this, ratio);
  28020. if (!this._geometryBufferRenderer.isSupported) {
  28021. this._geometryBufferRenderer = null;
  28022. }
  28023. return this._geometryBufferRenderer;
  28024. };
  28025. /**
  28026. * Disables the GeometryBufferRender associated with the scene
  28027. */
  28028. Scene.prototype.disableGeometryBufferRenderer = function () {
  28029. if (!this._geometryBufferRenderer) {
  28030. return;
  28031. }
  28032. this._geometryBufferRenderer.dispose();
  28033. this._geometryBufferRenderer = null;
  28034. };
  28035. /**
  28036. * Freeze all materials
  28037. * A frozen material will not be updatable but should be faster to render
  28038. */
  28039. Scene.prototype.freezeMaterials = function () {
  28040. for (var i = 0; i < this.materials.length; i++) {
  28041. this.materials[i].freeze();
  28042. }
  28043. };
  28044. /**
  28045. * Unfreeze all materials
  28046. * A frozen material will not be updatable but should be faster to render
  28047. */
  28048. Scene.prototype.unfreezeMaterials = function () {
  28049. for (var i = 0; i < this.materials.length; i++) {
  28050. this.materials[i].unfreeze();
  28051. }
  28052. };
  28053. /**
  28054. * Releases all held ressources
  28055. */
  28056. Scene.prototype.dispose = function () {
  28057. this.beforeRender = null;
  28058. this.afterRender = null;
  28059. this.skeletons = [];
  28060. this.morphTargetManagers = [];
  28061. this.importedMeshesFiles = new Array();
  28062. this.stopAllAnimations();
  28063. this.resetCachedMaterial();
  28064. for (var key in this._depthRenderer) {
  28065. this._depthRenderer[key].dispose();
  28066. }
  28067. if (this._gamepadManager) {
  28068. this._gamepadManager.dispose();
  28069. this._gamepadManager = null;
  28070. }
  28071. // Smart arrays
  28072. if (this.activeCamera) {
  28073. this.activeCamera._activeMeshes.dispose();
  28074. this.activeCamera = null;
  28075. }
  28076. this._activeMeshes.dispose();
  28077. this._renderingManager.dispose();
  28078. this._processedMaterials.dispose();
  28079. this._activeParticleSystems.dispose();
  28080. this._activeSkeletons.dispose();
  28081. this._softwareSkinnedMeshes.dispose();
  28082. this._renderTargets.dispose();
  28083. this._registeredForLateAnimationBindings.dispose();
  28084. if (this._boundingBoxRenderer) {
  28085. this._boundingBoxRenderer.dispose();
  28086. }
  28087. this._meshesForIntersections.dispose();
  28088. this._toBeDisposed.dispose();
  28089. // Abort active requests
  28090. for (var _i = 0, _a = this._activeRequests; _i < _a.length; _i++) {
  28091. var request = _a[_i];
  28092. request.abort();
  28093. }
  28094. // Debug layer
  28095. if (this._debugLayer) {
  28096. this._debugLayer.hide();
  28097. }
  28098. // Events
  28099. this.onDisposeObservable.notifyObservers(this);
  28100. this.onDisposeObservable.clear();
  28101. this.onBeforeRenderObservable.clear();
  28102. this.onAfterRenderObservable.clear();
  28103. this.onBeforeRenderTargetsRenderObservable.clear();
  28104. this.onAfterRenderTargetsRenderObservable.clear();
  28105. this.onAfterStepObservable.clear();
  28106. this.onBeforeStepObservable.clear();
  28107. this.onBeforeActiveMeshesEvaluationObservable.clear();
  28108. this.onAfterActiveMeshesEvaluationObservable.clear();
  28109. this.onBeforeParticlesRenderingObservable.clear();
  28110. this.onAfterParticlesRenderingObservable.clear();
  28111. this.onBeforeSpritesRenderingObservable.clear();
  28112. this.onAfterSpritesRenderingObservable.clear();
  28113. this.onBeforeDrawPhaseObservable.clear();
  28114. this.onAfterDrawPhaseObservable.clear();
  28115. this.onBeforePhysicsObservable.clear();
  28116. this.onAfterPhysicsObservable.clear();
  28117. this.onBeforeAnimationsObservable.clear();
  28118. this.onAfterAnimationsObservable.clear();
  28119. this.onDataLoadedObservable.clear();
  28120. this.detachControl();
  28121. // Release sounds & sounds tracks
  28122. if (BABYLON.AudioEngine) {
  28123. this.disposeSounds();
  28124. }
  28125. // VR Helper
  28126. if (this.VRHelper) {
  28127. this.VRHelper.dispose();
  28128. }
  28129. // Detach cameras
  28130. var canvas = this._engine.getRenderingCanvas();
  28131. if (canvas) {
  28132. var index;
  28133. for (index = 0; index < this.cameras.length; index++) {
  28134. this.cameras[index].detachControl(canvas);
  28135. }
  28136. }
  28137. // Release animation groups
  28138. while (this.animationGroups.length) {
  28139. this.animationGroups[0].dispose();
  28140. }
  28141. // Release lights
  28142. while (this.lights.length) {
  28143. this.lights[0].dispose();
  28144. }
  28145. // Release meshes
  28146. while (this.meshes.length) {
  28147. this.meshes[0].dispose(true);
  28148. }
  28149. while (this.transformNodes.length) {
  28150. this.removeTransformNode(this.transformNodes[0]);
  28151. }
  28152. // Release cameras
  28153. while (this.cameras.length) {
  28154. this.cameras[0].dispose();
  28155. }
  28156. // Release materials
  28157. if (this.defaultMaterial) {
  28158. this.defaultMaterial.dispose();
  28159. }
  28160. while (this.multiMaterials.length) {
  28161. this.multiMaterials[0].dispose();
  28162. }
  28163. while (this.materials.length) {
  28164. this.materials[0].dispose();
  28165. }
  28166. // Release particles
  28167. while (this.particleSystems.length) {
  28168. this.particleSystems[0].dispose();
  28169. }
  28170. // Release sprites
  28171. while (this.spriteManagers.length) {
  28172. this.spriteManagers[0].dispose();
  28173. }
  28174. // Release postProcesses
  28175. while (this.postProcesses.length) {
  28176. this.postProcesses[0].dispose();
  28177. }
  28178. // Release layers
  28179. while (this.layers.length) {
  28180. this.layers[0].dispose();
  28181. }
  28182. while (this.effectLayers.length) {
  28183. this.effectLayers[0].dispose();
  28184. }
  28185. // Release textures
  28186. while (this.textures.length) {
  28187. this.textures[0].dispose();
  28188. }
  28189. // Release UBO
  28190. this._sceneUbo.dispose();
  28191. if (this._alternateSceneUbo) {
  28192. this._alternateSceneUbo.dispose();
  28193. }
  28194. // Post-processes
  28195. this.postProcessManager.dispose();
  28196. if (this._postProcessRenderPipelineManager) {
  28197. this._postProcessRenderPipelineManager.dispose();
  28198. }
  28199. // Physics
  28200. if (this._physicsEngine) {
  28201. this.disablePhysicsEngine();
  28202. }
  28203. // Remove from engine
  28204. index = this._engine.scenes.indexOf(this);
  28205. if (index > -1) {
  28206. this._engine.scenes.splice(index, 1);
  28207. }
  28208. this._engine.wipeCaches(true);
  28209. this._isDisposed = true;
  28210. };
  28211. Object.defineProperty(Scene.prototype, "isDisposed", {
  28212. /**
  28213. * Gets if the scene is already disposed
  28214. */
  28215. get: function () {
  28216. return this._isDisposed;
  28217. },
  28218. enumerable: true,
  28219. configurable: true
  28220. });
  28221. /**
  28222. * Releases sounds & soundtracks
  28223. */
  28224. Scene.prototype.disposeSounds = function () {
  28225. if (!this._mainSoundTrack) {
  28226. return;
  28227. }
  28228. this.mainSoundTrack.dispose();
  28229. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  28230. this.soundTracks[scIndex].dispose();
  28231. }
  28232. };
  28233. /**
  28234. * Call this function to reduce memory footprint of the scene.
  28235. * Vertex buffers will not store CPU data anymore (this will prevent picking, collisions or physics to work correctly)
  28236. */
  28237. Scene.prototype.clearCachedVertexData = function () {
  28238. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  28239. var mesh = this.meshes[meshIndex];
  28240. var geometry = mesh.geometry;
  28241. if (geometry) {
  28242. geometry._indices = [];
  28243. for (var vbName in geometry._vertexBuffers) {
  28244. if (!geometry._vertexBuffers.hasOwnProperty(vbName)) {
  28245. continue;
  28246. }
  28247. geometry._vertexBuffers[vbName]._buffer._data = null;
  28248. }
  28249. }
  28250. }
  28251. };
  28252. /**
  28253. * This function will remove the local cached buffer data from texture.
  28254. * It will save memory but will prevent the texture from being rebuilt
  28255. */
  28256. Scene.prototype.cleanCachedTextureBuffer = function () {
  28257. for (var _i = 0, _a = this.textures; _i < _a.length; _i++) {
  28258. var baseTexture = _a[_i];
  28259. var buffer = baseTexture._buffer;
  28260. if (buffer) {
  28261. baseTexture._buffer = null;
  28262. }
  28263. }
  28264. };
  28265. // Octrees
  28266. /**
  28267. * Get the world extend vectors with an optional filter
  28268. *
  28269. * @param filterPredicate the predicate - which meshes should be included when calculating the world size
  28270. * @returns {{ min: Vector3; max: Vector3 }} min and max vectors
  28271. */
  28272. Scene.prototype.getWorldExtends = function (filterPredicate) {
  28273. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  28274. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  28275. filterPredicate = filterPredicate || (function () { return true; });
  28276. this.meshes.filter(filterPredicate).forEach(function (mesh) {
  28277. mesh.computeWorldMatrix(true);
  28278. if (!mesh.subMeshes || mesh.subMeshes.length === 0 || mesh.infiniteDistance) {
  28279. return;
  28280. }
  28281. var boundingInfo = mesh.getBoundingInfo();
  28282. var minBox = boundingInfo.boundingBox.minimumWorld;
  28283. var maxBox = boundingInfo.boundingBox.maximumWorld;
  28284. BABYLON.Tools.CheckExtends(minBox, min, max);
  28285. BABYLON.Tools.CheckExtends(maxBox, min, max);
  28286. });
  28287. return {
  28288. min: min,
  28289. max: max
  28290. };
  28291. };
  28292. /**
  28293. * Creates or updates the octree used to boost selection (picking)
  28294. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees
  28295. * @param maxCapacity defines the maximum capacity per leaf
  28296. * @param maxDepth defines the maximum depth of the octree
  28297. * @returns an octree of AbstractMesh
  28298. */
  28299. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  28300. if (maxCapacity === void 0) { maxCapacity = 64; }
  28301. if (maxDepth === void 0) { maxDepth = 2; }
  28302. if (!this._selectionOctree) {
  28303. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  28304. }
  28305. var worldExtends = this.getWorldExtends();
  28306. // Update octree
  28307. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  28308. return this._selectionOctree;
  28309. };
  28310. // Picking
  28311. /**
  28312. * Creates a ray that can be used to pick in the scene
  28313. * @param x defines the x coordinate of the origin (on-screen)
  28314. * @param y defines the y coordinate of the origin (on-screen)
  28315. * @param world defines the world matrix to use if you want to pick in object space (instead of world space)
  28316. * @param camera defines the camera to use for the picking
  28317. * @param cameraViewSpace defines if picking will be done in view space (false by default)
  28318. * @returns a Ray
  28319. */
  28320. Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
  28321. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  28322. var result = BABYLON.Ray.Zero();
  28323. this.createPickingRayToRef(x, y, world, result, camera, cameraViewSpace);
  28324. return result;
  28325. };
  28326. /**
  28327. * Creates a ray that can be used to pick in the scene
  28328. * @param x defines the x coordinate of the origin (on-screen)
  28329. * @param y defines the y coordinate of the origin (on-screen)
  28330. * @param world defines the world matrix to use if you want to pick in object space (instead of world space)
  28331. * @param result defines the ray where to store the picking ray
  28332. * @param camera defines the camera to use for the picking
  28333. * @param cameraViewSpace defines if picking will be done in view space (false by default)
  28334. * @returns the current scene
  28335. */
  28336. Scene.prototype.createPickingRayToRef = function (x, y, world, result, camera, cameraViewSpace) {
  28337. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  28338. var engine = this._engine;
  28339. if (!camera) {
  28340. if (!this.activeCamera)
  28341. throw new Error("Active camera not set");
  28342. camera = this.activeCamera;
  28343. }
  28344. var cameraViewport = camera.viewport;
  28345. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  28346. // Moving coordinates to local viewport world
  28347. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  28348. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  28349. result.update(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  28350. return this;
  28351. };
  28352. /**
  28353. * Creates a ray that can be used to pick in the scene
  28354. * @param x defines the x coordinate of the origin (on-screen)
  28355. * @param y defines the y coordinate of the origin (on-screen)
  28356. * @param camera defines the camera to use for the picking
  28357. * @returns a Ray
  28358. */
  28359. Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
  28360. var result = BABYLON.Ray.Zero();
  28361. this.createPickingRayInCameraSpaceToRef(x, y, result, camera);
  28362. return result;
  28363. };
  28364. /**
  28365. * Creates a ray that can be used to pick in the scene
  28366. * @param x defines the x coordinate of the origin (on-screen)
  28367. * @param y defines the y coordinate of the origin (on-screen)
  28368. * @param result defines the ray where to store the picking ray
  28369. * @param camera defines the camera to use for the picking
  28370. * @returns the current scene
  28371. */
  28372. Scene.prototype.createPickingRayInCameraSpaceToRef = function (x, y, result, camera) {
  28373. if (!BABYLON.PickingInfo) {
  28374. return this;
  28375. }
  28376. var engine = this._engine;
  28377. if (!camera) {
  28378. if (!this.activeCamera)
  28379. throw new Error("Active camera not set");
  28380. camera = this.activeCamera;
  28381. }
  28382. var cameraViewport = camera.viewport;
  28383. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  28384. var identity = BABYLON.Matrix.Identity();
  28385. // Moving coordinates to local viewport world
  28386. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  28387. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  28388. result.update(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  28389. return this;
  28390. };
  28391. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  28392. if (!BABYLON.PickingInfo) {
  28393. return null;
  28394. }
  28395. var pickingInfo = null;
  28396. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  28397. var mesh = this.meshes[meshIndex];
  28398. if (predicate) {
  28399. if (!predicate(mesh)) {
  28400. continue;
  28401. }
  28402. }
  28403. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  28404. continue;
  28405. }
  28406. var world = mesh.getWorldMatrix();
  28407. var ray = rayFunction(world);
  28408. var result = mesh.intersects(ray, fastCheck);
  28409. if (!result || !result.hit)
  28410. continue;
  28411. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  28412. continue;
  28413. pickingInfo = result;
  28414. if (fastCheck) {
  28415. break;
  28416. }
  28417. }
  28418. return pickingInfo || new BABYLON.PickingInfo();
  28419. };
  28420. Scene.prototype._internalMultiPick = function (rayFunction, predicate) {
  28421. if (!BABYLON.PickingInfo) {
  28422. return null;
  28423. }
  28424. var pickingInfos = new Array();
  28425. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  28426. var mesh = this.meshes[meshIndex];
  28427. if (predicate) {
  28428. if (!predicate(mesh)) {
  28429. continue;
  28430. }
  28431. }
  28432. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  28433. continue;
  28434. }
  28435. var world = mesh.getWorldMatrix();
  28436. var ray = rayFunction(world);
  28437. var result = mesh.intersects(ray, false);
  28438. if (!result || !result.hit)
  28439. continue;
  28440. pickingInfos.push(result);
  28441. }
  28442. return pickingInfos;
  28443. };
  28444. Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
  28445. if (!BABYLON.PickingInfo) {
  28446. return null;
  28447. }
  28448. var pickingInfo = null;
  28449. if (!camera) {
  28450. if (!this.activeCamera) {
  28451. return null;
  28452. }
  28453. camera = this.activeCamera;
  28454. }
  28455. if (this.spriteManagers.length > 0) {
  28456. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  28457. var spriteManager = this.spriteManagers[spriteIndex];
  28458. if (!spriteManager.isPickable) {
  28459. continue;
  28460. }
  28461. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  28462. if (!result || !result.hit)
  28463. continue;
  28464. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  28465. continue;
  28466. pickingInfo = result;
  28467. if (fastCheck) {
  28468. break;
  28469. }
  28470. }
  28471. }
  28472. return pickingInfo || new BABYLON.PickingInfo();
  28473. };
  28474. /** Launch a ray to try to pick a mesh in the scene
  28475. * @param x position on screen
  28476. * @param y position on screen
  28477. * @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
  28478. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  28479. * @param camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  28480. * @returns a PickingInfo
  28481. */
  28482. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  28483. var _this = this;
  28484. if (!BABYLON.PickingInfo) {
  28485. return null;
  28486. }
  28487. return this._internalPick(function (world) {
  28488. _this.createPickingRayToRef(x, y, world, _this._tempPickingRay, camera || null);
  28489. return _this._tempPickingRay;
  28490. }, predicate, fastCheck);
  28491. };
  28492. /** Launch a ray to try to pick a sprite in the scene
  28493. * @param x position on screen
  28494. * @param y position on screen
  28495. * @param predicate Predicate function used to determine eligible sprites. Can be set to null. In this case, a sprite must have isPickable set to true
  28496. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  28497. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  28498. * @returns a PickingInfo
  28499. */
  28500. Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
  28501. this.createPickingRayInCameraSpaceToRef(x, y, this._tempPickingRay, camera);
  28502. return this._internalPickSprites(this._tempPickingRay, predicate, fastCheck, camera);
  28503. };
  28504. /** Use the given ray to pick a mesh in the scene
  28505. * @param ray The ray to use to pick meshes
  28506. * @param predicate Predicate function used to determine eligible sprites. Can be set to null. In this case, a sprite must have isPickable set to true
  28507. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null
  28508. * @returns a PickingInfo
  28509. */
  28510. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  28511. var _this = this;
  28512. var result = this._internalPick(function (world) {
  28513. if (!_this._pickWithRayInverseMatrix) {
  28514. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  28515. }
  28516. world.invertToRef(_this._pickWithRayInverseMatrix);
  28517. if (!_this._cachedRayForTransform) {
  28518. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  28519. }
  28520. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  28521. return _this._cachedRayForTransform;
  28522. }, predicate, fastCheck);
  28523. if (result) {
  28524. result.ray = ray;
  28525. }
  28526. return result;
  28527. };
  28528. /**
  28529. * Launch a ray to try to pick a mesh in the scene
  28530. * @param x X position on screen
  28531. * @param y Y position on screen
  28532. * @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
  28533. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  28534. * @returns an array of PickingInfo
  28535. */
  28536. Scene.prototype.multiPick = function (x, y, predicate, camera) {
  28537. var _this = this;
  28538. return this._internalMultiPick(function (world) { return _this.createPickingRay(x, y, world, camera || null); }, predicate);
  28539. };
  28540. /**
  28541. * Launch a ray to try to pick a mesh in the scene
  28542. * @param ray Ray to use
  28543. * @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
  28544. * @returns an array of PickingInfo
  28545. */
  28546. Scene.prototype.multiPickWithRay = function (ray, predicate) {
  28547. var _this = this;
  28548. return this._internalMultiPick(function (world) {
  28549. if (!_this._pickWithRayInverseMatrix) {
  28550. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  28551. }
  28552. world.invertToRef(_this._pickWithRayInverseMatrix);
  28553. if (!_this._cachedRayForTransform) {
  28554. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  28555. }
  28556. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  28557. return _this._cachedRayForTransform;
  28558. }, predicate);
  28559. };
  28560. /**
  28561. * Force the value of meshUnderPointer
  28562. * @param mesh defines the mesh to use
  28563. */
  28564. Scene.prototype.setPointerOverMesh = function (mesh) {
  28565. if (this._pointerOverMesh === mesh) {
  28566. return;
  28567. }
  28568. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  28569. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  28570. }
  28571. this._pointerOverMesh = mesh;
  28572. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  28573. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  28574. }
  28575. };
  28576. /**
  28577. * Gets the mesh under the pointer
  28578. * @returns a Mesh or null if no mesh is under the pointer
  28579. */
  28580. Scene.prototype.getPointerOverMesh = function () {
  28581. return this._pointerOverMesh;
  28582. };
  28583. /**
  28584. * Force the sprite under the pointer
  28585. * @param sprite defines the sprite to use
  28586. */
  28587. Scene.prototype.setPointerOverSprite = function (sprite) {
  28588. if (this._pointerOverSprite === sprite) {
  28589. return;
  28590. }
  28591. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  28592. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  28593. }
  28594. this._pointerOverSprite = sprite;
  28595. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  28596. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  28597. }
  28598. };
  28599. /**
  28600. * Gets the sprite under the pointer
  28601. * @returns a Sprite or null if no sprite is under the pointer
  28602. */
  28603. Scene.prototype.getPointerOverSprite = function () {
  28604. return this._pointerOverSprite;
  28605. };
  28606. // Physics
  28607. /**
  28608. * Gets the current physics engine
  28609. * @returns a PhysicsEngine or null if none attached
  28610. */
  28611. Scene.prototype.getPhysicsEngine = function () {
  28612. return this._physicsEngine;
  28613. };
  28614. /**
  28615. * Enables physics to the current scene
  28616. * @param gravity defines the scene's gravity for the physics engine
  28617. * @param plugin defines the physics engine to be used. defaults to OimoJS.
  28618. * @return a boolean indicating if the physics engine was initialized
  28619. */
  28620. Scene.prototype.enablePhysics = function (gravity, plugin) {
  28621. if (gravity === void 0) { gravity = null; }
  28622. if (this._physicsEngine) {
  28623. return true;
  28624. }
  28625. try {
  28626. this._physicsEngine = new BABYLON.PhysicsEngine(gravity, plugin);
  28627. return true;
  28628. }
  28629. catch (e) {
  28630. BABYLON.Tools.Error(e.message);
  28631. return false;
  28632. }
  28633. };
  28634. /**
  28635. * Disables and disposes the physics engine associated with the scene
  28636. */
  28637. Scene.prototype.disablePhysicsEngine = function () {
  28638. if (!this._physicsEngine) {
  28639. return;
  28640. }
  28641. this._physicsEngine.dispose();
  28642. this._physicsEngine = null;
  28643. };
  28644. /**
  28645. * Gets a boolean indicating if there is an active physics engine
  28646. * @returns a boolean indicating if there is an active physics engine
  28647. */
  28648. Scene.prototype.isPhysicsEnabled = function () {
  28649. return this._physicsEngine !== undefined;
  28650. };
  28651. /**
  28652. * Deletes a physics compound impostor
  28653. * @param compound defines the compound to delete
  28654. */
  28655. Scene.prototype.deleteCompoundImpostor = function (compound) {
  28656. var mesh = compound.parts[0].mesh;
  28657. if (mesh.physicsImpostor) {
  28658. mesh.physicsImpostor.dispose( /*true*/);
  28659. mesh.physicsImpostor = null;
  28660. }
  28661. };
  28662. // Misc.
  28663. /** @hidden */
  28664. Scene.prototype._rebuildGeometries = function () {
  28665. for (var _i = 0, _a = this._geometries; _i < _a.length; _i++) {
  28666. var geometry = _a[_i];
  28667. geometry._rebuild();
  28668. }
  28669. for (var _b = 0, _c = this.meshes; _b < _c.length; _b++) {
  28670. var mesh = _c[_b];
  28671. mesh._rebuild();
  28672. }
  28673. if (this.postProcessManager) {
  28674. this.postProcessManager._rebuild();
  28675. }
  28676. for (var _d = 0, _e = this.layers; _d < _e.length; _d++) {
  28677. var layer = _e[_d];
  28678. layer._rebuild();
  28679. }
  28680. for (var _f = 0, _g = this.effectLayers; _f < _g.length; _f++) {
  28681. var effectLayer = _g[_f];
  28682. effectLayer._rebuild();
  28683. }
  28684. if (this._boundingBoxRenderer) {
  28685. this._boundingBoxRenderer._rebuild();
  28686. }
  28687. for (var _h = 0, _j = this.particleSystems; _h < _j.length; _h++) {
  28688. var system = _j[_h];
  28689. system.rebuild();
  28690. }
  28691. if (this._postProcessRenderPipelineManager) {
  28692. this._postProcessRenderPipelineManager._rebuild();
  28693. }
  28694. };
  28695. /** @hidden */
  28696. Scene.prototype._rebuildTextures = function () {
  28697. for (var _i = 0, _a = this.textures; _i < _a.length; _i++) {
  28698. var texture = _a[_i];
  28699. texture._rebuild();
  28700. }
  28701. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  28702. };
  28703. /**
  28704. * Creates a default light for the scene.
  28705. * @param replace Whether to replace the existing lights in the scene.
  28706. */
  28707. Scene.prototype.createDefaultLight = function (replace) {
  28708. if (replace === void 0) { replace = false; }
  28709. // Dispose existing light in replace mode.
  28710. if (replace) {
  28711. if (this.lights) {
  28712. for (var i = 0; i < this.lights.length; i++) {
  28713. this.lights[i].dispose();
  28714. }
  28715. }
  28716. }
  28717. // Light
  28718. if (this.lights.length === 0) {
  28719. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  28720. }
  28721. };
  28722. /**
  28723. * Creates a default camera for the scene.
  28724. * @param createArcRotateCamera Whether to create an arc rotate or a free camera.
  28725. * @param replace Whether to replace the existing active camera in the scene.
  28726. * @param attachCameraControls Whether to attach camera controls to the canvas.
  28727. */
  28728. Scene.prototype.createDefaultCamera = function (createArcRotateCamera, replace, attachCameraControls) {
  28729. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  28730. if (replace === void 0) { replace = false; }
  28731. if (attachCameraControls === void 0) { attachCameraControls = false; }
  28732. // Dispose existing camera in replace mode.
  28733. if (replace) {
  28734. if (this.activeCamera) {
  28735. this.activeCamera.dispose();
  28736. this.activeCamera = null;
  28737. }
  28738. }
  28739. // Camera
  28740. if (!this.activeCamera) {
  28741. var worldExtends = this.getWorldExtends();
  28742. var worldSize = worldExtends.max.subtract(worldExtends.min);
  28743. var worldCenter = worldExtends.min.add(worldSize.scale(0.5));
  28744. var camera;
  28745. var radius = worldSize.length() * 1.5;
  28746. // empty scene scenario!
  28747. if (!isFinite(radius)) {
  28748. radius = 1;
  28749. worldCenter.copyFromFloats(0, 0, 0);
  28750. }
  28751. if (createArcRotateCamera) {
  28752. var arcRotateCamera = new BABYLON.ArcRotateCamera("default camera", -(Math.PI / 2), Math.PI / 2, radius, worldCenter, this);
  28753. arcRotateCamera.lowerRadiusLimit = radius * 0.01;
  28754. arcRotateCamera.wheelPrecision = 100 / radius;
  28755. camera = arcRotateCamera;
  28756. }
  28757. else {
  28758. var freeCamera = new BABYLON.FreeCamera("default camera", new BABYLON.Vector3(worldCenter.x, worldCenter.y, -radius), this);
  28759. freeCamera.setTarget(worldCenter);
  28760. camera = freeCamera;
  28761. }
  28762. camera.minZ = radius * 0.01;
  28763. camera.maxZ = radius * 1000;
  28764. camera.speed = radius * 0.2;
  28765. this.activeCamera = camera;
  28766. var canvas = this.getEngine().getRenderingCanvas();
  28767. if (attachCameraControls && canvas) {
  28768. camera.attachControl(canvas);
  28769. }
  28770. }
  28771. };
  28772. /**
  28773. * Creates a default camera and a default light
  28774. * @param createArcRotateCamera defines that the camera will be an ArcRotateCamera
  28775. * @param replace defines if the camera and/or light will replace the existing ones
  28776. * @param attachCameraControls defines if attachControl will be called on the new camera
  28777. */
  28778. Scene.prototype.createDefaultCameraOrLight = function (createArcRotateCamera, replace, attachCameraControls) {
  28779. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  28780. if (replace === void 0) { replace = false; }
  28781. if (attachCameraControls === void 0) { attachCameraControls = false; }
  28782. this.createDefaultLight(replace);
  28783. this.createDefaultCamera(createArcRotateCamera, replace, attachCameraControls);
  28784. };
  28785. /**
  28786. * Creates a new sky box
  28787. * @see http://doc.babylonjs.com/babylon101/environment#skybox
  28788. * @param environmentTexture defines the texture to use as environment texture
  28789. * @param pbr defines if PBRMaterial must be used instead of StandardMaterial
  28790. * @param scale defines the overall scale of the skybox
  28791. * @param blur defines if blurring must be applied to the environment texture (works only with pbr === true)
  28792. * @param setGlobalEnvTexture defines a boolean indicating that scene.environmentTexture must match the current skybox texture (true by default)
  28793. * @returns a new mesh holding the sky box
  28794. */
  28795. Scene.prototype.createDefaultSkybox = function (environmentTexture, pbr, scale, blur, setGlobalEnvTexture) {
  28796. if (pbr === void 0) { pbr = false; }
  28797. if (scale === void 0) { scale = 1000; }
  28798. if (blur === void 0) { blur = 0; }
  28799. if (setGlobalEnvTexture === void 0) { setGlobalEnvTexture = true; }
  28800. if (!environmentTexture) {
  28801. BABYLON.Tools.Warn("Can not create default skybox without environment texture.");
  28802. return null;
  28803. }
  28804. if (setGlobalEnvTexture) {
  28805. if (environmentTexture) {
  28806. this.environmentTexture = environmentTexture;
  28807. }
  28808. }
  28809. // Skybox
  28810. var hdrSkybox = BABYLON.Mesh.CreateBox("hdrSkyBox", scale, this);
  28811. if (pbr) {
  28812. var hdrSkyboxMaterial = new BABYLON.PBRMaterial("skyBox", this);
  28813. hdrSkyboxMaterial.backFaceCulling = false;
  28814. hdrSkyboxMaterial.reflectionTexture = environmentTexture.clone();
  28815. if (hdrSkyboxMaterial.reflectionTexture) {
  28816. hdrSkyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  28817. }
  28818. hdrSkyboxMaterial.microSurface = 1.0 - blur;
  28819. hdrSkyboxMaterial.disableLighting = true;
  28820. hdrSkyboxMaterial.twoSidedLighting = true;
  28821. hdrSkybox.infiniteDistance = true;
  28822. hdrSkybox.material = hdrSkyboxMaterial;
  28823. }
  28824. else {
  28825. var skyboxMaterial = new BABYLON.StandardMaterial("skyBox", this);
  28826. skyboxMaterial.backFaceCulling = false;
  28827. skyboxMaterial.reflectionTexture = environmentTexture.clone();
  28828. if (skyboxMaterial.reflectionTexture) {
  28829. skyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  28830. }
  28831. skyboxMaterial.disableLighting = true;
  28832. hdrSkybox.infiniteDistance = true;
  28833. hdrSkybox.material = skyboxMaterial;
  28834. }
  28835. return hdrSkybox;
  28836. };
  28837. /**
  28838. * Creates a new environment
  28839. * @see http://doc.babylonjs.com/babylon101/environment#skybox
  28840. * @param options defines the options you can use to configure the environment
  28841. * @returns the new EnvironmentHelper
  28842. */
  28843. Scene.prototype.createDefaultEnvironment = function (options) {
  28844. if (BABYLON.EnvironmentHelper) {
  28845. return new BABYLON.EnvironmentHelper(options, this);
  28846. }
  28847. return null;
  28848. };
  28849. /**
  28850. * Creates a new VREXperienceHelper
  28851. * @see http://doc.babylonjs.com/how_to/webvr_helper
  28852. * @param webVROptions defines the options used to create the new VREXperienceHelper
  28853. * @returns a new VREXperienceHelper
  28854. */
  28855. Scene.prototype.createDefaultVRExperience = function (webVROptions) {
  28856. if (webVROptions === void 0) { webVROptions = {}; }
  28857. return new BABYLON.VRExperienceHelper(this, webVROptions);
  28858. };
  28859. // Tags
  28860. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  28861. if (tagsQuery === undefined) {
  28862. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  28863. return list;
  28864. }
  28865. var listByTags = [];
  28866. forEach = forEach || (function (item) { return; });
  28867. for (var i in list) {
  28868. var item = list[i];
  28869. if (BABYLON.Tags && BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  28870. listByTags.push(item);
  28871. forEach(item);
  28872. }
  28873. }
  28874. return listByTags;
  28875. };
  28876. /**
  28877. * Get a list of meshes by tags
  28878. * @param tagsQuery defines the tags query to use
  28879. * @param forEach defines a predicate used to filter results
  28880. * @returns an array of Mesh
  28881. */
  28882. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  28883. return this._getByTags(this.meshes, tagsQuery, forEach);
  28884. };
  28885. /**
  28886. * Get a list of cameras by tags
  28887. * @param tagsQuery defines the tags query to use
  28888. * @param forEach defines a predicate used to filter results
  28889. * @returns an array of Camera
  28890. */
  28891. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  28892. return this._getByTags(this.cameras, tagsQuery, forEach);
  28893. };
  28894. /**
  28895. * Get a list of lights by tags
  28896. * @param tagsQuery defines the tags query to use
  28897. * @param forEach defines a predicate used to filter results
  28898. * @returns an array of Light
  28899. */
  28900. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  28901. return this._getByTags(this.lights, tagsQuery, forEach);
  28902. };
  28903. /**
  28904. * Get a list of materials by tags
  28905. * @param tagsQuery defines the tags query to use
  28906. * @param forEach defines a predicate used to filter results
  28907. * @returns an array of Material
  28908. */
  28909. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  28910. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  28911. };
  28912. /**
  28913. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  28914. * This allowed control for front to back rendering or reversly depending of the special needs.
  28915. *
  28916. * @param renderingGroupId The rendering group id corresponding to its index
  28917. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  28918. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  28919. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  28920. */
  28921. Scene.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  28922. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  28923. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  28924. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  28925. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  28926. };
  28927. /**
  28928. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  28929. *
  28930. * @param renderingGroupId The rendering group id corresponding to its index
  28931. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  28932. * @param depth Automatically clears depth between groups if true and autoClear is true.
  28933. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  28934. */
  28935. Scene.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  28936. if (depth === void 0) { depth = true; }
  28937. if (stencil === void 0) { stencil = true; }
  28938. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil, depth, stencil);
  28939. };
  28940. /**
  28941. * Will flag all materials as dirty to trigger new shader compilation
  28942. * @param flag defines the flag used to specify which material part must be marked as dirty
  28943. * @param predicate If not null, it will be used to specifiy if a material has to be marked as dirty
  28944. */
  28945. Scene.prototype.markAllMaterialsAsDirty = function (flag, predicate) {
  28946. for (var _i = 0, _a = this.materials; _i < _a.length; _i++) {
  28947. var material = _a[_i];
  28948. if (predicate && !predicate(material)) {
  28949. continue;
  28950. }
  28951. material.markAsDirty(flag);
  28952. }
  28953. };
  28954. /** @hidden */
  28955. Scene.prototype._loadFile = function (url, onSuccess, onProgress, useDatabase, useArrayBuffer, onError) {
  28956. var _this = this;
  28957. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, useDatabase ? this.database : undefined, useArrayBuffer, onError);
  28958. this._activeRequests.push(request);
  28959. request.onCompleteObservable.add(function (request) {
  28960. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  28961. });
  28962. return request;
  28963. };
  28964. /** @hidden */
  28965. Scene.prototype._loadFileAsync = function (url, useDatabase, useArrayBuffer) {
  28966. var _this = this;
  28967. return new Promise(function (resolve, reject) {
  28968. _this._loadFile(url, function (data) {
  28969. resolve(data);
  28970. }, undefined, useDatabase, useArrayBuffer, function (request, exception) {
  28971. reject(exception);
  28972. });
  28973. });
  28974. };
  28975. // Statics
  28976. Scene._FOGMODE_NONE = 0;
  28977. Scene._FOGMODE_EXP = 1;
  28978. Scene._FOGMODE_EXP2 = 2;
  28979. Scene._FOGMODE_LINEAR = 3;
  28980. Scene._uniqueIdCounter = 0;
  28981. /**
  28982. * Gets or sets the minimum deltatime when deterministic lock step is enabled
  28983. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  28984. */
  28985. Scene.MinDeltaTime = 1.0;
  28986. /**
  28987. * Gets or sets the maximum deltatime when deterministic lock step is enabled
  28988. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  28989. */
  28990. Scene.MaxDeltaTime = 1000.0;
  28991. /** The distance in pixel that you have to move to prevent some events */
  28992. Scene.DragMovementThreshold = 10; // in pixels
  28993. /** Time in milliseconds to wait to raise long press events if button is still pressed */
  28994. Scene.LongPressDelay = 500; // in milliseconds
  28995. /** Time in milliseconds with two consecutive clicks will be considered as a double click */
  28996. Scene.DoubleClickDelay = 300; // in milliseconds
  28997. /** If you need to check double click without raising a single click at first click, enable this flag */
  28998. Scene.ExclusiveDoubleClickMode = false;
  28999. return Scene;
  29000. }());
  29001. BABYLON.Scene = Scene;
  29002. })(BABYLON || (BABYLON = {}));
  29003. //# sourceMappingURL=babylon.scene.js.map
  29004. var BABYLON;
  29005. (function (BABYLON) {
  29006. /**
  29007. * Set of assets to keep when moving a scene into an asset container.
  29008. */
  29009. var KeepAssets = /** @class */ (function () {
  29010. function KeepAssets() {
  29011. /**
  29012. * Cameras to keep.
  29013. */
  29014. this.cameras = new Array();
  29015. /**
  29016. * Lights to keep.
  29017. */
  29018. this.lights = new Array();
  29019. /**
  29020. * Meshes to keep.
  29021. */
  29022. this.meshes = new Array();
  29023. /**
  29024. * Skeletons to keep.
  29025. */
  29026. this.skeletons = new Array();
  29027. /**
  29028. * ParticleSystems to keep.
  29029. */
  29030. this.particleSystems = new Array();
  29031. /**
  29032. * Animations to keep.
  29033. */
  29034. this.animations = new Array();
  29035. /**
  29036. * AnimationGroups to keep.
  29037. */
  29038. this.animationGroups = new Array();
  29039. /**
  29040. * MultiMaterials to keep.
  29041. */
  29042. this.multiMaterials = new Array();
  29043. /**
  29044. * Materials to keep.
  29045. */
  29046. this.materials = new Array();
  29047. /**
  29048. * MorphTargetManagers to keep.
  29049. */
  29050. this.morphTargetManagers = new Array();
  29051. /**
  29052. * Geometries to keep.
  29053. */
  29054. this.geometries = new Array();
  29055. /**
  29056. * TransformNodes to keep.
  29057. */
  29058. this.transformNodes = new Array();
  29059. /**
  29060. * LensFlareSystems to keep.
  29061. */
  29062. this.lensFlareSystems = new Array();
  29063. /**
  29064. * ShadowGenerators to keep.
  29065. */
  29066. this.shadowGenerators = new Array();
  29067. /**
  29068. * ActionManagers to keep.
  29069. */
  29070. this.actionManagers = new Array();
  29071. /**
  29072. * Sounds to keep.
  29073. */
  29074. this.sounds = new Array();
  29075. /**
  29076. * Textures to keep.
  29077. */
  29078. this.textures = new Array();
  29079. /**
  29080. * Effect layers to keep.
  29081. */
  29082. this.effectLayers = new Array();
  29083. }
  29084. return KeepAssets;
  29085. }());
  29086. BABYLON.KeepAssets = KeepAssets;
  29087. /**
  29088. * Container with a set of assets that can be added or removed from a scene.
  29089. */
  29090. var AssetContainer = /** @class */ (function () {
  29091. /**
  29092. * Instantiates an AssetContainer.
  29093. * @param scene The scene the AssetContainer belongs to.
  29094. */
  29095. function AssetContainer(scene) {
  29096. // Objects
  29097. /**
  29098. * Cameras populated in the container.
  29099. */
  29100. this.cameras = new Array();
  29101. /**
  29102. * Lights populated in the container.
  29103. */
  29104. this.lights = new Array();
  29105. /**
  29106. * Meshes populated in the container.
  29107. */
  29108. this.meshes = new Array();
  29109. /**
  29110. * Skeletons populated in the container.
  29111. */
  29112. this.skeletons = new Array();
  29113. /**
  29114. * ParticleSystems populated in the container.
  29115. */
  29116. this.particleSystems = new Array();
  29117. /**
  29118. * Animations populated in the container.
  29119. */
  29120. this.animations = new Array();
  29121. /**
  29122. * AnimationGroups populated in the container.
  29123. */
  29124. this.animationGroups = new Array();
  29125. /**
  29126. * MultiMaterials populated in the container.
  29127. */
  29128. this.multiMaterials = new Array();
  29129. /**
  29130. * Materials populated in the container.
  29131. */
  29132. this.materials = new Array();
  29133. /**
  29134. * MorphTargetManagers populated in the container.
  29135. */
  29136. this.morphTargetManagers = new Array();
  29137. /**
  29138. * Geometries populated in the container.
  29139. */
  29140. this.geometries = new Array();
  29141. /**
  29142. * TransformNodes populated in the container.
  29143. */
  29144. this.transformNodes = new Array();
  29145. /**
  29146. * LensFlareSystems populated in the container.
  29147. */
  29148. this.lensFlareSystems = new Array();
  29149. /**
  29150. * ShadowGenerators populated in the container.
  29151. */
  29152. this.shadowGenerators = new Array();
  29153. /**
  29154. * ActionManagers populated in the container.
  29155. */
  29156. this.actionManagers = new Array();
  29157. /**
  29158. * Sounds populated in the container.
  29159. */
  29160. this.sounds = new Array();
  29161. /**
  29162. * Textures populated in the container.
  29163. */
  29164. this.textures = new Array();
  29165. /**
  29166. * Effect layers populated in the container.
  29167. */
  29168. this.effectLayers = new Array();
  29169. this.scene = scene;
  29170. }
  29171. /**
  29172. * Adds all the assets from the container to the scene.
  29173. */
  29174. AssetContainer.prototype.addAllToScene = function () {
  29175. var _this = this;
  29176. this.cameras.forEach(function (o) {
  29177. _this.scene.addCamera(o);
  29178. });
  29179. this.lights.forEach(function (o) {
  29180. _this.scene.addLight(o);
  29181. });
  29182. this.meshes.forEach(function (o) {
  29183. _this.scene.addMesh(o);
  29184. });
  29185. this.skeletons.forEach(function (o) {
  29186. _this.scene.addSkeleton(o);
  29187. });
  29188. this.particleSystems.forEach(function (o) {
  29189. _this.scene.addParticleSystem(o);
  29190. });
  29191. this.animations.forEach(function (o) {
  29192. _this.scene.addAnimation(o);
  29193. });
  29194. this.animationGroups.forEach(function (o) {
  29195. _this.scene.addAnimationGroup(o);
  29196. });
  29197. this.multiMaterials.forEach(function (o) {
  29198. _this.scene.addMultiMaterial(o);
  29199. });
  29200. this.materials.forEach(function (o) {
  29201. _this.scene.addMaterial(o);
  29202. });
  29203. this.morphTargetManagers.forEach(function (o) {
  29204. _this.scene.addMorphTargetManager(o);
  29205. });
  29206. this.geometries.forEach(function (o) {
  29207. _this.scene.addGeometry(o);
  29208. });
  29209. this.transformNodes.forEach(function (o) {
  29210. _this.scene.addTransformNode(o);
  29211. });
  29212. this.lensFlareSystems.forEach(function (o) {
  29213. _this.scene.addLensFlareSystem(o);
  29214. });
  29215. this.actionManagers.forEach(function (o) {
  29216. _this.scene.addActionManager(o);
  29217. });
  29218. this.sounds.forEach(function (o) {
  29219. o.play();
  29220. o.autoplay = true;
  29221. _this.scene.mainSoundTrack.AddSound(o);
  29222. });
  29223. this.textures.forEach(function (o) {
  29224. _this.scene.addTexture(o);
  29225. });
  29226. this.effectLayers.forEach(function (o) {
  29227. _this.scene.addEffectLayer(o);
  29228. });
  29229. };
  29230. /**
  29231. * Removes all the assets in the container from the scene
  29232. */
  29233. AssetContainer.prototype.removeAllFromScene = function () {
  29234. var _this = this;
  29235. this.cameras.forEach(function (o) {
  29236. _this.scene.removeCamera(o);
  29237. });
  29238. this.lights.forEach(function (o) {
  29239. _this.scene.removeLight(o);
  29240. });
  29241. this.meshes.forEach(function (o) {
  29242. _this.scene.removeMesh(o);
  29243. });
  29244. this.skeletons.forEach(function (o) {
  29245. _this.scene.removeSkeleton(o);
  29246. });
  29247. this.particleSystems.forEach(function (o) {
  29248. _this.scene.removeParticleSystem(o);
  29249. });
  29250. this.animations.forEach(function (o) {
  29251. _this.scene.removeAnimation(o);
  29252. });
  29253. this.animationGroups.forEach(function (o) {
  29254. _this.scene.removeAnimationGroup(o);
  29255. });
  29256. this.multiMaterials.forEach(function (o) {
  29257. _this.scene.removeMultiMaterial(o);
  29258. });
  29259. this.materials.forEach(function (o) {
  29260. _this.scene.removeMaterial(o);
  29261. });
  29262. this.morphTargetManagers.forEach(function (o) {
  29263. _this.scene.removeMorphTargetManager(o);
  29264. });
  29265. this.geometries.forEach(function (o) {
  29266. _this.scene.removeGeometry(o);
  29267. });
  29268. this.transformNodes.forEach(function (o) {
  29269. _this.scene.removeTransformNode(o);
  29270. });
  29271. this.lensFlareSystems.forEach(function (o) {
  29272. _this.scene.removeLensFlareSystem(o);
  29273. });
  29274. this.actionManagers.forEach(function (o) {
  29275. _this.scene.removeActionManager(o);
  29276. });
  29277. this.sounds.forEach(function (o) {
  29278. o.stop();
  29279. o.autoplay = false;
  29280. _this.scene.mainSoundTrack.RemoveSound(o);
  29281. });
  29282. this.textures.forEach(function (o) {
  29283. _this.scene.removeTexture(o);
  29284. });
  29285. this.effectLayers.forEach(function (o) {
  29286. _this.scene.removeEffectLayer(o);
  29287. });
  29288. };
  29289. AssetContainer.prototype._moveAssets = function (sourceAssets, targetAssets, keepAssets) {
  29290. for (var _i = 0, sourceAssets_1 = sourceAssets; _i < sourceAssets_1.length; _i++) {
  29291. var asset = sourceAssets_1[_i];
  29292. var move = true;
  29293. for (var _a = 0, keepAssets_1 = keepAssets; _a < keepAssets_1.length; _a++) {
  29294. var keepAsset = keepAssets_1[_a];
  29295. if (asset === keepAsset) {
  29296. move = false;
  29297. break;
  29298. }
  29299. }
  29300. if (move) {
  29301. targetAssets.push(asset);
  29302. }
  29303. }
  29304. };
  29305. /**
  29306. * Removes all the assets contained in the scene and adds them to the container.
  29307. * @param keepAssets Set of assets to keep in the scene. (default: empty)
  29308. */
  29309. AssetContainer.prototype.moveAllFromScene = function (keepAssets) {
  29310. if (keepAssets === undefined) {
  29311. keepAssets = new KeepAssets();
  29312. }
  29313. this._moveAssets(this.scene.cameras, this.cameras, keepAssets.cameras);
  29314. this._moveAssets(this.scene.meshes, this.meshes, keepAssets.meshes);
  29315. this._moveAssets(this.scene.getGeometries(), this.geometries, keepAssets.geometries);
  29316. this._moveAssets(this.scene.materials, this.materials, keepAssets.materials);
  29317. this._moveAssets(this.scene._actionManagers, this.actionManagers, keepAssets.actionManagers);
  29318. this._moveAssets(this.scene.animations, this.animations, keepAssets.animations);
  29319. this._moveAssets(this.scene.animationGroups, this.animationGroups, keepAssets.animationGroups);
  29320. this._moveAssets(this.scene.lensFlareSystems, this.lensFlareSystems, keepAssets.lensFlareSystems);
  29321. this._moveAssets(this.scene.lights, this.lights, keepAssets.lights);
  29322. this._moveAssets(this.scene.morphTargetManagers, this.morphTargetManagers, keepAssets.morphTargetManagers);
  29323. this._moveAssets(this.scene.multiMaterials, this.multiMaterials, keepAssets.multiMaterials);
  29324. this._moveAssets(this.scene.skeletons, this.skeletons, keepAssets.skeletons);
  29325. this._moveAssets(this.scene.particleSystems, this.particleSystems, keepAssets.particleSystems);
  29326. this._moveAssets(this.scene.mainSoundTrack.soundCollection, this.sounds, keepAssets.sounds);
  29327. this._moveAssets(this.scene.transformNodes, this.transformNodes, keepAssets.transformNodes);
  29328. this._moveAssets(this.scene.textures, this.textures, keepAssets.textures);
  29329. this._moveAssets(this.scene.effectLayers, this.effectLayers, keepAssets.effectLayers);
  29330. this.removeAllFromScene();
  29331. };
  29332. /**
  29333. * 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.
  29334. * @returns the root mesh
  29335. */
  29336. AssetContainer.prototype.createRootMesh = function () {
  29337. var rootMesh = new BABYLON.Mesh("assetContainerRootMesh", this.scene);
  29338. this.meshes.forEach(function (m) {
  29339. if (!m.parent) {
  29340. rootMesh.addChild(m);
  29341. }
  29342. });
  29343. this.meshes.unshift(rootMesh);
  29344. return rootMesh;
  29345. };
  29346. return AssetContainer;
  29347. }());
  29348. BABYLON.AssetContainer = AssetContainer;
  29349. })(BABYLON || (BABYLON = {}));
  29350. //# sourceMappingURL=babylon.assetContainer.js.map
  29351. var BABYLON;
  29352. (function (BABYLON) {
  29353. var Buffer = /** @class */ (function () {
  29354. /**
  29355. * Constructor
  29356. * @param engine the engine
  29357. * @param data the data to use for this buffer
  29358. * @param updatable whether the data is updatable
  29359. * @param stride the stride (optional)
  29360. * @param postponeInternalCreation whether to postpone creating the internal WebGL buffer (optional)
  29361. * @param instanced whether the buffer is instanced (optional)
  29362. * @param useBytes set to true if the stride in in bytes (optional)
  29363. */
  29364. function Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced, useBytes) {
  29365. if (stride === void 0) { stride = 0; }
  29366. if (postponeInternalCreation === void 0) { postponeInternalCreation = false; }
  29367. if (instanced === void 0) { instanced = false; }
  29368. if (useBytes === void 0) { useBytes = false; }
  29369. if (engine instanceof BABYLON.Mesh) { // old versions of BABYLON.VertexBuffer accepted 'mesh' instead of 'engine'
  29370. this._engine = engine.getScene().getEngine();
  29371. }
  29372. else {
  29373. this._engine = engine;
  29374. }
  29375. this._updatable = updatable;
  29376. this._instanced = instanced;
  29377. this._data = data;
  29378. this.byteStride = useBytes ? stride : stride * Float32Array.BYTES_PER_ELEMENT;
  29379. if (!postponeInternalCreation) { // by default
  29380. this.create();
  29381. }
  29382. }
  29383. /**
  29384. * Create a new {BABYLON.VertexBuffer} based on the current buffer
  29385. * @param kind defines the vertex buffer kind (position, normal, etc.)
  29386. * @param offset defines offset in the buffer (0 by default)
  29387. * @param size defines the size in floats of attributes (position is 3 for instance)
  29388. * @param stride defines the stride size in floats in the buffer (the offset to apply to reach next value when data is interleaved)
  29389. * @param instanced defines if the vertex buffer contains indexed data
  29390. * @param useBytes defines if the offset and stride are in bytes
  29391. * @returns the new vertex buffer
  29392. */
  29393. Buffer.prototype.createVertexBuffer = function (kind, offset, size, stride, instanced, useBytes) {
  29394. if (useBytes === void 0) { useBytes = false; }
  29395. var byteOffset = useBytes ? offset : offset * Float32Array.BYTES_PER_ELEMENT;
  29396. var byteStride = stride ? (useBytes ? stride : stride * Float32Array.BYTES_PER_ELEMENT) : this.byteStride;
  29397. // a lot of these parameters are ignored as they are overriden by the buffer
  29398. return new BABYLON.VertexBuffer(this._engine, this, kind, this._updatable, true, byteStride, instanced === undefined ? this._instanced : instanced, byteOffset, size, undefined, undefined, true);
  29399. };
  29400. // Properties
  29401. Buffer.prototype.isUpdatable = function () {
  29402. return this._updatable;
  29403. };
  29404. Buffer.prototype.getData = function () {
  29405. return this._data;
  29406. };
  29407. Buffer.prototype.getBuffer = function () {
  29408. return this._buffer;
  29409. };
  29410. /**
  29411. * Gets the stride in float32 units (i.e. byte stride / 4).
  29412. * May not be an integer if the byte stride is not divisible by 4.
  29413. * DEPRECATED. Use byteStride instead.
  29414. * @returns the stride in float32 units
  29415. */
  29416. Buffer.prototype.getStrideSize = function () {
  29417. return this.byteStride / Float32Array.BYTES_PER_ELEMENT;
  29418. };
  29419. // Methods
  29420. Buffer.prototype.create = function (data) {
  29421. if (data === void 0) { data = null; }
  29422. if (!data && this._buffer) {
  29423. return; // nothing to do
  29424. }
  29425. data = data || this._data;
  29426. if (!data) {
  29427. return;
  29428. }
  29429. if (!this._buffer) { // create buffer
  29430. if (this._updatable) {
  29431. this._buffer = this._engine.createDynamicVertexBuffer(data);
  29432. this._data = data;
  29433. }
  29434. else {
  29435. this._buffer = this._engine.createVertexBuffer(data);
  29436. }
  29437. }
  29438. else if (this._updatable) { // update buffer
  29439. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  29440. this._data = data;
  29441. }
  29442. };
  29443. Buffer.prototype._rebuild = function () {
  29444. this._buffer = null;
  29445. this.create(this._data);
  29446. };
  29447. Buffer.prototype.update = function (data) {
  29448. this.create(data);
  29449. };
  29450. /**
  29451. * Updates the data directly.
  29452. * @param data the new data
  29453. * @param offset the new offset
  29454. * @param vertexCount the vertex count (optional)
  29455. * @param useBytes set to true if the offset is in bytes
  29456. */
  29457. Buffer.prototype.updateDirectly = function (data, offset, vertexCount, useBytes) {
  29458. if (useBytes === void 0) { useBytes = false; }
  29459. if (!this._buffer) {
  29460. return;
  29461. }
  29462. if (this._updatable) { // update buffer
  29463. this._engine.updateDynamicVertexBuffer(this._buffer, data, useBytes ? offset : offset * Float32Array.BYTES_PER_ELEMENT, (vertexCount ? vertexCount * this.byteStride : undefined));
  29464. this._data = null;
  29465. }
  29466. };
  29467. Buffer.prototype.dispose = function () {
  29468. if (!this._buffer) {
  29469. return;
  29470. }
  29471. if (this._engine._releaseBuffer(this._buffer)) {
  29472. this._buffer = null;
  29473. }
  29474. };
  29475. return Buffer;
  29476. }());
  29477. BABYLON.Buffer = Buffer;
  29478. })(BABYLON || (BABYLON = {}));
  29479. //# sourceMappingURL=babylon.buffer.js.map
  29480. var BABYLON;
  29481. (function (BABYLON) {
  29482. var VertexBuffer = /** @class */ (function () {
  29483. /**
  29484. * Constructor
  29485. * @param engine the engine
  29486. * @param data the data to use for this vertex buffer
  29487. * @param kind the vertex buffer kind
  29488. * @param updatable whether the data is updatable
  29489. * @param postponeInternalCreation whether to postpone creating the internal WebGL buffer (optional)
  29490. * @param stride the stride (optional)
  29491. * @param instanced whether the buffer is instanced (optional)
  29492. * @param offset the offset of the data (optional)
  29493. * @param size the number of components (optional)
  29494. * @param type the type of the component (optional)
  29495. * @param normalized whether the data contains normalized data (optional)
  29496. * @param useBytes set to true if stride and offset are in bytes (optional)
  29497. */
  29498. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride, instanced, offset, size, type, normalized, useBytes) {
  29499. if (normalized === void 0) { normalized = false; }
  29500. if (useBytes === void 0) { useBytes = false; }
  29501. if (data instanceof BABYLON.Buffer) {
  29502. this._buffer = data;
  29503. this._ownsBuffer = false;
  29504. }
  29505. else {
  29506. this._buffer = new BABYLON.Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced, useBytes);
  29507. this._ownsBuffer = true;
  29508. }
  29509. this._kind = kind;
  29510. if (type == undefined) {
  29511. var data_1 = this.getData();
  29512. this.type = VertexBuffer.FLOAT;
  29513. if (data_1 instanceof Int8Array)
  29514. this.type = VertexBuffer.BYTE;
  29515. else if (data_1 instanceof Uint8Array)
  29516. this.type = VertexBuffer.UNSIGNED_BYTE;
  29517. else if (data_1 instanceof Int16Array)
  29518. this.type = VertexBuffer.SHORT;
  29519. else if (data_1 instanceof Uint16Array)
  29520. this.type = VertexBuffer.UNSIGNED_SHORT;
  29521. else if (data_1 instanceof Int32Array)
  29522. this.type = VertexBuffer.INT;
  29523. else if (data_1 instanceof Uint32Array)
  29524. this.type = VertexBuffer.UNSIGNED_INT;
  29525. }
  29526. else {
  29527. this.type = type;
  29528. }
  29529. var typeByteLength = VertexBuffer.GetTypeByteLength(this.type);
  29530. if (useBytes) {
  29531. this._size = size || (stride ? (stride / typeByteLength) : VertexBuffer.DeduceStride(kind));
  29532. this.byteStride = stride || this._buffer.byteStride || (this._size * typeByteLength);
  29533. this.byteOffset = offset || 0;
  29534. }
  29535. else {
  29536. this._size = size || stride || VertexBuffer.DeduceStride(kind);
  29537. this.byteStride = stride ? (stride * typeByteLength) : (this._buffer.byteStride || (this._size * typeByteLength));
  29538. this.byteOffset = (offset || 0) * typeByteLength;
  29539. }
  29540. this.normalized = normalized;
  29541. this._instanced = instanced !== undefined ? instanced : false;
  29542. this._instanceDivisor = instanced ? 1 : 0;
  29543. }
  29544. Object.defineProperty(VertexBuffer.prototype, "instanceDivisor", {
  29545. /**
  29546. * Gets or sets the instance divisor when in instanced mode
  29547. */
  29548. get: function () {
  29549. return this._instanceDivisor;
  29550. },
  29551. set: function (value) {
  29552. this._instanceDivisor = value;
  29553. if (value == 0) {
  29554. this._instanced = false;
  29555. }
  29556. else {
  29557. this._instanced = true;
  29558. }
  29559. },
  29560. enumerable: true,
  29561. configurable: true
  29562. });
  29563. VertexBuffer.prototype._rebuild = function () {
  29564. if (!this._buffer) {
  29565. return;
  29566. }
  29567. this._buffer._rebuild();
  29568. };
  29569. /**
  29570. * Returns the kind of the VertexBuffer (string).
  29571. */
  29572. VertexBuffer.prototype.getKind = function () {
  29573. return this._kind;
  29574. };
  29575. // Properties
  29576. /**
  29577. * Boolean : is the VertexBuffer updatable ?
  29578. */
  29579. VertexBuffer.prototype.isUpdatable = function () {
  29580. return this._buffer.isUpdatable();
  29581. };
  29582. /**
  29583. * Returns an array of numbers or a typed array containing the VertexBuffer data.
  29584. */
  29585. VertexBuffer.prototype.getData = function () {
  29586. return this._buffer.getData();
  29587. };
  29588. /**
  29589. * Returns the WebGLBuffer associated to the VertexBuffer.
  29590. */
  29591. VertexBuffer.prototype.getBuffer = function () {
  29592. return this._buffer.getBuffer();
  29593. };
  29594. /**
  29595. * Returns the stride as a multiple of the type byte length.
  29596. * DEPRECATED. Use byteStride instead.
  29597. */
  29598. VertexBuffer.prototype.getStrideSize = function () {
  29599. return this.byteStride / VertexBuffer.GetTypeByteLength(this.type);
  29600. };
  29601. /**
  29602. * Returns the offset as a multiple of the type byte length.
  29603. * DEPRECATED. Use byteOffset instead.
  29604. */
  29605. VertexBuffer.prototype.getOffset = function () {
  29606. return this.byteOffset / VertexBuffer.GetTypeByteLength(this.type);
  29607. };
  29608. /**
  29609. * Returns the number of components per vertex attribute (integer).
  29610. */
  29611. VertexBuffer.prototype.getSize = function () {
  29612. return this._size;
  29613. };
  29614. /**
  29615. * Boolean : is the WebGLBuffer of the VertexBuffer instanced now ?
  29616. */
  29617. VertexBuffer.prototype.getIsInstanced = function () {
  29618. return this._instanced;
  29619. };
  29620. /**
  29621. * Returns the instancing divisor, zero for non-instanced (integer).
  29622. */
  29623. VertexBuffer.prototype.getInstanceDivisor = function () {
  29624. return this._instanceDivisor;
  29625. };
  29626. // Methods
  29627. /**
  29628. * Creates the underlying WebGLBuffer from the passed numeric array or Float32Array.
  29629. * Returns the created WebGLBuffer.
  29630. */
  29631. VertexBuffer.prototype.create = function (data) {
  29632. return this._buffer.create(data);
  29633. };
  29634. /**
  29635. * Updates the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  29636. * This function will create a new buffer if the current one is not updatable
  29637. * Returns the updated WebGLBuffer.
  29638. */
  29639. VertexBuffer.prototype.update = function (data) {
  29640. return this._buffer.update(data);
  29641. };
  29642. /**
  29643. * Updates directly the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  29644. * Returns the directly updated WebGLBuffer.
  29645. * @param data the new data
  29646. * @param offset the new offset
  29647. * @param useBytes set to true if the offset is in bytes
  29648. */
  29649. VertexBuffer.prototype.updateDirectly = function (data, offset, useBytes) {
  29650. if (useBytes === void 0) { useBytes = false; }
  29651. this._buffer.updateDirectly(data, offset, undefined, useBytes);
  29652. };
  29653. /**
  29654. * Disposes the VertexBuffer and the underlying WebGLBuffer.
  29655. */
  29656. VertexBuffer.prototype.dispose = function () {
  29657. if (this._ownsBuffer) {
  29658. this._buffer.dispose();
  29659. }
  29660. };
  29661. /**
  29662. * Enumerates each value of this vertex buffer as numbers.
  29663. * @param count the number of values to enumerate
  29664. * @param callback the callback function called for each value
  29665. */
  29666. VertexBuffer.prototype.forEach = function (count, callback) {
  29667. VertexBuffer.ForEach(this._buffer.getData(), this.byteOffset, this.byteStride, this._size, this.type, count, this.normalized, callback);
  29668. };
  29669. Object.defineProperty(VertexBuffer, "PositionKind", {
  29670. get: function () {
  29671. return VertexBuffer._PositionKind;
  29672. },
  29673. enumerable: true,
  29674. configurable: true
  29675. });
  29676. Object.defineProperty(VertexBuffer, "NormalKind", {
  29677. get: function () {
  29678. return VertexBuffer._NormalKind;
  29679. },
  29680. enumerable: true,
  29681. configurable: true
  29682. });
  29683. Object.defineProperty(VertexBuffer, "TangentKind", {
  29684. get: function () {
  29685. return VertexBuffer._TangentKind;
  29686. },
  29687. enumerable: true,
  29688. configurable: true
  29689. });
  29690. Object.defineProperty(VertexBuffer, "UVKind", {
  29691. get: function () {
  29692. return VertexBuffer._UVKind;
  29693. },
  29694. enumerable: true,
  29695. configurable: true
  29696. });
  29697. Object.defineProperty(VertexBuffer, "UV2Kind", {
  29698. get: function () {
  29699. return VertexBuffer._UV2Kind;
  29700. },
  29701. enumerable: true,
  29702. configurable: true
  29703. });
  29704. Object.defineProperty(VertexBuffer, "UV3Kind", {
  29705. get: function () {
  29706. return VertexBuffer._UV3Kind;
  29707. },
  29708. enumerable: true,
  29709. configurable: true
  29710. });
  29711. Object.defineProperty(VertexBuffer, "UV4Kind", {
  29712. get: function () {
  29713. return VertexBuffer._UV4Kind;
  29714. },
  29715. enumerable: true,
  29716. configurable: true
  29717. });
  29718. Object.defineProperty(VertexBuffer, "UV5Kind", {
  29719. get: function () {
  29720. return VertexBuffer._UV5Kind;
  29721. },
  29722. enumerable: true,
  29723. configurable: true
  29724. });
  29725. Object.defineProperty(VertexBuffer, "UV6Kind", {
  29726. get: function () {
  29727. return VertexBuffer._UV6Kind;
  29728. },
  29729. enumerable: true,
  29730. configurable: true
  29731. });
  29732. Object.defineProperty(VertexBuffer, "ColorKind", {
  29733. get: function () {
  29734. return VertexBuffer._ColorKind;
  29735. },
  29736. enumerable: true,
  29737. configurable: true
  29738. });
  29739. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  29740. get: function () {
  29741. return VertexBuffer._MatricesIndicesKind;
  29742. },
  29743. enumerable: true,
  29744. configurable: true
  29745. });
  29746. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  29747. get: function () {
  29748. return VertexBuffer._MatricesWeightsKind;
  29749. },
  29750. enumerable: true,
  29751. configurable: true
  29752. });
  29753. Object.defineProperty(VertexBuffer, "MatricesIndicesExtraKind", {
  29754. get: function () {
  29755. return VertexBuffer._MatricesIndicesExtraKind;
  29756. },
  29757. enumerable: true,
  29758. configurable: true
  29759. });
  29760. Object.defineProperty(VertexBuffer, "MatricesWeightsExtraKind", {
  29761. get: function () {
  29762. return VertexBuffer._MatricesWeightsExtraKind;
  29763. },
  29764. enumerable: true,
  29765. configurable: true
  29766. });
  29767. /**
  29768. * Deduces the stride given a kind.
  29769. * @param kind The kind string to deduce
  29770. * @returns The deduced stride
  29771. */
  29772. VertexBuffer.DeduceStride = function (kind) {
  29773. switch (kind) {
  29774. case VertexBuffer.UVKind:
  29775. case VertexBuffer.UV2Kind:
  29776. case VertexBuffer.UV3Kind:
  29777. case VertexBuffer.UV4Kind:
  29778. case VertexBuffer.UV5Kind:
  29779. case VertexBuffer.UV6Kind:
  29780. return 2;
  29781. case VertexBuffer.NormalKind:
  29782. case VertexBuffer.PositionKind:
  29783. return 3;
  29784. case VertexBuffer.ColorKind:
  29785. case VertexBuffer.MatricesIndicesKind:
  29786. case VertexBuffer.MatricesIndicesExtraKind:
  29787. case VertexBuffer.MatricesWeightsKind:
  29788. case VertexBuffer.MatricesWeightsExtraKind:
  29789. case VertexBuffer.TangentKind:
  29790. return 4;
  29791. default:
  29792. throw new Error("Invalid kind '" + kind + "'");
  29793. }
  29794. };
  29795. /**
  29796. * Gets the byte length of the given type.
  29797. * @param type the type
  29798. * @returns the number of bytes
  29799. */
  29800. VertexBuffer.GetTypeByteLength = function (type) {
  29801. switch (type) {
  29802. case VertexBuffer.BYTE:
  29803. case VertexBuffer.UNSIGNED_BYTE:
  29804. return 1;
  29805. case VertexBuffer.SHORT:
  29806. case VertexBuffer.UNSIGNED_SHORT:
  29807. return 2;
  29808. case VertexBuffer.INT:
  29809. case VertexBuffer.FLOAT:
  29810. return 4;
  29811. default:
  29812. throw new Error("Invalid type '" + type + "'");
  29813. }
  29814. };
  29815. /**
  29816. * Enumerates each value of the given parameters as numbers.
  29817. * @param data the data to enumerate
  29818. * @param byteOffset the byte offset of the data
  29819. * @param byteStride the byte stride of the data
  29820. * @param componentCount the number of components per element
  29821. * @param componentType the type of the component
  29822. * @param count the total number of components
  29823. * @param normalized whether the data is normalized
  29824. * @param callback the callback function called for each value
  29825. */
  29826. VertexBuffer.ForEach = function (data, byteOffset, byteStride, componentCount, componentType, count, normalized, callback) {
  29827. if (data instanceof Array) {
  29828. var offset = byteOffset / 4;
  29829. var stride = byteStride / 4;
  29830. for (var index = 0; index < count; index += componentCount) {
  29831. for (var componentIndex = 0; componentIndex < componentCount; componentIndex++) {
  29832. callback(data[offset + componentIndex], index + componentIndex);
  29833. }
  29834. offset += stride;
  29835. }
  29836. }
  29837. else {
  29838. var dataView = data instanceof ArrayBuffer ? new DataView(data) : new DataView(data.buffer, data.byteOffset, data.byteLength);
  29839. var componentByteLength = VertexBuffer.GetTypeByteLength(componentType);
  29840. for (var index = 0; index < count; index += componentCount) {
  29841. var componentByteOffset = byteOffset;
  29842. for (var componentIndex = 0; componentIndex < componentCount; componentIndex++) {
  29843. var value = VertexBuffer._GetFloatValue(dataView, componentType, componentByteOffset, normalized);
  29844. callback(value, index + componentIndex);
  29845. componentByteOffset += componentByteLength;
  29846. }
  29847. byteOffset += byteStride;
  29848. }
  29849. }
  29850. };
  29851. VertexBuffer._GetFloatValue = function (dataView, type, byteOffset, normalized) {
  29852. switch (type) {
  29853. case VertexBuffer.BYTE: {
  29854. var value = dataView.getInt8(byteOffset);
  29855. if (normalized) {
  29856. value = Math.max(value / 127, -1);
  29857. }
  29858. return value;
  29859. }
  29860. case VertexBuffer.UNSIGNED_BYTE: {
  29861. var value = dataView.getUint8(byteOffset);
  29862. if (normalized) {
  29863. value = value / 255;
  29864. }
  29865. return value;
  29866. }
  29867. case VertexBuffer.SHORT: {
  29868. var value = dataView.getInt16(byteOffset, true);
  29869. if (normalized) {
  29870. value = Math.max(value / 16383, -1);
  29871. }
  29872. return value;
  29873. }
  29874. case VertexBuffer.UNSIGNED_SHORT: {
  29875. var value = dataView.getUint16(byteOffset, true);
  29876. if (normalized) {
  29877. value = value / 65535;
  29878. }
  29879. return value;
  29880. }
  29881. case VertexBuffer.FLOAT: {
  29882. return dataView.getFloat32(byteOffset, true);
  29883. }
  29884. default: {
  29885. throw new Error("Invalid component type " + type);
  29886. }
  29887. }
  29888. };
  29889. /**
  29890. * The byte type.
  29891. */
  29892. VertexBuffer.BYTE = 5120;
  29893. /**
  29894. * The unsigned byte type.
  29895. */
  29896. VertexBuffer.UNSIGNED_BYTE = 5121;
  29897. /**
  29898. * The short type.
  29899. */
  29900. VertexBuffer.SHORT = 5122;
  29901. /**
  29902. * The unsigned short type.
  29903. */
  29904. VertexBuffer.UNSIGNED_SHORT = 5123;
  29905. /**
  29906. * The integer type.
  29907. */
  29908. VertexBuffer.INT = 5124;
  29909. /**
  29910. * The unsigned integer type.
  29911. */
  29912. VertexBuffer.UNSIGNED_INT = 5125;
  29913. /**
  29914. * The float type.
  29915. */
  29916. VertexBuffer.FLOAT = 5126;
  29917. // Enums
  29918. VertexBuffer._PositionKind = "position";
  29919. VertexBuffer._NormalKind = "normal";
  29920. VertexBuffer._TangentKind = "tangent";
  29921. VertexBuffer._UVKind = "uv";
  29922. VertexBuffer._UV2Kind = "uv2";
  29923. VertexBuffer._UV3Kind = "uv3";
  29924. VertexBuffer._UV4Kind = "uv4";
  29925. VertexBuffer._UV5Kind = "uv5";
  29926. VertexBuffer._UV6Kind = "uv6";
  29927. VertexBuffer._ColorKind = "color";
  29928. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  29929. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  29930. VertexBuffer._MatricesIndicesExtraKind = "matricesIndicesExtra";
  29931. VertexBuffer._MatricesWeightsExtraKind = "matricesWeightsExtra";
  29932. return VertexBuffer;
  29933. }());
  29934. BABYLON.VertexBuffer = VertexBuffer;
  29935. })(BABYLON || (BABYLON = {}));
  29936. //# sourceMappingURL=babylon.vertexBuffer.js.map
  29937. var BABYLON;
  29938. (function (BABYLON) {
  29939. /**
  29940. * Internal class used by the engine to get list of {BABYLON.InternalTexture} already bound to the GL context
  29941. */
  29942. var DummyInternalTextureTracker = /** @class */ (function () {
  29943. function DummyInternalTextureTracker() {
  29944. /**
  29945. * Gets or set the previous tracker in the list
  29946. */
  29947. this.previous = null;
  29948. /**
  29949. * Gets or set the next tracker in the list
  29950. */
  29951. this.next = null;
  29952. }
  29953. return DummyInternalTextureTracker;
  29954. }());
  29955. BABYLON.DummyInternalTextureTracker = DummyInternalTextureTracker;
  29956. })(BABYLON || (BABYLON = {}));
  29957. //# sourceMappingURL=babylon.internalTextureTracker.js.map
  29958. var BABYLON;
  29959. (function (BABYLON) {
  29960. /**
  29961. * Class used to store data associated with WebGL texture data for the engine
  29962. * This class should not be used directly
  29963. */
  29964. var InternalTexture = /** @class */ (function () {
  29965. /**
  29966. * Creates a new InternalTexture
  29967. * @param engine defines the engine to use
  29968. * @param dataSource defines the type of data that will be used
  29969. */
  29970. function InternalTexture(engine, dataSource) {
  29971. /**
  29972. * Observable called when the texture is loaded
  29973. */
  29974. this.onLoadedObservable = new BABYLON.Observable();
  29975. /**
  29976. * Gets or set the previous tracker in the list
  29977. */
  29978. this.previous = null;
  29979. /**
  29980. * Gets or set the next tracker in the list
  29981. */
  29982. this.next = null;
  29983. // Private
  29984. /** @hidden */
  29985. this._initialSlot = -1;
  29986. /** @hidden */
  29987. this._designatedSlot = -1;
  29988. /** @hidden */
  29989. this._dataSource = InternalTexture.DATASOURCE_UNKNOWN;
  29990. /** @hidden */
  29991. this._comparisonFunction = 0;
  29992. /** @hidden */
  29993. this._references = 1;
  29994. this._engine = engine;
  29995. this._dataSource = dataSource;
  29996. this._webGLTexture = engine._createTexture();
  29997. }
  29998. Object.defineProperty(InternalTexture.prototype, "dataSource", {
  29999. /**
  30000. * Gets the data source type of the texture (can be one of the BABYLON.InternalTexture.DATASOURCE_XXXX)
  30001. */
  30002. get: function () {
  30003. return this._dataSource;
  30004. },
  30005. enumerable: true,
  30006. configurable: true
  30007. });
  30008. /**
  30009. * Increments the number of references (ie. the number of {BABYLON.Texture} that point to it)
  30010. */
  30011. InternalTexture.prototype.incrementReferences = function () {
  30012. this._references++;
  30013. };
  30014. /**
  30015. * Change the size of the texture (not the size of the content)
  30016. * @param width defines the new width
  30017. * @param height defines the new height
  30018. * @param depth defines the new depth (1 by default)
  30019. */
  30020. InternalTexture.prototype.updateSize = function (width, height, depth) {
  30021. if (depth === void 0) { depth = 1; }
  30022. this.width = width;
  30023. this.height = height;
  30024. this.depth = depth;
  30025. this.baseWidth = width;
  30026. this.baseHeight = height;
  30027. this.baseDepth = depth;
  30028. this._size = width * height * depth;
  30029. };
  30030. /** @hidden */
  30031. InternalTexture.prototype._rebuild = function () {
  30032. var _this = this;
  30033. var proxy;
  30034. this.isReady = false;
  30035. this._cachedCoordinatesMode = null;
  30036. this._cachedWrapU = null;
  30037. this._cachedWrapV = null;
  30038. this._cachedAnisotropicFilteringLevel = null;
  30039. switch (this._dataSource) {
  30040. case InternalTexture.DATASOURCE_TEMP:
  30041. return;
  30042. case InternalTexture.DATASOURCE_URL:
  30043. proxy = this._engine.createTexture(this.url, !this.generateMipMaps, this.invertY, null, this.samplingMode, function () {
  30044. _this.isReady = true;
  30045. }, null, this._buffer, undefined, this.format);
  30046. proxy._swapAndDie(this);
  30047. return;
  30048. case InternalTexture.DATASOURCE_RAW:
  30049. proxy = this._engine.createRawTexture(this._bufferView, this.baseWidth, this.baseHeight, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  30050. proxy._swapAndDie(this);
  30051. this.isReady = true;
  30052. return;
  30053. case InternalTexture.DATASOURCE_RAW3D:
  30054. proxy = this._engine.createRawTexture3D(this._bufferView, this.baseWidth, this.baseHeight, this.baseDepth, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  30055. proxy._swapAndDie(this);
  30056. this.isReady = true;
  30057. return;
  30058. case InternalTexture.DATASOURCE_DYNAMIC:
  30059. proxy = this._engine.createDynamicTexture(this.baseWidth, this.baseHeight, this.generateMipMaps, this.samplingMode);
  30060. proxy._swapAndDie(this);
  30061. // The engine will make sure to update content so no need to flag it as isReady = true
  30062. return;
  30063. case InternalTexture.DATASOURCE_RENDERTARGET:
  30064. var options = new BABYLON.RenderTargetCreationOptions();
  30065. options.generateDepthBuffer = this._generateDepthBuffer;
  30066. options.generateMipMaps = this.generateMipMaps;
  30067. options.generateStencilBuffer = this._generateStencilBuffer;
  30068. options.samplingMode = this.samplingMode;
  30069. options.type = this.type;
  30070. if (this.isCube) {
  30071. proxy = this._engine.createRenderTargetCubeTexture(this.width, options);
  30072. }
  30073. else {
  30074. var size = {
  30075. width: this.width,
  30076. height: this.height
  30077. };
  30078. proxy = this._engine.createRenderTargetTexture(size, options);
  30079. }
  30080. proxy._swapAndDie(this);
  30081. this.isReady = true;
  30082. return;
  30083. case InternalTexture.DATASOURCE_DEPTHTEXTURE:
  30084. var depthTextureOptions = {
  30085. bilinearFiltering: this.samplingMode !== BABYLON.Texture.BILINEAR_SAMPLINGMODE,
  30086. comparisonFunction: this._comparisonFunction,
  30087. generateStencil: this._generateStencilBuffer,
  30088. isCube: this.isCube
  30089. };
  30090. proxy = this._engine.createDepthStencilTexture({ width: this.width, height: this.height }, depthTextureOptions);
  30091. proxy._swapAndDie(this);
  30092. this.isReady = true;
  30093. return;
  30094. case InternalTexture.DATASOURCE_CUBE:
  30095. proxy = this._engine.createCubeTexture(this.url, null, this._files, !this.generateMipMaps, function () {
  30096. _this.isReady = true;
  30097. }, null, this.format, this._extension);
  30098. proxy._swapAndDie(this);
  30099. return;
  30100. case InternalTexture.DATASOURCE_CUBERAW:
  30101. proxy = this._engine.createRawCubeTexture(this._bufferViewArray, this.width, this.format, this.type, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  30102. proxy._swapAndDie(this);
  30103. this.isReady = true;
  30104. return;
  30105. case InternalTexture.DATASOURCE_CUBEPREFILTERED:
  30106. proxy = this._engine.createPrefilteredCubeTexture(this.url, null, this._lodGenerationScale, this._lodGenerationOffset, function (proxy) {
  30107. if (proxy) {
  30108. proxy._swapAndDie(_this);
  30109. }
  30110. _this.isReady = true;
  30111. }, null, this.format, this._extension);
  30112. proxy._sphericalPolynomial = this._sphericalPolynomial;
  30113. return;
  30114. }
  30115. };
  30116. InternalTexture.prototype._swapAndDie = function (target) {
  30117. target._webGLTexture = this._webGLTexture;
  30118. if (this._framebuffer) {
  30119. target._framebuffer = this._framebuffer;
  30120. }
  30121. if (this._depthStencilBuffer) {
  30122. target._depthStencilBuffer = this._depthStencilBuffer;
  30123. }
  30124. if (this._lodTextureHigh) {
  30125. if (target._lodTextureHigh) {
  30126. target._lodTextureHigh.dispose();
  30127. }
  30128. target._lodTextureHigh = this._lodTextureHigh;
  30129. }
  30130. if (this._lodTextureMid) {
  30131. if (target._lodTextureMid) {
  30132. target._lodTextureMid.dispose();
  30133. }
  30134. target._lodTextureMid = this._lodTextureMid;
  30135. }
  30136. if (this._lodTextureLow) {
  30137. if (target._lodTextureLow) {
  30138. target._lodTextureLow.dispose();
  30139. }
  30140. target._lodTextureLow = this._lodTextureLow;
  30141. }
  30142. var cache = this._engine.getLoadedTexturesCache();
  30143. var index = cache.indexOf(this);
  30144. if (index !== -1) {
  30145. cache.splice(index, 1);
  30146. }
  30147. };
  30148. /**
  30149. * Dispose the current allocated resources
  30150. */
  30151. InternalTexture.prototype.dispose = function () {
  30152. if (!this._webGLTexture) {
  30153. return;
  30154. }
  30155. this._references--;
  30156. if (this._references === 0) {
  30157. this._engine._releaseTexture(this);
  30158. this._webGLTexture = null;
  30159. this.previous = null;
  30160. this.next = null;
  30161. }
  30162. };
  30163. /**
  30164. * The source of the texture data is unknown
  30165. */
  30166. InternalTexture.DATASOURCE_UNKNOWN = 0;
  30167. /**
  30168. * Texture data comes from an URL
  30169. */
  30170. InternalTexture.DATASOURCE_URL = 1;
  30171. /**
  30172. * Texture data is only used for temporary storage
  30173. */
  30174. InternalTexture.DATASOURCE_TEMP = 2;
  30175. /**
  30176. * Texture data comes from raw data (ArrayBuffer)
  30177. */
  30178. InternalTexture.DATASOURCE_RAW = 3;
  30179. /**
  30180. * Texture content is dynamic (video or dynamic texture)
  30181. */
  30182. InternalTexture.DATASOURCE_DYNAMIC = 4;
  30183. /**
  30184. * Texture content is generated by rendering to it
  30185. */
  30186. InternalTexture.DATASOURCE_RENDERTARGET = 5;
  30187. /**
  30188. * Texture content is part of a multi render target process
  30189. */
  30190. InternalTexture.DATASOURCE_MULTIRENDERTARGET = 6;
  30191. /**
  30192. * Texture data comes from a cube data file
  30193. */
  30194. InternalTexture.DATASOURCE_CUBE = 7;
  30195. /**
  30196. * Texture data comes from a raw cube data
  30197. */
  30198. InternalTexture.DATASOURCE_CUBERAW = 8;
  30199. /**
  30200. * Texture data come from a prefiltered cube data file
  30201. */
  30202. InternalTexture.DATASOURCE_CUBEPREFILTERED = 9;
  30203. /**
  30204. * Texture content is raw 3D data
  30205. */
  30206. InternalTexture.DATASOURCE_RAW3D = 10;
  30207. /**
  30208. * Texture content is a depth texture
  30209. */
  30210. InternalTexture.DATASOURCE_DEPTHTEXTURE = 11;
  30211. return InternalTexture;
  30212. }());
  30213. BABYLON.InternalTexture = InternalTexture;
  30214. })(BABYLON || (BABYLON = {}));
  30215. //# sourceMappingURL=babylon.internalTexture.js.map
  30216. var BABYLON;
  30217. (function (BABYLON) {
  30218. var BaseTexture = /** @class */ (function () {
  30219. function BaseTexture(scene) {
  30220. this._hasAlpha = false;
  30221. this.getAlphaFromRGB = false;
  30222. this.level = 1;
  30223. this.coordinatesIndex = 0;
  30224. this._coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  30225. /**
  30226. * | Value | Type | Description |
  30227. * | ----- | ------------------ | ----------- |
  30228. * | 0 | CLAMP_ADDRESSMODE | |
  30229. * | 1 | WRAP_ADDRESSMODE | |
  30230. * | 2 | MIRROR_ADDRESSMODE | |
  30231. */
  30232. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  30233. /**
  30234. * | Value | Type | Description |
  30235. * | ----- | ------------------ | ----------- |
  30236. * | 0 | CLAMP_ADDRESSMODE | |
  30237. * | 1 | WRAP_ADDRESSMODE | |
  30238. * | 2 | MIRROR_ADDRESSMODE | |
  30239. */
  30240. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  30241. /**
  30242. * | Value | Type | Description |
  30243. * | ----- | ------------------ | ----------- |
  30244. * | 0 | CLAMP_ADDRESSMODE | |
  30245. * | 1 | WRAP_ADDRESSMODE | |
  30246. * | 2 | MIRROR_ADDRESSMODE | |
  30247. */
  30248. this.wrapR = BABYLON.Texture.WRAP_ADDRESSMODE;
  30249. this.anisotropicFilteringLevel = BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL;
  30250. this.isCube = false;
  30251. this.is3D = false;
  30252. this.gammaSpace = true;
  30253. this.invertZ = false;
  30254. this.lodLevelInAlpha = false;
  30255. this.lodGenerationOffset = 0.0;
  30256. this.lodGenerationScale = 0.8;
  30257. this.isRenderTarget = false;
  30258. this.animations = new Array();
  30259. /**
  30260. * An event triggered when the texture is disposed.
  30261. */
  30262. this.onDisposeObservable = new BABYLON.Observable();
  30263. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  30264. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  30265. if (this._scene) {
  30266. this._scene.textures.push(this);
  30267. }
  30268. this._uid = null;
  30269. }
  30270. Object.defineProperty(BaseTexture.prototype, "hasAlpha", {
  30271. get: function () {
  30272. return this._hasAlpha;
  30273. },
  30274. set: function (value) {
  30275. if (this._hasAlpha === value) {
  30276. return;
  30277. }
  30278. this._hasAlpha = value;
  30279. if (this._scene) {
  30280. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  30281. }
  30282. },
  30283. enumerable: true,
  30284. configurable: true
  30285. });
  30286. Object.defineProperty(BaseTexture.prototype, "coordinatesMode", {
  30287. get: function () {
  30288. return this._coordinatesMode;
  30289. },
  30290. /**
  30291. * How a texture is mapped.
  30292. *
  30293. * | Value | Type | Description |
  30294. * | ----- | ----------------------------------- | ----------- |
  30295. * | 0 | EXPLICIT_MODE | |
  30296. * | 1 | SPHERICAL_MODE | |
  30297. * | 2 | PLANAR_MODE | |
  30298. * | 3 | CUBIC_MODE | |
  30299. * | 4 | PROJECTION_MODE | |
  30300. * | 5 | SKYBOX_MODE | |
  30301. * | 6 | INVCUBIC_MODE | |
  30302. * | 7 | EQUIRECTANGULAR_MODE | |
  30303. * | 8 | FIXED_EQUIRECTANGULAR_MODE | |
  30304. * | 9 | FIXED_EQUIRECTANGULAR_MIRRORED_MODE | |
  30305. */
  30306. set: function (value) {
  30307. if (this._coordinatesMode === value) {
  30308. return;
  30309. }
  30310. this._coordinatesMode = value;
  30311. if (this._scene) {
  30312. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  30313. }
  30314. },
  30315. enumerable: true,
  30316. configurable: true
  30317. });
  30318. Object.defineProperty(BaseTexture.prototype, "uid", {
  30319. get: function () {
  30320. if (!this._uid) {
  30321. this._uid = BABYLON.Tools.RandomId();
  30322. }
  30323. return this._uid;
  30324. },
  30325. enumerable: true,
  30326. configurable: true
  30327. });
  30328. BaseTexture.prototype.toString = function () {
  30329. return this.name;
  30330. };
  30331. BaseTexture.prototype.getClassName = function () {
  30332. return "BaseTexture";
  30333. };
  30334. Object.defineProperty(BaseTexture.prototype, "onDispose", {
  30335. set: function (callback) {
  30336. if (this._onDisposeObserver) {
  30337. this.onDisposeObservable.remove(this._onDisposeObserver);
  30338. }
  30339. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  30340. },
  30341. enumerable: true,
  30342. configurable: true
  30343. });
  30344. Object.defineProperty(BaseTexture.prototype, "isBlocking", {
  30345. get: function () {
  30346. return true;
  30347. },
  30348. enumerable: true,
  30349. configurable: true
  30350. });
  30351. BaseTexture.prototype.getScene = function () {
  30352. return this._scene;
  30353. };
  30354. BaseTexture.prototype.getTextureMatrix = function () {
  30355. return BABYLON.Matrix.IdentityReadOnly;
  30356. };
  30357. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  30358. return BABYLON.Matrix.IdentityReadOnly;
  30359. };
  30360. BaseTexture.prototype.getInternalTexture = function () {
  30361. return this._texture;
  30362. };
  30363. BaseTexture.prototype.isReadyOrNotBlocking = function () {
  30364. return !this.isBlocking || this.isReady();
  30365. };
  30366. BaseTexture.prototype.isReady = function () {
  30367. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  30368. this.delayLoad();
  30369. return false;
  30370. }
  30371. if (this._texture) {
  30372. return this._texture.isReady;
  30373. }
  30374. return false;
  30375. };
  30376. BaseTexture.prototype.getSize = function () {
  30377. if (this._texture && this._texture.width) {
  30378. return new BABYLON.Size(this._texture.width, this._texture.height);
  30379. }
  30380. if (this._texture && this._texture._size) {
  30381. return new BABYLON.Size(this._texture._size, this._texture._size);
  30382. }
  30383. return BABYLON.Size.Zero();
  30384. };
  30385. BaseTexture.prototype.getBaseSize = function () {
  30386. if (!this.isReady() || !this._texture)
  30387. return BABYLON.Size.Zero();
  30388. if (this._texture._size) {
  30389. return new BABYLON.Size(this._texture._size, this._texture._size);
  30390. }
  30391. return new BABYLON.Size(this._texture.baseWidth, this._texture.baseHeight);
  30392. };
  30393. BaseTexture.prototype.scale = function (ratio) {
  30394. };
  30395. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  30396. get: function () {
  30397. return false;
  30398. },
  30399. enumerable: true,
  30400. configurable: true
  30401. });
  30402. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  30403. if (!this._scene) {
  30404. return null;
  30405. }
  30406. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  30407. for (var index = 0; index < texturesCache.length; index++) {
  30408. var texturesCacheEntry = texturesCache[index];
  30409. if (texturesCacheEntry.url === url && texturesCacheEntry.generateMipMaps === !noMipmap) {
  30410. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  30411. texturesCacheEntry.incrementReferences();
  30412. return texturesCacheEntry;
  30413. }
  30414. }
  30415. }
  30416. return null;
  30417. };
  30418. BaseTexture.prototype._rebuild = function () {
  30419. };
  30420. BaseTexture.prototype.delayLoad = function () {
  30421. };
  30422. BaseTexture.prototype.clone = function () {
  30423. return null;
  30424. };
  30425. Object.defineProperty(BaseTexture.prototype, "textureType", {
  30426. get: function () {
  30427. if (!this._texture) {
  30428. return BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  30429. }
  30430. return (this._texture.type !== undefined) ? this._texture.type : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  30431. },
  30432. enumerable: true,
  30433. configurable: true
  30434. });
  30435. Object.defineProperty(BaseTexture.prototype, "textureFormat", {
  30436. get: function () {
  30437. if (!this._texture) {
  30438. return BABYLON.Engine.TEXTUREFORMAT_RGBA;
  30439. }
  30440. return (this._texture.format !== undefined) ? this._texture.format : BABYLON.Engine.TEXTUREFORMAT_RGBA;
  30441. },
  30442. enumerable: true,
  30443. configurable: true
  30444. });
  30445. BaseTexture.prototype.readPixels = function (faceIndex) {
  30446. if (faceIndex === void 0) { faceIndex = 0; }
  30447. if (!this._texture) {
  30448. return null;
  30449. }
  30450. var size = this.getSize();
  30451. var scene = this.getScene();
  30452. if (!scene) {
  30453. return null;
  30454. }
  30455. var engine = scene.getEngine();
  30456. if (this._texture.isCube) {
  30457. return engine._readTexturePixels(this._texture, size.width, size.height, faceIndex);
  30458. }
  30459. return engine._readTexturePixels(this._texture, size.width, size.height, -1);
  30460. };
  30461. BaseTexture.prototype.releaseInternalTexture = function () {
  30462. if (this._texture) {
  30463. this._texture.dispose();
  30464. this._texture = null;
  30465. }
  30466. };
  30467. Object.defineProperty(BaseTexture.prototype, "sphericalPolynomial", {
  30468. get: function () {
  30469. if (!this._texture || !BABYLON.CubeMapToSphericalPolynomialTools || !this.isReady()) {
  30470. return null;
  30471. }
  30472. if (!this._texture._sphericalPolynomial) {
  30473. this._texture._sphericalPolynomial =
  30474. BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial(this);
  30475. }
  30476. return this._texture._sphericalPolynomial;
  30477. },
  30478. set: function (value) {
  30479. if (this._texture) {
  30480. this._texture._sphericalPolynomial = value;
  30481. }
  30482. },
  30483. enumerable: true,
  30484. configurable: true
  30485. });
  30486. Object.defineProperty(BaseTexture.prototype, "_lodTextureHigh", {
  30487. get: function () {
  30488. if (this._texture) {
  30489. return this._texture._lodTextureHigh;
  30490. }
  30491. return null;
  30492. },
  30493. enumerable: true,
  30494. configurable: true
  30495. });
  30496. Object.defineProperty(BaseTexture.prototype, "_lodTextureMid", {
  30497. get: function () {
  30498. if (this._texture) {
  30499. return this._texture._lodTextureMid;
  30500. }
  30501. return null;
  30502. },
  30503. enumerable: true,
  30504. configurable: true
  30505. });
  30506. Object.defineProperty(BaseTexture.prototype, "_lodTextureLow", {
  30507. get: function () {
  30508. if (this._texture) {
  30509. return this._texture._lodTextureLow;
  30510. }
  30511. return null;
  30512. },
  30513. enumerable: true,
  30514. configurable: true
  30515. });
  30516. BaseTexture.prototype.dispose = function () {
  30517. if (!this._scene) {
  30518. return;
  30519. }
  30520. // Animations
  30521. this._scene.stopAnimation(this);
  30522. // Remove from scene
  30523. this._scene._removePendingData(this);
  30524. var index = this._scene.textures.indexOf(this);
  30525. if (index >= 0) {
  30526. this._scene.textures.splice(index, 1);
  30527. }
  30528. if (this._texture === undefined) {
  30529. return;
  30530. }
  30531. // Release
  30532. this.releaseInternalTexture();
  30533. // Callback
  30534. this.onDisposeObservable.notifyObservers(this);
  30535. this.onDisposeObservable.clear();
  30536. };
  30537. BaseTexture.prototype.serialize = function () {
  30538. if (!this.name) {
  30539. return null;
  30540. }
  30541. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  30542. // Animations
  30543. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  30544. return serializationObject;
  30545. };
  30546. BaseTexture.WhenAllReady = function (textures, callback) {
  30547. var numRemaining = textures.length;
  30548. if (numRemaining === 0) {
  30549. callback();
  30550. return;
  30551. }
  30552. var _loop_1 = function () {
  30553. texture = textures[i];
  30554. if (texture.isReady()) {
  30555. if (--numRemaining === 0) {
  30556. callback();
  30557. }
  30558. }
  30559. else {
  30560. onLoadObservable = texture.onLoadObservable;
  30561. var onLoadCallback_1 = function () {
  30562. onLoadObservable.removeCallback(onLoadCallback_1);
  30563. if (--numRemaining === 0) {
  30564. callback();
  30565. }
  30566. };
  30567. onLoadObservable.add(onLoadCallback_1);
  30568. }
  30569. };
  30570. var texture, onLoadObservable;
  30571. for (var i = 0; i < textures.length; i++) {
  30572. _loop_1();
  30573. }
  30574. };
  30575. BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL = 4;
  30576. __decorate([
  30577. BABYLON.serialize()
  30578. ], BaseTexture.prototype, "name", void 0);
  30579. __decorate([
  30580. BABYLON.serialize("hasAlpha")
  30581. ], BaseTexture.prototype, "_hasAlpha", void 0);
  30582. __decorate([
  30583. BABYLON.serialize()
  30584. ], BaseTexture.prototype, "getAlphaFromRGB", void 0);
  30585. __decorate([
  30586. BABYLON.serialize()
  30587. ], BaseTexture.prototype, "level", void 0);
  30588. __decorate([
  30589. BABYLON.serialize()
  30590. ], BaseTexture.prototype, "coordinatesIndex", void 0);
  30591. __decorate([
  30592. BABYLON.serialize("coordinatesMode")
  30593. ], BaseTexture.prototype, "_coordinatesMode", void 0);
  30594. __decorate([
  30595. BABYLON.serialize()
  30596. ], BaseTexture.prototype, "wrapU", void 0);
  30597. __decorate([
  30598. BABYLON.serialize()
  30599. ], BaseTexture.prototype, "wrapV", void 0);
  30600. __decorate([
  30601. BABYLON.serialize()
  30602. ], BaseTexture.prototype, "wrapR", void 0);
  30603. __decorate([
  30604. BABYLON.serialize()
  30605. ], BaseTexture.prototype, "anisotropicFilteringLevel", void 0);
  30606. __decorate([
  30607. BABYLON.serialize()
  30608. ], BaseTexture.prototype, "isCube", void 0);
  30609. __decorate([
  30610. BABYLON.serialize()
  30611. ], BaseTexture.prototype, "is3D", void 0);
  30612. __decorate([
  30613. BABYLON.serialize()
  30614. ], BaseTexture.prototype, "gammaSpace", void 0);
  30615. __decorate([
  30616. BABYLON.serialize()
  30617. ], BaseTexture.prototype, "invertZ", void 0);
  30618. __decorate([
  30619. BABYLON.serialize()
  30620. ], BaseTexture.prototype, "lodLevelInAlpha", void 0);
  30621. __decorate([
  30622. BABYLON.serialize()
  30623. ], BaseTexture.prototype, "lodGenerationOffset", void 0);
  30624. __decorate([
  30625. BABYLON.serialize()
  30626. ], BaseTexture.prototype, "lodGenerationScale", void 0);
  30627. __decorate([
  30628. BABYLON.serialize()
  30629. ], BaseTexture.prototype, "isRenderTarget", void 0);
  30630. return BaseTexture;
  30631. }());
  30632. BABYLON.BaseTexture = BaseTexture;
  30633. })(BABYLON || (BABYLON = {}));
  30634. //# sourceMappingURL=babylon.baseTexture.js.map
  30635. var BABYLON;
  30636. (function (BABYLON) {
  30637. var Texture = /** @class */ (function (_super) {
  30638. __extends(Texture, _super);
  30639. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format) {
  30640. if (noMipmap === void 0) { noMipmap = false; }
  30641. if (invertY === void 0) { invertY = true; }
  30642. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  30643. if (onLoad === void 0) { onLoad = null; }
  30644. if (onError === void 0) { onError = null; }
  30645. if (buffer === void 0) { buffer = null; }
  30646. if (deleteBuffer === void 0) { deleteBuffer = false; }
  30647. var _this = _super.call(this, scene) || this;
  30648. _this.uOffset = 0;
  30649. _this.vOffset = 0;
  30650. _this.uScale = 1.0;
  30651. _this.vScale = 1.0;
  30652. _this.uAng = 0;
  30653. _this.vAng = 0;
  30654. _this.wAng = 0;
  30655. /**
  30656. * Defines the center of rotation (U)
  30657. */
  30658. _this.uRotationCenter = 0.5;
  30659. /**
  30660. * Defines the center of rotation (V)
  30661. */
  30662. _this.vRotationCenter = 0.5;
  30663. /**
  30664. * Defines the center of rotation (W)
  30665. */
  30666. _this.wRotationCenter = 0.5;
  30667. _this._isBlocking = true;
  30668. _this.name = url || "";
  30669. _this.url = url;
  30670. _this._noMipmap = noMipmap;
  30671. _this._invertY = invertY;
  30672. _this._samplingMode = samplingMode;
  30673. _this._buffer = buffer;
  30674. _this._deleteBuffer = deleteBuffer;
  30675. if (format) {
  30676. _this._format = format;
  30677. }
  30678. scene = _this.getScene();
  30679. if (!scene) {
  30680. return _this;
  30681. }
  30682. scene.getEngine().onBeforeTextureInitObservable.notifyObservers(_this);
  30683. var load = function () {
  30684. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  30685. _this.onLoadObservable.notifyObservers(_this);
  30686. }
  30687. if (onLoad) {
  30688. onLoad();
  30689. }
  30690. if (!_this.isBlocking && scene) {
  30691. scene.resetCachedMaterial();
  30692. }
  30693. };
  30694. if (!_this.url) {
  30695. _this._delayedOnLoad = load;
  30696. _this._delayedOnError = onError;
  30697. return _this;
  30698. }
  30699. _this._texture = _this._getFromCache(_this.url, noMipmap, samplingMode);
  30700. if (!_this._texture) {
  30701. if (!scene.useDelayedTextureLoading) {
  30702. _this._texture = scene.getEngine().createTexture(_this.url, noMipmap, invertY, scene, _this._samplingMode, load, onError, _this._buffer, undefined, _this._format);
  30703. if (deleteBuffer) {
  30704. delete _this._buffer;
  30705. }
  30706. }
  30707. else {
  30708. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  30709. _this._delayedOnLoad = load;
  30710. _this._delayedOnError = onError;
  30711. }
  30712. }
  30713. else {
  30714. if (_this._texture.isReady) {
  30715. BABYLON.Tools.SetImmediate(function () { return load(); });
  30716. }
  30717. else {
  30718. _this._texture.onLoadedObservable.add(load);
  30719. }
  30720. }
  30721. return _this;
  30722. }
  30723. Object.defineProperty(Texture.prototype, "noMipmap", {
  30724. get: function () {
  30725. return this._noMipmap;
  30726. },
  30727. enumerable: true,
  30728. configurable: true
  30729. });
  30730. Object.defineProperty(Texture.prototype, "isBlocking", {
  30731. get: function () {
  30732. return this._isBlocking;
  30733. },
  30734. set: function (value) {
  30735. this._isBlocking = value;
  30736. },
  30737. enumerable: true,
  30738. configurable: true
  30739. });
  30740. Object.defineProperty(Texture.prototype, "samplingMode", {
  30741. get: function () {
  30742. return this._samplingMode;
  30743. },
  30744. enumerable: true,
  30745. configurable: true
  30746. });
  30747. /**
  30748. * Update the url (and optional buffer) of this texture if url was null during construction.
  30749. * @param url the url of the texture
  30750. * @param buffer the buffer of the texture (defaults to null)
  30751. */
  30752. Texture.prototype.updateURL = function (url, buffer) {
  30753. if (buffer === void 0) { buffer = null; }
  30754. if (this.url) {
  30755. throw new Error("URL is already set");
  30756. }
  30757. this.url = url;
  30758. this._buffer = buffer;
  30759. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  30760. this.delayLoad();
  30761. };
  30762. Texture.prototype.delayLoad = function () {
  30763. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  30764. return;
  30765. }
  30766. var scene = this.getScene();
  30767. if (!scene) {
  30768. return;
  30769. }
  30770. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  30771. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  30772. if (!this._texture) {
  30773. this._texture = scene.getEngine().createTexture(this.url, this._noMipmap, this._invertY, scene, this._samplingMode, this._delayedOnLoad, this._delayedOnError, this._buffer, null, this._format);
  30774. if (this._deleteBuffer) {
  30775. delete this._buffer;
  30776. }
  30777. }
  30778. else {
  30779. if (this._delayedOnLoad) {
  30780. if (this._texture.isReady) {
  30781. BABYLON.Tools.SetImmediate(this._delayedOnLoad);
  30782. }
  30783. else {
  30784. this._texture.onLoadedObservable.add(this._delayedOnLoad);
  30785. }
  30786. }
  30787. }
  30788. this._delayedOnLoad = null;
  30789. this._delayedOnError = null;
  30790. };
  30791. Texture.prototype.updateSamplingMode = function (samplingMode) {
  30792. if (!this._texture) {
  30793. return;
  30794. }
  30795. var scene = this.getScene();
  30796. if (!scene) {
  30797. return;
  30798. }
  30799. this._samplingMode = samplingMode;
  30800. scene.getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  30801. };
  30802. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  30803. x *= this.uScale;
  30804. y *= this.vScale;
  30805. x -= this.uRotationCenter * this.uScale;
  30806. y -= this.vRotationCenter * this.vScale;
  30807. z -= this.wRotationCenter;
  30808. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  30809. t.x += this.uRotationCenter * this.uScale + this.uOffset;
  30810. t.y += this.vRotationCenter * this.vScale + this.vOffset;
  30811. t.z += this.wRotationCenter;
  30812. };
  30813. Texture.prototype.getTextureMatrix = function () {
  30814. var _this = this;
  30815. if (this.uOffset === this._cachedUOffset &&
  30816. this.vOffset === this._cachedVOffset &&
  30817. this.uScale === this._cachedUScale &&
  30818. this.vScale === this._cachedVScale &&
  30819. this.uAng === this._cachedUAng &&
  30820. this.vAng === this._cachedVAng &&
  30821. this.wAng === this._cachedWAng) {
  30822. return this._cachedTextureMatrix;
  30823. }
  30824. this._cachedUOffset = this.uOffset;
  30825. this._cachedVOffset = this.vOffset;
  30826. this._cachedUScale = this.uScale;
  30827. this._cachedVScale = this.vScale;
  30828. this._cachedUAng = this.uAng;
  30829. this._cachedVAng = this.vAng;
  30830. this._cachedWAng = this.wAng;
  30831. if (!this._cachedTextureMatrix) {
  30832. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  30833. this._rowGenerationMatrix = new BABYLON.Matrix();
  30834. this._t0 = BABYLON.Vector3.Zero();
  30835. this._t1 = BABYLON.Vector3.Zero();
  30836. this._t2 = BABYLON.Vector3.Zero();
  30837. }
  30838. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  30839. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  30840. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  30841. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  30842. this._t1.subtractInPlace(this._t0);
  30843. this._t2.subtractInPlace(this._t0);
  30844. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  30845. this._cachedTextureMatrix.m[0] = this._t1.x;
  30846. this._cachedTextureMatrix.m[1] = this._t1.y;
  30847. this._cachedTextureMatrix.m[2] = this._t1.z;
  30848. this._cachedTextureMatrix.m[4] = this._t2.x;
  30849. this._cachedTextureMatrix.m[5] = this._t2.y;
  30850. this._cachedTextureMatrix.m[6] = this._t2.z;
  30851. this._cachedTextureMatrix.m[8] = this._t0.x;
  30852. this._cachedTextureMatrix.m[9] = this._t0.y;
  30853. this._cachedTextureMatrix.m[10] = this._t0.z;
  30854. var scene = this.getScene();
  30855. if (!scene) {
  30856. return this._cachedTextureMatrix;
  30857. }
  30858. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  30859. return mat.hasTexture(_this);
  30860. });
  30861. return this._cachedTextureMatrix;
  30862. };
  30863. Texture.prototype.getReflectionTextureMatrix = function () {
  30864. var _this = this;
  30865. var scene = this.getScene();
  30866. if (!scene) {
  30867. return this._cachedTextureMatrix;
  30868. }
  30869. if (this.uOffset === this._cachedUOffset &&
  30870. this.vOffset === this._cachedVOffset &&
  30871. this.uScale === this._cachedUScale &&
  30872. this.vScale === this._cachedVScale &&
  30873. this.coordinatesMode === this._cachedCoordinatesMode) {
  30874. if (this.coordinatesMode === Texture.PROJECTION_MODE) {
  30875. if (this._cachedProjectionMatrixId === scene.getProjectionMatrix().updateFlag) {
  30876. return this._cachedTextureMatrix;
  30877. }
  30878. }
  30879. else {
  30880. return this._cachedTextureMatrix;
  30881. }
  30882. }
  30883. if (!this._cachedTextureMatrix) {
  30884. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  30885. }
  30886. if (!this._projectionModeMatrix) {
  30887. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  30888. }
  30889. this._cachedUOffset = this.uOffset;
  30890. this._cachedVOffset = this.vOffset;
  30891. this._cachedUScale = this.uScale;
  30892. this._cachedVScale = this.vScale;
  30893. this._cachedCoordinatesMode = this.coordinatesMode;
  30894. switch (this.coordinatesMode) {
  30895. case Texture.PLANAR_MODE:
  30896. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  30897. this._cachedTextureMatrix[0] = this.uScale;
  30898. this._cachedTextureMatrix[5] = this.vScale;
  30899. this._cachedTextureMatrix[12] = this.uOffset;
  30900. this._cachedTextureMatrix[13] = this.vOffset;
  30901. break;
  30902. case Texture.PROJECTION_MODE:
  30903. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  30904. this._projectionModeMatrix.m[0] = 0.5;
  30905. this._projectionModeMatrix.m[5] = -0.5;
  30906. this._projectionModeMatrix.m[10] = 0.0;
  30907. this._projectionModeMatrix.m[12] = 0.5;
  30908. this._projectionModeMatrix.m[13] = 0.5;
  30909. this._projectionModeMatrix.m[14] = 1.0;
  30910. this._projectionModeMatrix.m[15] = 1.0;
  30911. var projectionMatrix = scene.getProjectionMatrix();
  30912. this._cachedProjectionMatrixId = projectionMatrix.updateFlag;
  30913. projectionMatrix.multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  30914. break;
  30915. default:
  30916. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  30917. break;
  30918. }
  30919. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  30920. return (mat.getActiveTextures().indexOf(_this) !== -1);
  30921. });
  30922. return this._cachedTextureMatrix;
  30923. };
  30924. Texture.prototype.clone = function () {
  30925. var _this = this;
  30926. return BABYLON.SerializationHelper.Clone(function () {
  30927. return new Texture(_this._texture ? _this._texture.url : null, _this.getScene(), _this._noMipmap, _this._invertY, _this._samplingMode);
  30928. }, this);
  30929. };
  30930. Object.defineProperty(Texture.prototype, "onLoadObservable", {
  30931. get: function () {
  30932. if (!this._onLoadObservable) {
  30933. this._onLoadObservable = new BABYLON.Observable();
  30934. }
  30935. return this._onLoadObservable;
  30936. },
  30937. enumerable: true,
  30938. configurable: true
  30939. });
  30940. Texture.prototype.serialize = function () {
  30941. var serializationObject = _super.prototype.serialize.call(this);
  30942. if (typeof this._buffer === "string" && this._buffer.substr(0, 5) === "data:") {
  30943. serializationObject.base64String = this._buffer;
  30944. serializationObject.name = serializationObject.name.replace("data:", "");
  30945. }
  30946. serializationObject.invertY = this._invertY;
  30947. serializationObject.samplingMode = this.samplingMode;
  30948. return serializationObject;
  30949. };
  30950. Texture.prototype.getClassName = function () {
  30951. return "Texture";
  30952. };
  30953. Texture.prototype.dispose = function () {
  30954. _super.prototype.dispose.call(this);
  30955. if (this.onLoadObservable) {
  30956. this.onLoadObservable.clear();
  30957. this._onLoadObservable = null;
  30958. }
  30959. this._delayedOnLoad = null;
  30960. this._delayedOnError = null;
  30961. };
  30962. // Statics
  30963. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  30964. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  30965. if (onLoad === void 0) { onLoad = null; }
  30966. if (onError === void 0) { onError = null; }
  30967. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  30968. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data, false, format);
  30969. };
  30970. Texture.Parse = function (parsedTexture, scene, rootUrl) {
  30971. if (parsedTexture.customType) {
  30972. var customTexture = BABYLON.Tools.Instantiate(parsedTexture.customType);
  30973. // Update Sampling Mode
  30974. var parsedCustomTexture = customTexture.Parse(parsedTexture, scene, rootUrl);
  30975. if (parsedTexture.samplingMode && parsedCustomTexture.updateSamplingMode && parsedCustomTexture._samplingMode) {
  30976. if (parsedCustomTexture._samplingMode !== parsedTexture.samplingMode) {
  30977. parsedCustomTexture.updateSamplingMode(parsedTexture.samplingMode);
  30978. }
  30979. }
  30980. return parsedCustomTexture;
  30981. }
  30982. if (parsedTexture.isCube) {
  30983. return BABYLON.CubeTexture.Parse(parsedTexture, scene, rootUrl);
  30984. }
  30985. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  30986. return null;
  30987. }
  30988. var texture = BABYLON.SerializationHelper.Parse(function () {
  30989. var generateMipMaps = true;
  30990. if (parsedTexture.noMipmap) {
  30991. generateMipMaps = false;
  30992. }
  30993. if (parsedTexture.mirrorPlane) {
  30994. var mirrorTexture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  30995. mirrorTexture._waitingRenderList = parsedTexture.renderList;
  30996. mirrorTexture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  30997. return mirrorTexture;
  30998. }
  30999. else if (parsedTexture.isRenderTarget) {
  31000. var renderTargetTexture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  31001. renderTargetTexture._waitingRenderList = parsedTexture.renderList;
  31002. return renderTargetTexture;
  31003. }
  31004. else {
  31005. var texture;
  31006. if (parsedTexture.base64String) {
  31007. texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene, !generateMipMaps);
  31008. }
  31009. else {
  31010. var url = rootUrl + parsedTexture.name;
  31011. if (Texture.UseSerializedUrlIfAny && parsedTexture.url) {
  31012. url = parsedTexture.url;
  31013. }
  31014. texture = new Texture(url, scene, !generateMipMaps, parsedTexture.invertY);
  31015. }
  31016. return texture;
  31017. }
  31018. }, parsedTexture, scene);
  31019. // Update Sampling Mode
  31020. if (parsedTexture.samplingMode) {
  31021. var sampling = parsedTexture.samplingMode;
  31022. if (texture._samplingMode !== sampling) {
  31023. texture.updateSamplingMode(sampling);
  31024. }
  31025. }
  31026. // Animations
  31027. if (parsedTexture.animations) {
  31028. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  31029. var parsedAnimation = parsedTexture.animations[animationIndex];
  31030. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  31031. }
  31032. }
  31033. return texture;
  31034. };
  31035. Texture.LoadFromDataString = function (name, buffer, scene, deleteBuffer, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  31036. if (deleteBuffer === void 0) { deleteBuffer = false; }
  31037. if (noMipmap === void 0) { noMipmap = false; }
  31038. if (invertY === void 0) { invertY = true; }
  31039. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  31040. if (onLoad === void 0) { onLoad = null; }
  31041. if (onError === void 0) { onError = null; }
  31042. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  31043. if (name.substr(0, 5) !== "data:") {
  31044. name = "data:" + name;
  31045. }
  31046. return new Texture(name, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format);
  31047. };
  31048. // Constants
  31049. Texture.NEAREST_SAMPLINGMODE = 1;
  31050. Texture.NEAREST_NEAREST_MIPLINEAR = 1; // nearest is mag = nearest and min = nearest and mip = linear
  31051. Texture.BILINEAR_SAMPLINGMODE = 2;
  31052. Texture.LINEAR_LINEAR_MIPNEAREST = 2; // Bilinear is mag = linear and min = linear and mip = nearest
  31053. Texture.TRILINEAR_SAMPLINGMODE = 3;
  31054. Texture.LINEAR_LINEAR_MIPLINEAR = 3; // Trilinear is mag = linear and min = linear and mip = linear
  31055. Texture.NEAREST_NEAREST_MIPNEAREST = 4;
  31056. Texture.NEAREST_LINEAR_MIPNEAREST = 5;
  31057. Texture.NEAREST_LINEAR_MIPLINEAR = 6;
  31058. Texture.NEAREST_LINEAR = 7;
  31059. Texture.NEAREST_NEAREST = 8;
  31060. Texture.LINEAR_NEAREST_MIPNEAREST = 9;
  31061. Texture.LINEAR_NEAREST_MIPLINEAR = 10;
  31062. Texture.LINEAR_LINEAR = 11;
  31063. Texture.LINEAR_NEAREST = 12;
  31064. Texture.EXPLICIT_MODE = 0;
  31065. Texture.SPHERICAL_MODE = 1;
  31066. Texture.PLANAR_MODE = 2;
  31067. Texture.CUBIC_MODE = 3;
  31068. Texture.PROJECTION_MODE = 4;
  31069. Texture.SKYBOX_MODE = 5;
  31070. Texture.INVCUBIC_MODE = 6;
  31071. Texture.EQUIRECTANGULAR_MODE = 7;
  31072. Texture.FIXED_EQUIRECTANGULAR_MODE = 8;
  31073. Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE = 9;
  31074. Texture.CLAMP_ADDRESSMODE = 0;
  31075. Texture.WRAP_ADDRESSMODE = 1;
  31076. Texture.MIRROR_ADDRESSMODE = 2;
  31077. /**
  31078. * 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
  31079. */
  31080. Texture.UseSerializedUrlIfAny = false;
  31081. __decorate([
  31082. BABYLON.serialize()
  31083. ], Texture.prototype, "url", void 0);
  31084. __decorate([
  31085. BABYLON.serialize()
  31086. ], Texture.prototype, "uOffset", void 0);
  31087. __decorate([
  31088. BABYLON.serialize()
  31089. ], Texture.prototype, "vOffset", void 0);
  31090. __decorate([
  31091. BABYLON.serialize()
  31092. ], Texture.prototype, "uScale", void 0);
  31093. __decorate([
  31094. BABYLON.serialize()
  31095. ], Texture.prototype, "vScale", void 0);
  31096. __decorate([
  31097. BABYLON.serialize()
  31098. ], Texture.prototype, "uAng", void 0);
  31099. __decorate([
  31100. BABYLON.serialize()
  31101. ], Texture.prototype, "vAng", void 0);
  31102. __decorate([
  31103. BABYLON.serialize()
  31104. ], Texture.prototype, "wAng", void 0);
  31105. __decorate([
  31106. BABYLON.serialize()
  31107. ], Texture.prototype, "uRotationCenter", void 0);
  31108. __decorate([
  31109. BABYLON.serialize()
  31110. ], Texture.prototype, "vRotationCenter", void 0);
  31111. __decorate([
  31112. BABYLON.serialize()
  31113. ], Texture.prototype, "wRotationCenter", void 0);
  31114. __decorate([
  31115. BABYLON.serialize()
  31116. ], Texture.prototype, "isBlocking", null);
  31117. return Texture;
  31118. }(BABYLON.BaseTexture));
  31119. BABYLON.Texture = Texture;
  31120. })(BABYLON || (BABYLON = {}));
  31121. //# sourceMappingURL=babylon.texture.js.map
  31122. var BABYLON;
  31123. (function (BABYLON) {
  31124. /**
  31125. * @hidden
  31126. **/
  31127. var _InstancesBatch = /** @class */ (function () {
  31128. function _InstancesBatch() {
  31129. this.mustReturn = false;
  31130. this.visibleInstances = new Array();
  31131. this.renderSelf = new Array();
  31132. }
  31133. return _InstancesBatch;
  31134. }());
  31135. BABYLON._InstancesBatch = _InstancesBatch;
  31136. var Mesh = /** @class */ (function (_super) {
  31137. __extends(Mesh, _super);
  31138. /**
  31139. * @constructor
  31140. * @param {string} name The value used by scene.getMeshByName() to do a lookup.
  31141. * @param {Scene} scene The scene to add this mesh to.
  31142. * @param {Node} parent The parent of this mesh, if it has one
  31143. * @param {Mesh} source An optional Mesh from which geometry is shared, cloned.
  31144. * @param {boolean} doNotCloneChildren When cloning, skip cloning child meshes of source, default False.
  31145. * When false, achieved by calling a clone(), also passing False.
  31146. * This will make creation of children, recursive.
  31147. * @param {boolean} clonePhysicsImpostor When cloning, include cloning mesh physics impostor, default True.
  31148. */
  31149. function Mesh(name, scene, parent, source, doNotCloneChildren, clonePhysicsImpostor) {
  31150. if (scene === void 0) { scene = null; }
  31151. if (parent === void 0) { parent = null; }
  31152. if (source === void 0) { source = null; }
  31153. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  31154. var _this = _super.call(this, name, scene) || this;
  31155. // Events
  31156. /**
  31157. * An event triggered before rendering the mesh
  31158. */
  31159. _this.onBeforeRenderObservable = new BABYLON.Observable();
  31160. /**
  31161. * An event triggered after rendering the mesh
  31162. */
  31163. _this.onAfterRenderObservable = new BABYLON.Observable();
  31164. /**
  31165. * An event triggered before drawing the mesh
  31166. */
  31167. _this.onBeforeDrawObservable = new BABYLON.Observable();
  31168. // Members
  31169. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  31170. _this.instances = new Array();
  31171. _this._LODLevels = new Array();
  31172. _this._visibleInstances = {};
  31173. _this._renderIdForInstances = new Array();
  31174. _this._batchCache = new _InstancesBatch();
  31175. _this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  31176. // Use by builder only to know what orientation were the mesh build in.
  31177. _this._originalBuilderSideOrientation = Mesh._DEFAULTSIDE;
  31178. _this.overrideMaterialSideOrientation = null;
  31179. _this._areNormalsFrozen = false; // Will be used by ribbons mainly
  31180. // Will be used to save a source mesh reference, If any
  31181. _this._source = null;
  31182. scene = _this.getScene();
  31183. if (source) {
  31184. // Geometry
  31185. if (source._geometry) {
  31186. source._geometry.applyToMesh(_this);
  31187. }
  31188. // Deep copy
  31189. BABYLON.Tools.DeepCopy(source, _this, ["name", "material", "skeleton", "instances", "parent", "uniqueId",
  31190. "source", "metadata", "hasLODLevels", "geometry", "isBlocked", "areNormalsFrozen"], ["_poseMatrix"]);
  31191. // Source mesh
  31192. _this._source = source;
  31193. // Metadata
  31194. if (source.metadata && source.metadata.clone) {
  31195. _this.metadata = source.metadata.clone();
  31196. }
  31197. else {
  31198. _this.metadata = source.metadata;
  31199. }
  31200. // Tags
  31201. if (BABYLON.Tags && BABYLON.Tags.HasTags(source)) {
  31202. BABYLON.Tags.AddTagsTo(_this, BABYLON.Tags.GetTags(source, true));
  31203. }
  31204. // Parent
  31205. _this.parent = source.parent;
  31206. // Pivot
  31207. _this.setPivotMatrix(source.getPivotMatrix());
  31208. _this.id = name + "." + source.id;
  31209. // Material
  31210. _this.material = source.material;
  31211. var index;
  31212. if (!doNotCloneChildren) {
  31213. // Children
  31214. var directDescendants = source.getDescendants(true);
  31215. for (var index_1 = 0; index_1 < directDescendants.length; index_1++) {
  31216. var child = directDescendants[index_1];
  31217. if (child.clone) {
  31218. child.clone(name + "." + child.name, _this);
  31219. }
  31220. }
  31221. }
  31222. // Physics clone
  31223. var physicsEngine = _this.getScene().getPhysicsEngine();
  31224. if (clonePhysicsImpostor && physicsEngine) {
  31225. var impostor = physicsEngine.getImpostorForPhysicsObject(source);
  31226. if (impostor) {
  31227. _this.physicsImpostor = impostor.clone(_this);
  31228. }
  31229. }
  31230. // Particles
  31231. for (index = 0; index < scene.particleSystems.length; index++) {
  31232. var system = scene.particleSystems[index];
  31233. if (system.emitter === source) {
  31234. system.clone(system.name, _this);
  31235. }
  31236. }
  31237. _this.computeWorldMatrix(true);
  31238. }
  31239. // Parent
  31240. if (parent !== null) {
  31241. _this.parent = parent;
  31242. }
  31243. return _this;
  31244. }
  31245. Object.defineProperty(Mesh, "FRONTSIDE", {
  31246. /**
  31247. * Mesh side orientation : usually the external or front surface
  31248. */
  31249. get: function () {
  31250. return Mesh._FRONTSIDE;
  31251. },
  31252. enumerable: true,
  31253. configurable: true
  31254. });
  31255. Object.defineProperty(Mesh, "BACKSIDE", {
  31256. /**
  31257. * Mesh side orientation : usually the internal or back surface
  31258. */
  31259. get: function () {
  31260. return Mesh._BACKSIDE;
  31261. },
  31262. enumerable: true,
  31263. configurable: true
  31264. });
  31265. Object.defineProperty(Mesh, "DOUBLESIDE", {
  31266. /**
  31267. * Mesh side orientation : both internal and external or front and back surfaces
  31268. */
  31269. get: function () {
  31270. return Mesh._DOUBLESIDE;
  31271. },
  31272. enumerable: true,
  31273. configurable: true
  31274. });
  31275. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  31276. /**
  31277. * Mesh side orientation : by default, `FRONTSIDE`
  31278. */
  31279. get: function () {
  31280. return Mesh._DEFAULTSIDE;
  31281. },
  31282. enumerable: true,
  31283. configurable: true
  31284. });
  31285. Object.defineProperty(Mesh, "NO_CAP", {
  31286. /**
  31287. * Mesh cap setting : no cap
  31288. */
  31289. get: function () {
  31290. return Mesh._NO_CAP;
  31291. },
  31292. enumerable: true,
  31293. configurable: true
  31294. });
  31295. Object.defineProperty(Mesh, "CAP_START", {
  31296. /**
  31297. * Mesh cap setting : one cap at the beginning of the mesh
  31298. */
  31299. get: function () {
  31300. return Mesh._CAP_START;
  31301. },
  31302. enumerable: true,
  31303. configurable: true
  31304. });
  31305. Object.defineProperty(Mesh, "CAP_END", {
  31306. /**
  31307. * Mesh cap setting : one cap at the end of the mesh
  31308. */
  31309. get: function () {
  31310. return Mesh._CAP_END;
  31311. },
  31312. enumerable: true,
  31313. configurable: true
  31314. });
  31315. Object.defineProperty(Mesh, "CAP_ALL", {
  31316. /**
  31317. * Mesh cap setting : two caps, one at the beginning and one at the end of the mesh
  31318. */
  31319. get: function () {
  31320. return Mesh._CAP_ALL;
  31321. },
  31322. enumerable: true,
  31323. configurable: true
  31324. });
  31325. Object.defineProperty(Mesh.prototype, "onBeforeDraw", {
  31326. set: function (callback) {
  31327. if (this._onBeforeDrawObserver) {
  31328. this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver);
  31329. }
  31330. this._onBeforeDrawObserver = this.onBeforeDrawObservable.add(callback);
  31331. },
  31332. enumerable: true,
  31333. configurable: true
  31334. });
  31335. Object.defineProperty(Mesh.prototype, "morphTargetManager", {
  31336. get: function () {
  31337. return this._morphTargetManager;
  31338. },
  31339. set: function (value) {
  31340. if (this._morphTargetManager === value) {
  31341. return;
  31342. }
  31343. this._morphTargetManager = value;
  31344. this._syncGeometryWithMorphTargetManager();
  31345. },
  31346. enumerable: true,
  31347. configurable: true
  31348. });
  31349. Object.defineProperty(Mesh.prototype, "source", {
  31350. get: function () {
  31351. return this._source;
  31352. },
  31353. enumerable: true,
  31354. configurable: true
  31355. });
  31356. Object.defineProperty(Mesh.prototype, "isUnIndexed", {
  31357. get: function () {
  31358. return this._unIndexed;
  31359. },
  31360. set: function (value) {
  31361. if (this._unIndexed !== value) {
  31362. this._unIndexed = value;
  31363. this._markSubMeshesAsAttributesDirty();
  31364. }
  31365. },
  31366. enumerable: true,
  31367. configurable: true
  31368. });
  31369. // Methods
  31370. /**
  31371. * Returns the string "Mesh".
  31372. */
  31373. Mesh.prototype.getClassName = function () {
  31374. return "Mesh";
  31375. };
  31376. /**
  31377. * Returns a string.
  31378. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  31379. */
  31380. Mesh.prototype.toString = function (fullDetails) {
  31381. var ret = _super.prototype.toString.call(this, fullDetails);
  31382. ret += ", n vertices: " + this.getTotalVertices();
  31383. ret += ", parent: " + (this._waitingParentId ? this._waitingParentId : (this.parent ? this.parent.name : "NONE"));
  31384. if (this.animations) {
  31385. for (var i = 0; i < this.animations.length; i++) {
  31386. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  31387. }
  31388. }
  31389. if (fullDetails) {
  31390. if (this._geometry) {
  31391. var ib = this.getIndices();
  31392. var vb = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  31393. if (vb && ib) {
  31394. ret += ", flat shading: " + (vb.length / 3 === ib.length ? "YES" : "NO");
  31395. }
  31396. }
  31397. else {
  31398. ret += ", flat shading: UNKNOWN";
  31399. }
  31400. }
  31401. return ret;
  31402. };
  31403. Mesh.prototype._unBindEffect = function () {
  31404. _super.prototype._unBindEffect.call(this);
  31405. for (var _i = 0, _a = this.instances; _i < _a.length; _i++) {
  31406. var instance = _a[_i];
  31407. instance._unBindEffect();
  31408. }
  31409. };
  31410. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  31411. /**
  31412. * True if the mesh has some Levels Of Details (LOD).
  31413. * Returns a boolean.
  31414. */
  31415. get: function () {
  31416. return this._LODLevels.length > 0;
  31417. },
  31418. enumerable: true,
  31419. configurable: true
  31420. });
  31421. /**
  31422. * Gets the list of {BABYLON.MeshLODLevel} associated with the current mesh
  31423. * @returns an array of {BABYLON.MeshLODLevel}
  31424. */
  31425. Mesh.prototype.getLODLevels = function () {
  31426. return this._LODLevels;
  31427. };
  31428. Mesh.prototype._sortLODLevels = function () {
  31429. this._LODLevels.sort(function (a, b) {
  31430. if (a.distance < b.distance) {
  31431. return 1;
  31432. }
  31433. if (a.distance > b.distance) {
  31434. return -1;
  31435. }
  31436. return 0;
  31437. });
  31438. };
  31439. /**
  31440. * Add a mesh as LOD level triggered at the given distance.
  31441. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  31442. * @param {number} distance The distance from the center of the object to show this level
  31443. * @param {Mesh} mesh The mesh to be added as LOD level
  31444. * @return {Mesh} This mesh (for chaining)
  31445. */
  31446. Mesh.prototype.addLODLevel = function (distance, mesh) {
  31447. if (mesh && mesh._masterMesh) {
  31448. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  31449. return this;
  31450. }
  31451. var level = new BABYLON.MeshLODLevel(distance, mesh);
  31452. this._LODLevels.push(level);
  31453. if (mesh) {
  31454. mesh._masterMesh = this;
  31455. }
  31456. this._sortLODLevels();
  31457. return this;
  31458. };
  31459. /**
  31460. * Returns the LOD level mesh at the passed distance or null if not found.
  31461. * It is related to the method `addLODLevel(distance, mesh)`.
  31462. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  31463. * Returns an object Mesh or `null`.
  31464. */
  31465. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  31466. for (var index = 0; index < this._LODLevels.length; index++) {
  31467. var level = this._LODLevels[index];
  31468. if (level.distance === distance) {
  31469. return level.mesh;
  31470. }
  31471. }
  31472. return null;
  31473. };
  31474. /**
  31475. * Remove a mesh from the LOD array
  31476. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  31477. * @param {Mesh} mesh The mesh to be removed.
  31478. * @return {Mesh} This mesh (for chaining)
  31479. */
  31480. Mesh.prototype.removeLODLevel = function (mesh) {
  31481. for (var index = 0; index < this._LODLevels.length; index++) {
  31482. if (this._LODLevels[index].mesh === mesh) {
  31483. this._LODLevels.splice(index, 1);
  31484. if (mesh) {
  31485. mesh._masterMesh = null;
  31486. }
  31487. }
  31488. }
  31489. this._sortLODLevels();
  31490. return this;
  31491. };
  31492. /**
  31493. * Returns the registered LOD mesh distant from the parameter `camera` position if any, else returns the current mesh.
  31494. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  31495. */
  31496. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  31497. if (!this._LODLevels || this._LODLevels.length === 0) {
  31498. return this;
  31499. }
  31500. var bSphere;
  31501. if (boundingSphere) {
  31502. bSphere = boundingSphere;
  31503. }
  31504. else {
  31505. var boundingInfo = this.getBoundingInfo();
  31506. bSphere = boundingInfo.boundingSphere;
  31507. }
  31508. var distanceToCamera = bSphere.centerWorld.subtract(camera.globalPosition).length();
  31509. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  31510. if (this.onLODLevelSelection) {
  31511. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  31512. }
  31513. return this;
  31514. }
  31515. for (var index = 0; index < this._LODLevels.length; index++) {
  31516. var level = this._LODLevels[index];
  31517. if (level.distance < distanceToCamera) {
  31518. if (level.mesh) {
  31519. level.mesh._preActivate();
  31520. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  31521. }
  31522. if (this.onLODLevelSelection) {
  31523. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  31524. }
  31525. return level.mesh;
  31526. }
  31527. }
  31528. if (this.onLODLevelSelection) {
  31529. this.onLODLevelSelection(distanceToCamera, this, this);
  31530. }
  31531. return this;
  31532. };
  31533. Object.defineProperty(Mesh.prototype, "geometry", {
  31534. /**
  31535. * Returns the mesh internal Geometry object.
  31536. */
  31537. get: function () {
  31538. return this._geometry;
  31539. },
  31540. enumerable: true,
  31541. configurable: true
  31542. });
  31543. /**
  31544. * Returns a positive integer : the total number of vertices within the mesh geometry or zero if the mesh has no geometry.
  31545. */
  31546. Mesh.prototype.getTotalVertices = function () {
  31547. if (this._geometry === null || this._geometry === undefined) {
  31548. return 0;
  31549. }
  31550. return this._geometry.getTotalVertices();
  31551. };
  31552. /**
  31553. * Returns an array of integers or floats, or a Float32Array, depending on the requested `kind` (positions, indices, normals, etc).
  31554. * If `copywhenShared` is true (default false) and if the mesh geometry is shared among some other meshes, the returned array is a copy of the internal one.
  31555. * You can force the copy with forceCopy === true
  31556. * Returns null if the mesh has no geometry or no vertex buffer.
  31557. * Possible `kind` values :
  31558. * - BABYLON.VertexBuffer.PositionKind
  31559. * - BABYLON.VertexBuffer.UVKind
  31560. * - BABYLON.VertexBuffer.UV2Kind
  31561. * - BABYLON.VertexBuffer.UV3Kind
  31562. * - BABYLON.VertexBuffer.UV4Kind
  31563. * - BABYLON.VertexBuffer.UV5Kind
  31564. * - BABYLON.VertexBuffer.UV6Kind
  31565. * - BABYLON.VertexBuffer.ColorKind
  31566. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31567. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31568. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31569. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31570. */
  31571. Mesh.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  31572. if (!this._geometry) {
  31573. return null;
  31574. }
  31575. return this._geometry.getVerticesData(kind, copyWhenShared, forceCopy);
  31576. };
  31577. /**
  31578. * Returns the mesh VertexBuffer object from the requested `kind` : positions, indices, normals, etc.
  31579. * Returns `null` if the mesh has no geometry.
  31580. * Possible `kind` values :
  31581. * - BABYLON.VertexBuffer.PositionKind
  31582. * - BABYLON.VertexBuffer.UVKind
  31583. * - BABYLON.VertexBuffer.UV2Kind
  31584. * - BABYLON.VertexBuffer.UV3Kind
  31585. * - BABYLON.VertexBuffer.UV4Kind
  31586. * - BABYLON.VertexBuffer.UV5Kind
  31587. * - BABYLON.VertexBuffer.UV6Kind
  31588. * - BABYLON.VertexBuffer.ColorKind
  31589. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31590. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31591. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31592. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31593. */
  31594. Mesh.prototype.getVertexBuffer = function (kind) {
  31595. if (!this._geometry) {
  31596. return null;
  31597. }
  31598. return this._geometry.getVertexBuffer(kind);
  31599. };
  31600. Mesh.prototype.isVerticesDataPresent = function (kind) {
  31601. if (!this._geometry) {
  31602. if (this._delayInfo) {
  31603. return this._delayInfo.indexOf(kind) !== -1;
  31604. }
  31605. return false;
  31606. }
  31607. return this._geometry.isVerticesDataPresent(kind);
  31608. };
  31609. /**
  31610. * Returns a boolean defining if the vertex data for the requested `kind` is updatable.
  31611. * Possible `kind` values :
  31612. * - BABYLON.VertexBuffer.PositionKind
  31613. * - BABYLON.VertexBuffer.UVKind
  31614. * - BABYLON.VertexBuffer.UV2Kind
  31615. * - BABYLON.VertexBuffer.UV3Kind
  31616. * - BABYLON.VertexBuffer.UV4Kind
  31617. * - BABYLON.VertexBuffer.UV5Kind
  31618. * - BABYLON.VertexBuffer.UV6Kind
  31619. * - BABYLON.VertexBuffer.ColorKind
  31620. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31621. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31622. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31623. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31624. */
  31625. Mesh.prototype.isVertexBufferUpdatable = function (kind) {
  31626. if (!this._geometry) {
  31627. if (this._delayInfo) {
  31628. return this._delayInfo.indexOf(kind) !== -1;
  31629. }
  31630. return false;
  31631. }
  31632. return this._geometry.isVertexBufferUpdatable(kind);
  31633. };
  31634. /**
  31635. * Returns a string : the list of existing `kinds` of Vertex Data for this mesh.
  31636. * Possible `kind` values :
  31637. * - BABYLON.VertexBuffer.PositionKind
  31638. * - BABYLON.VertexBuffer.UVKind
  31639. * - BABYLON.VertexBuffer.UV2Kind
  31640. * - BABYLON.VertexBuffer.UV3Kind
  31641. * - BABYLON.VertexBuffer.UV4Kind
  31642. * - BABYLON.VertexBuffer.UV5Kind
  31643. * - BABYLON.VertexBuffer.UV6Kind
  31644. * - BABYLON.VertexBuffer.ColorKind
  31645. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31646. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31647. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31648. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31649. */
  31650. Mesh.prototype.getVerticesDataKinds = function () {
  31651. if (!this._geometry) {
  31652. var result = new Array();
  31653. if (this._delayInfo) {
  31654. this._delayInfo.forEach(function (kind, index, array) {
  31655. result.push(kind);
  31656. });
  31657. }
  31658. return result;
  31659. }
  31660. return this._geometry.getVerticesDataKinds();
  31661. };
  31662. /**
  31663. * Returns a positive integer : the total number of indices in this mesh geometry.
  31664. * Returns zero if the mesh has no geometry.
  31665. */
  31666. Mesh.prototype.getTotalIndices = function () {
  31667. if (!this._geometry) {
  31668. return 0;
  31669. }
  31670. return this._geometry.getTotalIndices();
  31671. };
  31672. /**
  31673. * Returns an array of integers or a typed array (Int32Array, Uint32Array, Uint16Array) populated with the mesh indices.
  31674. * If the parameter `copyWhenShared` is true (default false) and and if the mesh geometry is shared among some other meshes, the returned array is a copy of the internal one.
  31675. * Returns an empty array if the mesh has no geometry.
  31676. */
  31677. Mesh.prototype.getIndices = function (copyWhenShared) {
  31678. if (!this._geometry) {
  31679. return [];
  31680. }
  31681. return this._geometry.getIndices(copyWhenShared);
  31682. };
  31683. Object.defineProperty(Mesh.prototype, "isBlocked", {
  31684. get: function () {
  31685. return this._masterMesh !== null && this._masterMesh !== undefined;
  31686. },
  31687. enumerable: true,
  31688. configurable: true
  31689. });
  31690. /**
  31691. * Determine if the current mesh is ready to be rendered
  31692. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  31693. * @param forceInstanceSupport will check if the mesh will be ready when used with instances (false by default)
  31694. * @returns true if all associated assets are ready (material, textures, shaders)
  31695. */
  31696. Mesh.prototype.isReady = function (completeCheck, forceInstanceSupport) {
  31697. if (completeCheck === void 0) { completeCheck = false; }
  31698. if (forceInstanceSupport === void 0) { forceInstanceSupport = false; }
  31699. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  31700. return false;
  31701. }
  31702. if (!_super.prototype.isReady.call(this, completeCheck)) {
  31703. return false;
  31704. }
  31705. if (!this.subMeshes || this.subMeshes.length === 0) {
  31706. return true;
  31707. }
  31708. if (!completeCheck) {
  31709. return true;
  31710. }
  31711. var engine = this.getEngine();
  31712. var scene = this.getScene();
  31713. var hardwareInstancedRendering = forceInstanceSupport || engine.getCaps().instancedArrays && this.instances.length > 0;
  31714. this.computeWorldMatrix();
  31715. var mat = this.material || scene.defaultMaterial;
  31716. if (mat) {
  31717. if (mat.storeEffectOnSubMeshes) {
  31718. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  31719. var subMesh = _a[_i];
  31720. var effectiveMaterial = subMesh.getMaterial();
  31721. if (effectiveMaterial) {
  31722. if (effectiveMaterial.storeEffectOnSubMeshes) {
  31723. if (!effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  31724. return false;
  31725. }
  31726. }
  31727. else {
  31728. if (!effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  31729. return false;
  31730. }
  31731. }
  31732. }
  31733. }
  31734. }
  31735. else {
  31736. if (!mat.isReady(this, hardwareInstancedRendering)) {
  31737. return false;
  31738. }
  31739. }
  31740. }
  31741. // Shadows
  31742. for (var _b = 0, _c = this._lightSources; _b < _c.length; _b++) {
  31743. var light = _c[_b];
  31744. var generator = light.getShadowGenerator();
  31745. if (generator) {
  31746. for (var _d = 0, _e = this.subMeshes; _d < _e.length; _d++) {
  31747. var subMesh = _e[_d];
  31748. if (!generator.isReady(subMesh, hardwareInstancedRendering)) {
  31749. return false;
  31750. }
  31751. }
  31752. }
  31753. }
  31754. // LOD
  31755. for (var _f = 0, _g = this._LODLevels; _f < _g.length; _f++) {
  31756. var lod = _g[_f];
  31757. if (lod.mesh && !lod.mesh.isReady(hardwareInstancedRendering)) {
  31758. return false;
  31759. }
  31760. }
  31761. return true;
  31762. };
  31763. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  31764. /**
  31765. * Boolean : true if the normals aren't to be recomputed on next mesh `positions` array update.
  31766. * This property is pertinent only for updatable parametric shapes.
  31767. */
  31768. get: function () {
  31769. return this._areNormalsFrozen;
  31770. },
  31771. enumerable: true,
  31772. configurable: true
  31773. });
  31774. /**
  31775. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  31776. * It has no effect at all on other shapes.
  31777. * It prevents the mesh normals from being recomputed on next `positions` array update.
  31778. * Returns the Mesh.
  31779. */
  31780. Mesh.prototype.freezeNormals = function () {
  31781. this._areNormalsFrozen = true;
  31782. return this;
  31783. };
  31784. /**
  31785. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  31786. * It has no effect at all on other shapes.
  31787. * It reactivates the mesh normals computation if it was previously frozen.
  31788. * Returns the Mesh.
  31789. */
  31790. Mesh.prototype.unfreezeNormals = function () {
  31791. this._areNormalsFrozen = false;
  31792. return this;
  31793. };
  31794. Object.defineProperty(Mesh.prototype, "overridenInstanceCount", {
  31795. /**
  31796. * Overrides instance count. Only applicable when custom instanced InterleavedVertexBuffer are used rather than InstancedMeshs
  31797. */
  31798. set: function (count) {
  31799. this._overridenInstanceCount = count;
  31800. },
  31801. enumerable: true,
  31802. configurable: true
  31803. });
  31804. // Methods
  31805. Mesh.prototype._preActivate = function () {
  31806. var sceneRenderId = this.getScene().getRenderId();
  31807. if (this._preActivateId === sceneRenderId) {
  31808. return this;
  31809. }
  31810. this._preActivateId = sceneRenderId;
  31811. this._visibleInstances = null;
  31812. return this;
  31813. };
  31814. Mesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  31815. if (this._visibleInstances) {
  31816. this._visibleInstances.intermediateDefaultRenderId = renderId;
  31817. }
  31818. return this;
  31819. };
  31820. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  31821. if (!this._visibleInstances) {
  31822. this._visibleInstances = {};
  31823. this._visibleInstances.defaultRenderId = renderId;
  31824. this._visibleInstances.selfDefaultRenderId = this._renderId;
  31825. }
  31826. if (!this._visibleInstances[renderId]) {
  31827. this._visibleInstances[renderId] = new Array();
  31828. }
  31829. this._visibleInstances[renderId].push(instance);
  31830. return this;
  31831. };
  31832. /**
  31833. * This method recomputes and sets a new BoundingInfo to the mesh unless it is locked.
  31834. * This means the mesh underlying bounding box and sphere are recomputed.
  31835. * Returns the Mesh.
  31836. */
  31837. Mesh.prototype.refreshBoundingInfo = function () {
  31838. return this._refreshBoundingInfo(false);
  31839. };
  31840. Mesh.prototype._refreshBoundingInfo = function (applySkeleton) {
  31841. if (this._boundingInfo && this._boundingInfo.isLocked) {
  31842. return this;
  31843. }
  31844. var data = this._getPositionData(applySkeleton);
  31845. if (data) {
  31846. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  31847. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  31848. }
  31849. if (this.subMeshes) {
  31850. for (var index = 0; index < this.subMeshes.length; index++) {
  31851. this.subMeshes[index].refreshBoundingInfo();
  31852. }
  31853. }
  31854. this._updateBoundingInfo();
  31855. return this;
  31856. };
  31857. Mesh.prototype._getPositionData = function (applySkeleton) {
  31858. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  31859. if (data && applySkeleton && this.skeleton) {
  31860. data = BABYLON.Tools.Slice(data);
  31861. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  31862. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  31863. if (matricesWeightsData && matricesIndicesData) {
  31864. var needExtras = this.numBoneInfluencers > 4;
  31865. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  31866. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  31867. var skeletonMatrices = this.skeleton.getTransformMatrices(this);
  31868. var tempVector = BABYLON.Tmp.Vector3[0];
  31869. var finalMatrix = BABYLON.Tmp.Matrix[0];
  31870. var tempMatrix = BABYLON.Tmp.Matrix[1];
  31871. var matWeightIdx = 0;
  31872. for (var index = 0; index < data.length; index += 3, matWeightIdx += 4) {
  31873. finalMatrix.reset();
  31874. var inf;
  31875. var weight;
  31876. for (inf = 0; inf < 4; inf++) {
  31877. weight = matricesWeightsData[matWeightIdx + inf];
  31878. if (weight <= 0)
  31879. break;
  31880. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesData[matWeightIdx + inf] * 16), weight, tempMatrix);
  31881. finalMatrix.addToSelf(tempMatrix);
  31882. }
  31883. if (needExtras) {
  31884. for (inf = 0; inf < 4; inf++) {
  31885. weight = matricesWeightsExtraData[matWeightIdx + inf];
  31886. if (weight <= 0)
  31887. break;
  31888. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesExtraData[matWeightIdx + inf] * 16), weight, tempMatrix);
  31889. finalMatrix.addToSelf(tempMatrix);
  31890. }
  31891. }
  31892. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(data[index], data[index + 1], data[index + 2], finalMatrix, tempVector);
  31893. tempVector.toArray(data, index);
  31894. }
  31895. }
  31896. }
  31897. return data;
  31898. };
  31899. Mesh.prototype._createGlobalSubMesh = function (force) {
  31900. var totalVertices = this.getTotalVertices();
  31901. if (!totalVertices || !this.getIndices()) {
  31902. return null;
  31903. }
  31904. // Check if we need to recreate the submeshes
  31905. if (this.subMeshes && this.subMeshes.length > 0) {
  31906. var ib = this.getIndices();
  31907. if (!ib) {
  31908. return null;
  31909. }
  31910. var totalIndices = ib.length;
  31911. var needToRecreate = false;
  31912. if (force) {
  31913. needToRecreate = true;
  31914. }
  31915. else {
  31916. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  31917. var submesh = _a[_i];
  31918. if (submesh.indexStart + submesh.indexCount >= totalIndices) {
  31919. needToRecreate = true;
  31920. break;
  31921. }
  31922. if (submesh.verticesStart + submesh.verticesCount >= totalVertices) {
  31923. needToRecreate = true;
  31924. break;
  31925. }
  31926. }
  31927. }
  31928. if (!needToRecreate) {
  31929. return this.subMeshes[0];
  31930. }
  31931. }
  31932. this.releaseSubMeshes();
  31933. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  31934. };
  31935. Mesh.prototype.subdivide = function (count) {
  31936. if (count < 1) {
  31937. return;
  31938. }
  31939. var totalIndices = this.getTotalIndices();
  31940. var subdivisionSize = (totalIndices / count) | 0;
  31941. var offset = 0;
  31942. // Ensure that subdivisionSize is a multiple of 3
  31943. while (subdivisionSize % 3 !== 0) {
  31944. subdivisionSize++;
  31945. }
  31946. this.releaseSubMeshes();
  31947. for (var index = 0; index < count; index++) {
  31948. if (offset >= totalIndices) {
  31949. break;
  31950. }
  31951. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  31952. offset += subdivisionSize;
  31953. }
  31954. this.synchronizeInstances();
  31955. };
  31956. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  31957. if (updatable === void 0) { updatable = false; }
  31958. if (!this._geometry) {
  31959. var vertexData = new BABYLON.VertexData();
  31960. vertexData.set(data, kind);
  31961. var scene = this.getScene();
  31962. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  31963. }
  31964. else {
  31965. this._geometry.setVerticesData(kind, data, updatable, stride);
  31966. }
  31967. return this;
  31968. };
  31969. Mesh.prototype.markVerticesDataAsUpdatable = function (kind, updatable) {
  31970. if (updatable === void 0) { updatable = true; }
  31971. var vb = this.getVertexBuffer(kind);
  31972. if (!vb || vb.isUpdatable() === updatable) {
  31973. return;
  31974. }
  31975. this.setVerticesData(kind, this.getVerticesData(kind), updatable);
  31976. };
  31977. /**
  31978. * Sets the mesh VertexBuffer.
  31979. * Returns the Mesh.
  31980. */
  31981. Mesh.prototype.setVerticesBuffer = function (buffer) {
  31982. if (!this._geometry) {
  31983. this._geometry = BABYLON.Geometry.CreateGeometryForMesh(this);
  31984. }
  31985. this._geometry.setVerticesBuffer(buffer);
  31986. return this;
  31987. };
  31988. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  31989. if (!this._geometry) {
  31990. return this;
  31991. }
  31992. if (!makeItUnique) {
  31993. this._geometry.updateVerticesData(kind, data, updateExtends);
  31994. }
  31995. else {
  31996. this.makeGeometryUnique();
  31997. this.updateVerticesData(kind, data, updateExtends, false);
  31998. }
  31999. return this;
  32000. };
  32001. /**
  32002. * This method updates the vertex positions of an updatable mesh according to the `positionFunction` returned values.
  32003. * tuto : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#other-shapes-updatemeshpositions
  32004. * The parameter `positionFunction` is a simple JS function what is passed the mesh `positions` array. It doesn't need to return anything.
  32005. * The parameter `computeNormals` is a boolean (default true) to enable/disable the mesh normal recomputation after the vertex position update.
  32006. * Returns the Mesh.
  32007. */
  32008. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  32009. if (computeNormals === void 0) { computeNormals = true; }
  32010. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  32011. if (!positions) {
  32012. return this;
  32013. }
  32014. positionFunction(positions);
  32015. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  32016. if (computeNormals) {
  32017. var indices = this.getIndices();
  32018. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  32019. if (!normals) {
  32020. return this;
  32021. }
  32022. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  32023. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  32024. }
  32025. return this;
  32026. };
  32027. /**
  32028. * Creates a un-shared specific occurence of the geometry for the mesh.
  32029. * Returns the Mesh.
  32030. */
  32031. Mesh.prototype.makeGeometryUnique = function () {
  32032. if (!this._geometry) {
  32033. return this;
  32034. }
  32035. var oldGeometry = this._geometry;
  32036. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  32037. oldGeometry.releaseForMesh(this, true);
  32038. geometry.applyToMesh(this);
  32039. return this;
  32040. };
  32041. Mesh.prototype.setIndices = function (indices, totalVertices, updatable) {
  32042. if (totalVertices === void 0) { totalVertices = null; }
  32043. if (updatable === void 0) { updatable = false; }
  32044. if (!this._geometry) {
  32045. var vertexData = new BABYLON.VertexData();
  32046. vertexData.indices = indices;
  32047. var scene = this.getScene();
  32048. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  32049. }
  32050. else {
  32051. this._geometry.setIndices(indices, totalVertices, updatable);
  32052. }
  32053. return this;
  32054. };
  32055. /**
  32056. * Update the current index buffer
  32057. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array)
  32058. * Returns the Mesh.
  32059. */
  32060. Mesh.prototype.updateIndices = function (indices, offset) {
  32061. if (!this._geometry) {
  32062. return this;
  32063. }
  32064. this._geometry.updateIndices(indices, offset);
  32065. return this;
  32066. };
  32067. /**
  32068. * Invert the geometry to move from a right handed system to a left handed one.
  32069. * Returns the Mesh.
  32070. */
  32071. Mesh.prototype.toLeftHanded = function () {
  32072. if (!this._geometry) {
  32073. return this;
  32074. }
  32075. this._geometry.toLeftHanded();
  32076. return this;
  32077. };
  32078. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  32079. if (!this._geometry) {
  32080. return this;
  32081. }
  32082. var engine = this.getScene().getEngine();
  32083. // Wireframe
  32084. var indexToBind;
  32085. if (this._unIndexed) {
  32086. indexToBind = null;
  32087. }
  32088. else {
  32089. switch (fillMode) {
  32090. case BABYLON.Material.PointFillMode:
  32091. indexToBind = null;
  32092. break;
  32093. case BABYLON.Material.WireFrameFillMode:
  32094. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  32095. break;
  32096. default:
  32097. case BABYLON.Material.TriangleFillMode:
  32098. indexToBind = this._unIndexed ? null : this._geometry.getIndexBuffer();
  32099. break;
  32100. }
  32101. }
  32102. // VBOs
  32103. this._geometry._bind(effect, indexToBind);
  32104. return this;
  32105. };
  32106. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount, alternate) {
  32107. if (alternate === void 0) { alternate = false; }
  32108. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  32109. return this;
  32110. }
  32111. this.onBeforeDrawObservable.notifyObservers(this);
  32112. var scene = this.getScene();
  32113. var engine = scene.getEngine();
  32114. if (this._unIndexed || fillMode == BABYLON.Material.PointFillMode) {
  32115. // or triangles as points
  32116. engine.drawArraysType(fillMode, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  32117. }
  32118. else if (fillMode == BABYLON.Material.WireFrameFillMode) {
  32119. // Triangles as wireframe
  32120. engine.drawElementsType(fillMode, 0, subMesh.linesIndexCount, instancesCount);
  32121. }
  32122. else {
  32123. engine.drawElementsType(fillMode, subMesh.indexStart, subMesh.indexCount, instancesCount);
  32124. }
  32125. if (scene._isAlternateRenderingEnabled && !alternate) {
  32126. var effect = subMesh.effect || this._effectiveMaterial.getEffect();
  32127. if (!effect || !scene.activeCamera) {
  32128. return this;
  32129. }
  32130. scene._switchToAlternateCameraConfiguration(true);
  32131. this._effectiveMaterial.bindView(effect);
  32132. this._effectiveMaterial.bindViewProjection(effect);
  32133. engine.setViewport(scene.activeCamera._alternateCamera.viewport);
  32134. this._draw(subMesh, fillMode, instancesCount, true);
  32135. engine.setViewport(scene.activeCamera.viewport);
  32136. scene._switchToAlternateCameraConfiguration(false);
  32137. this._effectiveMaterial.bindView(effect);
  32138. this._effectiveMaterial.bindViewProjection(effect);
  32139. }
  32140. return this;
  32141. };
  32142. /**
  32143. * Registers for this mesh a javascript function called just before the rendering process.
  32144. * This function is passed the current mesh.
  32145. * Return the Mesh.
  32146. */
  32147. Mesh.prototype.registerBeforeRender = function (func) {
  32148. this.onBeforeRenderObservable.add(func);
  32149. return this;
  32150. };
  32151. /**
  32152. * Disposes a previously registered javascript function called before the rendering.
  32153. * This function is passed the current mesh.
  32154. * Returns the Mesh.
  32155. */
  32156. Mesh.prototype.unregisterBeforeRender = function (func) {
  32157. this.onBeforeRenderObservable.removeCallback(func);
  32158. return this;
  32159. };
  32160. /**
  32161. * Registers for this mesh a javascript function called just after the rendering is complete.
  32162. * This function is passed the current mesh.
  32163. * Returns the Mesh.
  32164. */
  32165. Mesh.prototype.registerAfterRender = function (func) {
  32166. this.onAfterRenderObservable.add(func);
  32167. return this;
  32168. };
  32169. /**
  32170. * Disposes a previously registered javascript function called after the rendering.
  32171. * This function is passed the current mesh.
  32172. * Return the Mesh.
  32173. */
  32174. Mesh.prototype.unregisterAfterRender = function (func) {
  32175. this.onAfterRenderObservable.removeCallback(func);
  32176. return this;
  32177. };
  32178. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  32179. var scene = this.getScene();
  32180. this._batchCache.mustReturn = false;
  32181. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  32182. this._batchCache.visibleInstances[subMeshId] = null;
  32183. if (this._visibleInstances) {
  32184. var currentRenderId = scene.getRenderId();
  32185. var defaultRenderId = (scene._isInIntermediateRendering() ? this._visibleInstances.intermediateDefaultRenderId : this._visibleInstances.defaultRenderId);
  32186. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  32187. var selfRenderId = this._renderId;
  32188. if (!this._batchCache.visibleInstances[subMeshId] && defaultRenderId) {
  32189. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[defaultRenderId];
  32190. currentRenderId = Math.max(defaultRenderId, currentRenderId);
  32191. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  32192. }
  32193. var visibleInstancesForSubMesh = this._batchCache.visibleInstances[subMeshId];
  32194. if (visibleInstancesForSubMesh && visibleInstancesForSubMesh.length) {
  32195. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  32196. this._batchCache.mustReturn = true;
  32197. return this._batchCache;
  32198. }
  32199. if (currentRenderId !== selfRenderId) {
  32200. this._batchCache.renderSelf[subMeshId] = false;
  32201. }
  32202. }
  32203. this._renderIdForInstances[subMeshId] = currentRenderId;
  32204. }
  32205. return this._batchCache;
  32206. };
  32207. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  32208. var visibleInstances = batch.visibleInstances[subMesh._id];
  32209. if (!visibleInstances) {
  32210. return this;
  32211. }
  32212. var matricesCount = visibleInstances.length + 1;
  32213. var bufferSize = matricesCount * 16 * 4;
  32214. var currentInstancesBufferSize = this._instancesBufferSize;
  32215. var instancesBuffer = this._instancesBuffer;
  32216. while (this._instancesBufferSize < bufferSize) {
  32217. this._instancesBufferSize *= 2;
  32218. }
  32219. if (!this._instancesData || currentInstancesBufferSize != this._instancesBufferSize) {
  32220. this._instancesData = new Float32Array(this._instancesBufferSize / 4);
  32221. }
  32222. var offset = 0;
  32223. var instancesCount = 0;
  32224. var world = this.getWorldMatrix();
  32225. if (batch.renderSelf[subMesh._id]) {
  32226. world.copyToArray(this._instancesData, offset);
  32227. offset += 16;
  32228. instancesCount++;
  32229. }
  32230. if (visibleInstances) {
  32231. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  32232. var instance = visibleInstances[instanceIndex];
  32233. instance.getWorldMatrix().copyToArray(this._instancesData, offset);
  32234. offset += 16;
  32235. instancesCount++;
  32236. }
  32237. }
  32238. if (!instancesBuffer || currentInstancesBufferSize != this._instancesBufferSize) {
  32239. if (instancesBuffer) {
  32240. instancesBuffer.dispose();
  32241. }
  32242. instancesBuffer = new BABYLON.Buffer(engine, this._instancesData, true, 16, false, true);
  32243. this._instancesBuffer = instancesBuffer;
  32244. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world0", 0, 4));
  32245. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world1", 4, 4));
  32246. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world2", 8, 4));
  32247. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world3", 12, 4));
  32248. }
  32249. else {
  32250. instancesBuffer.updateDirectly(this._instancesData, 0, instancesCount);
  32251. }
  32252. this._bind(subMesh, effect, fillMode);
  32253. this._draw(subMesh, fillMode, instancesCount);
  32254. engine.unbindInstanceAttributes();
  32255. return this;
  32256. };
  32257. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw, effectiveMaterial) {
  32258. var scene = this.getScene();
  32259. var engine = scene.getEngine();
  32260. if (hardwareInstancedRendering) {
  32261. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  32262. }
  32263. else {
  32264. if (batch.renderSelf[subMesh._id]) {
  32265. // Draw
  32266. if (onBeforeDraw) {
  32267. onBeforeDraw(false, this.getWorldMatrix(), effectiveMaterial);
  32268. }
  32269. this._draw(subMesh, fillMode, this._overridenInstanceCount);
  32270. }
  32271. var visibleInstancesForSubMesh = batch.visibleInstances[subMesh._id];
  32272. if (visibleInstancesForSubMesh) {
  32273. for (var instanceIndex = 0; instanceIndex < visibleInstancesForSubMesh.length; instanceIndex++) {
  32274. var instance = visibleInstancesForSubMesh[instanceIndex];
  32275. // World
  32276. var world = instance.getWorldMatrix();
  32277. if (onBeforeDraw) {
  32278. onBeforeDraw(true, world, effectiveMaterial);
  32279. }
  32280. // Draw
  32281. this._draw(subMesh, fillMode);
  32282. }
  32283. }
  32284. }
  32285. return this;
  32286. };
  32287. /**
  32288. * Triggers the draw call for the mesh.
  32289. * Usually, you don't need to call this method by your own because the mesh rendering is handled by the scene rendering manager.
  32290. * Returns the Mesh.
  32291. */
  32292. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  32293. this._checkOcclusionQuery();
  32294. if (this._isOccluded) {
  32295. return this;
  32296. }
  32297. var scene = this.getScene();
  32298. // Managing instances
  32299. var batch = this._getInstancesRenderList(subMesh._id);
  32300. if (batch.mustReturn) {
  32301. return this;
  32302. }
  32303. // Checking geometry state
  32304. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  32305. return this;
  32306. }
  32307. this.onBeforeRenderObservable.notifyObservers(this);
  32308. var engine = scene.getEngine();
  32309. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  32310. // Material
  32311. var material = subMesh.getMaterial();
  32312. if (!material) {
  32313. return this;
  32314. }
  32315. this._effectiveMaterial = material;
  32316. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  32317. if (!this._effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  32318. return this;
  32319. }
  32320. }
  32321. else if (!this._effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  32322. return this;
  32323. }
  32324. // Alpha mode
  32325. if (enableAlphaMode) {
  32326. engine.setAlphaMode(this._effectiveMaterial.alphaMode);
  32327. }
  32328. // Outline - step 1
  32329. var savedDepthWrite = engine.getDepthWrite();
  32330. if (this.renderOutline) {
  32331. engine.setDepthWrite(false);
  32332. scene.getOutlineRenderer().render(subMesh, batch);
  32333. engine.setDepthWrite(savedDepthWrite);
  32334. }
  32335. var effect;
  32336. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  32337. effect = subMesh.effect;
  32338. }
  32339. else {
  32340. effect = this._effectiveMaterial.getEffect();
  32341. }
  32342. if (!effect) {
  32343. return this;
  32344. }
  32345. var sideOrientation = this.overrideMaterialSideOrientation;
  32346. if (sideOrientation == null) {
  32347. sideOrientation = this._effectiveMaterial.sideOrientation;
  32348. if (this._getWorldMatrixDeterminant() < 0) {
  32349. sideOrientation = (sideOrientation === BABYLON.Material.ClockWiseSideOrientation ? BABYLON.Material.CounterClockWiseSideOrientation : BABYLON.Material.ClockWiseSideOrientation);
  32350. }
  32351. }
  32352. var reverse = this._effectiveMaterial._preBind(effect, sideOrientation);
  32353. if (this._effectiveMaterial.forceDepthWrite) {
  32354. engine.setDepthWrite(true);
  32355. }
  32356. // Bind
  32357. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : this._effectiveMaterial.fillMode);
  32358. if (!hardwareInstancedRendering) { // Binding will be done later because we need to add more info to the VB
  32359. this._bind(subMesh, effect, fillMode);
  32360. }
  32361. var world = this.getWorldMatrix();
  32362. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  32363. this._effectiveMaterial.bindForSubMesh(world, this, subMesh);
  32364. }
  32365. else {
  32366. this._effectiveMaterial.bind(world, this);
  32367. }
  32368. if (!this._effectiveMaterial.backFaceCulling && this._effectiveMaterial.separateCullingPass) {
  32369. engine.setState(true, this._effectiveMaterial.zOffset, false, !reverse);
  32370. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  32371. engine.setState(true, this._effectiveMaterial.zOffset, false, reverse);
  32372. }
  32373. // Draw
  32374. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  32375. // Unbind
  32376. this._effectiveMaterial.unbind();
  32377. // Outline - step 2
  32378. if (this.renderOutline && savedDepthWrite) {
  32379. engine.setDepthWrite(true);
  32380. engine.setColorWrite(false);
  32381. scene.getOutlineRenderer().render(subMesh, batch);
  32382. engine.setColorWrite(true);
  32383. }
  32384. // Overlay
  32385. if (this.renderOverlay) {
  32386. var currentMode = engine.getAlphaMode();
  32387. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  32388. scene.getOutlineRenderer().render(subMesh, batch, true);
  32389. engine.setAlphaMode(currentMode);
  32390. }
  32391. this.onAfterRenderObservable.notifyObservers(this);
  32392. return this;
  32393. };
  32394. Mesh.prototype._onBeforeDraw = function (isInstance, world, effectiveMaterial) {
  32395. if (isInstance && effectiveMaterial) {
  32396. effectiveMaterial.bindOnlyWorldMatrix(world);
  32397. }
  32398. };
  32399. /**
  32400. * Returns an array populated with ParticleSystem objects whose the mesh is the emitter.
  32401. */
  32402. Mesh.prototype.getEmittedParticleSystems = function () {
  32403. var results = new Array();
  32404. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  32405. var particleSystem = this.getScene().particleSystems[index];
  32406. if (particleSystem.emitter === this) {
  32407. results.push(particleSystem);
  32408. }
  32409. }
  32410. return results;
  32411. };
  32412. /**
  32413. * Returns an array populated with ParticleSystem objects whose the mesh or its children are the emitter.
  32414. */
  32415. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  32416. var results = new Array();
  32417. var descendants = this.getDescendants();
  32418. descendants.push(this);
  32419. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  32420. var particleSystem = this.getScene().particleSystems[index];
  32421. var emitter = particleSystem.emitter;
  32422. if (emitter.position && descendants.indexOf(emitter) !== -1) {
  32423. results.push(particleSystem);
  32424. }
  32425. }
  32426. return results;
  32427. };
  32428. /**
  32429. * Normalize matrix weights so that all vertices have a total weight set to 1
  32430. */
  32431. Mesh.prototype.cleanMatrixWeights = function () {
  32432. var epsilon = 1e-3;
  32433. var noInfluenceBoneIndex = 0.0;
  32434. if (this.skeleton) {
  32435. noInfluenceBoneIndex = this.skeleton.bones.length;
  32436. }
  32437. else {
  32438. return;
  32439. }
  32440. var matricesIndices = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  32441. var matricesIndicesExtra = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  32442. var matricesWeights = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  32443. var matricesWeightsExtra = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  32444. var influencers = this.numBoneInfluencers;
  32445. var size = matricesWeights.length;
  32446. for (var i = 0; i < size; i += 4) {
  32447. var weight = 0.0;
  32448. var firstZeroWeight = -1;
  32449. for (var j = 0; j < 4; j++) {
  32450. var w = matricesWeights[i + j];
  32451. weight += w;
  32452. if (w < epsilon && firstZeroWeight < 0) {
  32453. firstZeroWeight = j;
  32454. }
  32455. }
  32456. if (matricesWeightsExtra) {
  32457. for (var j = 0; j < 4; j++) {
  32458. var w = matricesWeightsExtra[i + j];
  32459. weight += w;
  32460. if (w < epsilon && firstZeroWeight < 0) {
  32461. firstZeroWeight = j + 4;
  32462. }
  32463. }
  32464. }
  32465. if (firstZeroWeight < 0 || firstZeroWeight > (influencers - 1)) {
  32466. firstZeroWeight = influencers - 1;
  32467. }
  32468. if (weight > epsilon) {
  32469. var mweight = 1.0 / weight;
  32470. for (var j = 0; j < 4; j++) {
  32471. matricesWeights[i + j] *= mweight;
  32472. }
  32473. if (matricesWeightsExtra) {
  32474. for (var j = 0; j < 4; j++) {
  32475. matricesWeightsExtra[i + j] *= mweight;
  32476. }
  32477. }
  32478. }
  32479. else {
  32480. if (firstZeroWeight >= 4) {
  32481. matricesWeightsExtra[i + firstZeroWeight - 4] = 1.0 - weight;
  32482. matricesIndicesExtra[i + firstZeroWeight - 4] = noInfluenceBoneIndex;
  32483. }
  32484. else {
  32485. matricesWeights[i + firstZeroWeight] = 1.0 - weight;
  32486. matricesIndices[i + firstZeroWeight] = noInfluenceBoneIndex;
  32487. }
  32488. }
  32489. }
  32490. this.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndices);
  32491. if (matricesIndicesExtra) {
  32492. this.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, matricesIndicesExtra);
  32493. }
  32494. this.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeights);
  32495. if (matricesWeightsExtra) {
  32496. this.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, matricesWeightsExtra);
  32497. }
  32498. };
  32499. Mesh.prototype._checkDelayState = function () {
  32500. var scene = this.getScene();
  32501. if (this._geometry) {
  32502. this._geometry.load(scene);
  32503. }
  32504. else if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  32505. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  32506. this._queueLoad(scene);
  32507. }
  32508. return this;
  32509. };
  32510. Mesh.prototype._queueLoad = function (scene) {
  32511. var _this = this;
  32512. scene._addPendingData(this);
  32513. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  32514. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  32515. if (data instanceof ArrayBuffer) {
  32516. _this._delayLoadingFunction(data, _this);
  32517. }
  32518. else {
  32519. _this._delayLoadingFunction(JSON.parse(data), _this);
  32520. }
  32521. _this.instances.forEach(function (instance) {
  32522. instance._syncSubMeshes();
  32523. });
  32524. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  32525. scene._removePendingData(_this);
  32526. }, function () { }, scene.database, getBinaryData);
  32527. return this;
  32528. };
  32529. /**
  32530. * Boolean, true is the mesh in the frustum defined by the Plane objects from the `frustumPlanes` array parameter.
  32531. */
  32532. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  32533. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  32534. return false;
  32535. }
  32536. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  32537. return false;
  32538. }
  32539. this._checkDelayState();
  32540. return true;
  32541. };
  32542. /**
  32543. * Sets the mesh material by the material or multiMaterial `id` property.
  32544. * The material `id` is a string identifying the material or the multiMaterial.
  32545. * This method returns the Mesh.
  32546. */
  32547. Mesh.prototype.setMaterialByID = function (id) {
  32548. var materials = this.getScene().materials;
  32549. var index;
  32550. for (index = materials.length - 1; index > -1; index--) {
  32551. if (materials[index].id === id) {
  32552. this.material = materials[index];
  32553. return this;
  32554. }
  32555. }
  32556. // Multi
  32557. var multiMaterials = this.getScene().multiMaterials;
  32558. for (index = multiMaterials.length - 1; index > -1; index--) {
  32559. if (multiMaterials[index].id === id) {
  32560. this.material = multiMaterials[index];
  32561. return this;
  32562. }
  32563. }
  32564. return this;
  32565. };
  32566. /**
  32567. * Returns as a new array populated with the mesh material and/or skeleton, if any.
  32568. */
  32569. Mesh.prototype.getAnimatables = function () {
  32570. var results = new Array();
  32571. if (this.material) {
  32572. results.push(this.material);
  32573. }
  32574. if (this.skeleton) {
  32575. results.push(this.skeleton);
  32576. }
  32577. return results;
  32578. };
  32579. /**
  32580. * Modifies the mesh geometry according to the passed transformation matrix.
  32581. * This method returns nothing but it really modifies the mesh even if it's originally not set as updatable.
  32582. * The mesh normals are modified accordingly the same transformation.
  32583. * tuto : http://doc.babylonjs.com/resources/baking_transformations
  32584. * Note that, under the hood, this method sets a new VertexBuffer each call.
  32585. * Returns the Mesh.
  32586. */
  32587. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  32588. // Position
  32589. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  32590. return this;
  32591. }
  32592. var submeshes = this.subMeshes.splice(0);
  32593. this._resetPointsArrayCache();
  32594. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  32595. var temp = new Array();
  32596. var index;
  32597. for (index = 0; index < data.length; index += 3) {
  32598. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  32599. }
  32600. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  32601. // Normals
  32602. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  32603. return this;
  32604. }
  32605. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  32606. temp = [];
  32607. for (index = 0; index < data.length; index += 3) {
  32608. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  32609. }
  32610. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  32611. // flip faces?
  32612. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  32613. this.flipFaces();
  32614. }
  32615. // Restore submeshes
  32616. this.releaseSubMeshes();
  32617. this.subMeshes = submeshes;
  32618. return this;
  32619. };
  32620. /**
  32621. * Modifies the mesh geometry according to its own current World Matrix.
  32622. * The mesh World Matrix is then reset.
  32623. * This method returns nothing but really modifies the mesh even if it's originally not set as updatable.
  32624. * tuto : tuto : http://doc.babylonjs.com/resources/baking_transformations
  32625. * Note that, under the hood, this method sets a new VertexBuffer each call.
  32626. * Returns the Mesh.
  32627. */
  32628. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  32629. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  32630. this.scaling.copyFromFloats(1, 1, 1);
  32631. this.position.copyFromFloats(0, 0, 0);
  32632. this.rotation.copyFromFloats(0, 0, 0);
  32633. //only if quaternion is already set
  32634. if (this.rotationQuaternion) {
  32635. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  32636. }
  32637. this._worldMatrix = BABYLON.Matrix.Identity();
  32638. return this;
  32639. };
  32640. Object.defineProperty(Mesh.prototype, "_positions", {
  32641. // Cache
  32642. get: function () {
  32643. if (this._geometry) {
  32644. return this._geometry._positions;
  32645. }
  32646. return null;
  32647. },
  32648. enumerable: true,
  32649. configurable: true
  32650. });
  32651. Mesh.prototype._resetPointsArrayCache = function () {
  32652. if (this._geometry) {
  32653. this._geometry._resetPointsArrayCache();
  32654. }
  32655. return this;
  32656. };
  32657. Mesh.prototype._generatePointsArray = function () {
  32658. if (this._geometry) {
  32659. return this._geometry._generatePointsArray();
  32660. }
  32661. return false;
  32662. };
  32663. /**
  32664. * Returns a new Mesh object generated from the current mesh properties.
  32665. * This method must not get confused with createInstance().
  32666. * The parameter `name` is a string, the name given to the new mesh.
  32667. * The optional parameter `newParent` can be any Node object (default `null`).
  32668. * The optional parameter `doNotCloneChildren` (default `false`) allows/denies the recursive cloning of the original mesh children if any.
  32669. * The parameter `clonePhysicsImpostor` (default `true`) allows/denies the cloning in the same time of the original mesh `body` used by the physics engine, if any.
  32670. */
  32671. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren, clonePhysicsImpostor) {
  32672. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  32673. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren, clonePhysicsImpostor);
  32674. };
  32675. /**
  32676. * Releases resources associated with this mesh.
  32677. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  32678. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  32679. */
  32680. Mesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  32681. var _this = this;
  32682. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  32683. this.morphTargetManager = null;
  32684. if (this._geometry) {
  32685. this._geometry.releaseForMesh(this, true);
  32686. }
  32687. // Sources
  32688. var meshes = this.getScene().meshes;
  32689. meshes.forEach(function (abstractMesh) {
  32690. var mesh = abstractMesh;
  32691. if (mesh._source && mesh._source === _this) {
  32692. mesh._source = null;
  32693. }
  32694. });
  32695. this._source = null;
  32696. // Instances
  32697. if (this._instancesBuffer) {
  32698. this._instancesBuffer.dispose();
  32699. this._instancesBuffer = null;
  32700. }
  32701. while (this.instances.length) {
  32702. this.instances[0].dispose();
  32703. }
  32704. // Effect layers.
  32705. var effectLayers = this.getScene().effectLayers;
  32706. for (var i = 0; i < effectLayers.length; i++) {
  32707. var effectLayer = effectLayers[i];
  32708. if (effectLayer) {
  32709. effectLayer._disposeMesh(this);
  32710. }
  32711. }
  32712. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  32713. };
  32714. /**
  32715. * Modifies the mesh geometry according to a displacement map.
  32716. * 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.
  32717. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  32718. * This method returns nothing.
  32719. * The parameter `url` is a string, the URL from the image file is to be downloaded.
  32720. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  32721. * The parameter `onSuccess` is an optional Javascript function to be called just after the mesh is modified. It is passed the modified mesh and must return nothing.
  32722. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  32723. * The parameter `uvScale` is an optional vector2 used to scale UV.
  32724. *
  32725. * Returns the Mesh.
  32726. */
  32727. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess, uvOffset, uvScale) {
  32728. var _this = this;
  32729. var scene = this.getScene();
  32730. var onload = function (img) {
  32731. // Getting height map data
  32732. var canvas = document.createElement("canvas");
  32733. var context = canvas.getContext("2d");
  32734. var heightMapWidth = img.width;
  32735. var heightMapHeight = img.height;
  32736. canvas.width = heightMapWidth;
  32737. canvas.height = heightMapHeight;
  32738. context.drawImage(img, 0, 0);
  32739. // Create VertexData from map data
  32740. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  32741. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  32742. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale);
  32743. //execute success callback, if set
  32744. if (onSuccess) {
  32745. onSuccess(_this);
  32746. }
  32747. };
  32748. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  32749. return this;
  32750. };
  32751. /**
  32752. * Modifies the mesh geometry according to a displacementMap buffer.
  32753. * 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.
  32754. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  32755. * This method returns nothing.
  32756. * The parameter `buffer` is a `Uint8Array` buffer containing series of `Uint8` lower than 255, the red, green, blue and alpha values of each successive pixel.
  32757. * The parameters `heightMapWidth` and `heightMapHeight` are positive integers to set the width and height of the buffer image.
  32758. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  32759. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  32760. * The parameter `uvScale` is an optional vector2 used to scale UV.
  32761. *
  32762. * Returns the Mesh.
  32763. */
  32764. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale) {
  32765. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  32766. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  32767. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  32768. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  32769. return this;
  32770. }
  32771. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  32772. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  32773. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  32774. var position = BABYLON.Vector3.Zero();
  32775. var normal = BABYLON.Vector3.Zero();
  32776. var uv = BABYLON.Vector2.Zero();
  32777. uvOffset = uvOffset || BABYLON.Vector2.Zero();
  32778. uvScale = uvScale || new BABYLON.Vector2(1, 1);
  32779. for (var index = 0; index < positions.length; index += 3) {
  32780. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  32781. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  32782. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  32783. // Compute height
  32784. var u = ((Math.abs(uv.x * uvScale.x + uvOffset.x) * heightMapWidth) % heightMapWidth) | 0;
  32785. var v = ((Math.abs(uv.y * uvScale.y + uvOffset.y) * heightMapHeight) % heightMapHeight) | 0;
  32786. var pos = (u + v * heightMapWidth) * 4;
  32787. var r = buffer[pos] / 255.0;
  32788. var g = buffer[pos + 1] / 255.0;
  32789. var b = buffer[pos + 2] / 255.0;
  32790. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  32791. normal.normalize();
  32792. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  32793. position = position.add(normal);
  32794. position.toArray(positions, index);
  32795. }
  32796. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  32797. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  32798. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  32799. return this;
  32800. };
  32801. /**
  32802. * Modify the mesh to get a flat shading rendering.
  32803. * This means each mesh facet will then have its own normals. Usually new vertices are added in the mesh geometry to get this result.
  32804. * This method returns the Mesh.
  32805. * Warning : the mesh is really modified even if not set originally as updatable and, under the hood, a new VertexBuffer is allocated.
  32806. */
  32807. Mesh.prototype.convertToFlatShadedMesh = function () {
  32808. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  32809. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  32810. var kinds = this.getVerticesDataKinds();
  32811. var vbs = {};
  32812. var data = {};
  32813. var newdata = {};
  32814. var updatableNormals = false;
  32815. var kindIndex;
  32816. var kind;
  32817. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32818. kind = kinds[kindIndex];
  32819. var vertexBuffer = this.getVertexBuffer(kind);
  32820. if (kind === BABYLON.VertexBuffer.NormalKind) {
  32821. updatableNormals = vertexBuffer.isUpdatable();
  32822. kinds.splice(kindIndex, 1);
  32823. kindIndex--;
  32824. continue;
  32825. }
  32826. vbs[kind] = vertexBuffer;
  32827. data[kind] = vbs[kind].getData();
  32828. newdata[kind] = [];
  32829. }
  32830. // Save previous submeshes
  32831. var previousSubmeshes = this.subMeshes.slice(0);
  32832. var indices = this.getIndices();
  32833. var totalIndices = this.getTotalIndices();
  32834. // Generating unique vertices per face
  32835. var index;
  32836. for (index = 0; index < totalIndices; index++) {
  32837. var vertexIndex = indices[index];
  32838. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32839. kind = kinds[kindIndex];
  32840. var stride = vbs[kind].getStrideSize();
  32841. for (var offset = 0; offset < stride; offset++) {
  32842. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  32843. }
  32844. }
  32845. }
  32846. // Updating faces & normal
  32847. var normals = [];
  32848. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  32849. for (index = 0; index < totalIndices; index += 3) {
  32850. indices[index] = index;
  32851. indices[index + 1] = index + 1;
  32852. indices[index + 2] = index + 2;
  32853. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  32854. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  32855. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  32856. var p1p2 = p1.subtract(p2);
  32857. var p3p2 = p3.subtract(p2);
  32858. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  32859. // Store same normals for every vertex
  32860. for (var localIndex = 0; localIndex < 3; localIndex++) {
  32861. normals.push(normal.x);
  32862. normals.push(normal.y);
  32863. normals.push(normal.z);
  32864. }
  32865. }
  32866. this.setIndices(indices);
  32867. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  32868. // Updating vertex buffers
  32869. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32870. kind = kinds[kindIndex];
  32871. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  32872. }
  32873. // Updating submeshes
  32874. this.releaseSubMeshes();
  32875. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  32876. var previousOne = previousSubmeshes[submeshIndex];
  32877. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  32878. }
  32879. this.synchronizeInstances();
  32880. return this;
  32881. };
  32882. /**
  32883. * This method removes all the mesh indices and add new vertices (duplication) in order to unfold facets into buffers.
  32884. * In other words, more vertices, no more indices and a single bigger VBO.
  32885. * The mesh is really modified even if not set originally as updatable. Under the hood, a new VertexBuffer is allocated.
  32886. * Returns the Mesh.
  32887. */
  32888. Mesh.prototype.convertToUnIndexedMesh = function () {
  32889. /// <summary>Remove indices by unfolding faces into buffers</summary>
  32890. /// <summary>Warning: This implies adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  32891. var kinds = this.getVerticesDataKinds();
  32892. var vbs = {};
  32893. var data = {};
  32894. var newdata = {};
  32895. var kindIndex;
  32896. var kind;
  32897. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32898. kind = kinds[kindIndex];
  32899. var vertexBuffer = this.getVertexBuffer(kind);
  32900. vbs[kind] = vertexBuffer;
  32901. data[kind] = vbs[kind].getData();
  32902. newdata[kind] = [];
  32903. }
  32904. // Save previous submeshes
  32905. var previousSubmeshes = this.subMeshes.slice(0);
  32906. var indices = this.getIndices();
  32907. var totalIndices = this.getTotalIndices();
  32908. // Generating unique vertices per face
  32909. var index;
  32910. for (index = 0; index < totalIndices; index++) {
  32911. var vertexIndex = indices[index];
  32912. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32913. kind = kinds[kindIndex];
  32914. var stride = vbs[kind].getStrideSize();
  32915. for (var offset = 0; offset < stride; offset++) {
  32916. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  32917. }
  32918. }
  32919. }
  32920. // Updating indices
  32921. for (index = 0; index < totalIndices; index += 3) {
  32922. indices[index] = index;
  32923. indices[index + 1] = index + 1;
  32924. indices[index + 2] = index + 2;
  32925. }
  32926. this.setIndices(indices);
  32927. // Updating vertex buffers
  32928. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32929. kind = kinds[kindIndex];
  32930. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  32931. }
  32932. // Updating submeshes
  32933. this.releaseSubMeshes();
  32934. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  32935. var previousOne = previousSubmeshes[submeshIndex];
  32936. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  32937. }
  32938. this._unIndexed = true;
  32939. this.synchronizeInstances();
  32940. return this;
  32941. };
  32942. /**
  32943. * Inverses facet orientations and inverts also the normals with `flipNormals` (default `false`) if true.
  32944. * This method returns the Mesh.
  32945. * Warning : the mesh is really modified even if not set originally as updatable. A new VertexBuffer is created under the hood each call.
  32946. */
  32947. Mesh.prototype.flipFaces = function (flipNormals) {
  32948. if (flipNormals === void 0) { flipNormals = false; }
  32949. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  32950. var i;
  32951. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind) && vertex_data.normals) {
  32952. for (i = 0; i < vertex_data.normals.length; i++) {
  32953. vertex_data.normals[i] *= -1;
  32954. }
  32955. }
  32956. if (vertex_data.indices) {
  32957. var temp;
  32958. for (i = 0; i < vertex_data.indices.length; i += 3) {
  32959. // reassign indices
  32960. temp = vertex_data.indices[i + 1];
  32961. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  32962. vertex_data.indices[i + 2] = temp;
  32963. }
  32964. }
  32965. vertex_data.applyToMesh(this);
  32966. return this;
  32967. };
  32968. // Instances
  32969. /**
  32970. * Creates a new InstancedMesh object from the mesh model.
  32971. * An instance shares the same properties and the same material than its model.
  32972. * Only these properties of each instance can then be set individually :
  32973. * - position
  32974. * - rotation
  32975. * - rotationQuaternion
  32976. * - setPivotMatrix
  32977. * - scaling
  32978. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_Instances
  32979. * Warning : this method is not supported for Line mesh and LineSystem
  32980. */
  32981. Mesh.prototype.createInstance = function (name) {
  32982. return new BABYLON.InstancedMesh(name, this);
  32983. };
  32984. /**
  32985. * Synchronises all the mesh instance submeshes to the current mesh submeshes, if any.
  32986. * After this call, all the mesh instances have the same submeshes than the current mesh.
  32987. * This method returns the Mesh.
  32988. */
  32989. Mesh.prototype.synchronizeInstances = function () {
  32990. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  32991. var instance = this.instances[instanceIndex];
  32992. instance._syncSubMeshes();
  32993. }
  32994. return this;
  32995. };
  32996. /**
  32997. * Simplify the mesh according to the given array of settings.
  32998. * Function will return immediately and will simplify async. It returns the Mesh.
  32999. * @param settings a collection of simplification settings.
  33000. * @param parallelProcessing should all levels calculate parallel or one after the other.
  33001. * @param type the type of simplification to run.
  33002. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  33003. */
  33004. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  33005. if (parallelProcessing === void 0) { parallelProcessing = true; }
  33006. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  33007. this.getScene().simplificationQueue.addTask({
  33008. settings: settings,
  33009. parallelProcessing: parallelProcessing,
  33010. mesh: this,
  33011. simplificationType: simplificationType,
  33012. successCallback: successCallback
  33013. });
  33014. return this;
  33015. };
  33016. /**
  33017. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  33018. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  33019. * This should be used together with the simplification to avoid disappearing triangles.
  33020. * Returns the Mesh.
  33021. * @param successCallback an optional success callback to be called after the optimization finished.
  33022. */
  33023. Mesh.prototype.optimizeIndices = function (successCallback) {
  33024. var _this = this;
  33025. var indices = this.getIndices();
  33026. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  33027. if (!positions || !indices) {
  33028. return this;
  33029. }
  33030. var vectorPositions = new Array();
  33031. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  33032. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  33033. }
  33034. var dupes = new Array();
  33035. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  33036. var realPos = vectorPositions.length - 1 - iteration;
  33037. var testedPosition = vectorPositions[realPos];
  33038. for (var j = 0; j < realPos; ++j) {
  33039. var againstPosition = vectorPositions[j];
  33040. if (testedPosition.equals(againstPosition)) {
  33041. dupes[realPos] = j;
  33042. break;
  33043. }
  33044. }
  33045. }, function () {
  33046. for (var i = 0; i < indices.length; ++i) {
  33047. indices[i] = dupes[indices[i]] || indices[i];
  33048. }
  33049. //indices are now reordered
  33050. var originalSubMeshes = _this.subMeshes.slice(0);
  33051. _this.setIndices(indices);
  33052. _this.subMeshes = originalSubMeshes;
  33053. if (successCallback) {
  33054. successCallback(_this);
  33055. }
  33056. });
  33057. return this;
  33058. };
  33059. Mesh.prototype.serialize = function (serializationObject) {
  33060. serializationObject.name = this.name;
  33061. serializationObject.id = this.id;
  33062. serializationObject.type = this.getClassName();
  33063. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  33064. serializationObject.tags = BABYLON.Tags.GetTags(this);
  33065. }
  33066. serializationObject.position = this.position.asArray();
  33067. if (this.rotationQuaternion) {
  33068. serializationObject.rotationQuaternion = this.rotationQuaternion.asArray();
  33069. }
  33070. else if (this.rotation) {
  33071. serializationObject.rotation = this.rotation.asArray();
  33072. }
  33073. serializationObject.scaling = this.scaling.asArray();
  33074. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  33075. serializationObject.isEnabled = this.isEnabled(false);
  33076. serializationObject.isVisible = this.isVisible;
  33077. serializationObject.infiniteDistance = this.infiniteDistance;
  33078. serializationObject.pickable = this.isPickable;
  33079. serializationObject.receiveShadows = this.receiveShadows;
  33080. serializationObject.billboardMode = this.billboardMode;
  33081. serializationObject.visibility = this.visibility;
  33082. serializationObject.checkCollisions = this.checkCollisions;
  33083. serializationObject.isBlocker = this.isBlocker;
  33084. // Parent
  33085. if (this.parent) {
  33086. serializationObject.parentId = this.parent.id;
  33087. }
  33088. // Geometry
  33089. serializationObject.isUnIndexed = this.isUnIndexed;
  33090. var geometry = this._geometry;
  33091. if (geometry) {
  33092. var geometryId = geometry.id;
  33093. serializationObject.geometryId = geometryId;
  33094. // SubMeshes
  33095. serializationObject.subMeshes = [];
  33096. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  33097. var subMesh = this.subMeshes[subIndex];
  33098. serializationObject.subMeshes.push({
  33099. materialIndex: subMesh.materialIndex,
  33100. verticesStart: subMesh.verticesStart,
  33101. verticesCount: subMesh.verticesCount,
  33102. indexStart: subMesh.indexStart,
  33103. indexCount: subMesh.indexCount
  33104. });
  33105. }
  33106. }
  33107. // Material
  33108. if (this.material) {
  33109. serializationObject.materialId = this.material.id;
  33110. }
  33111. else {
  33112. this.material = null;
  33113. }
  33114. // Morph targets
  33115. if (this.morphTargetManager) {
  33116. serializationObject.morphTargetManagerId = this.morphTargetManager.uniqueId;
  33117. }
  33118. // Skeleton
  33119. if (this.skeleton) {
  33120. serializationObject.skeletonId = this.skeleton.id;
  33121. }
  33122. // Physics
  33123. //TODO implement correct serialization for physics impostors.
  33124. var impostor = this.getPhysicsImpostor();
  33125. if (impostor) {
  33126. serializationObject.physicsMass = impostor.getParam("mass");
  33127. serializationObject.physicsFriction = impostor.getParam("friction");
  33128. serializationObject.physicsRestitution = impostor.getParam("mass");
  33129. serializationObject.physicsImpostor = impostor.type;
  33130. }
  33131. // Metadata
  33132. if (this.metadata) {
  33133. serializationObject.metadata = this.metadata;
  33134. }
  33135. // Instances
  33136. serializationObject.instances = [];
  33137. for (var index = 0; index < this.instances.length; index++) {
  33138. var instance = this.instances[index];
  33139. var serializationInstance = {
  33140. name: instance.name,
  33141. id: instance.id,
  33142. position: instance.position.asArray(),
  33143. scaling: instance.scaling.asArray()
  33144. };
  33145. if (instance.rotationQuaternion) {
  33146. serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();
  33147. }
  33148. else if (instance.rotation) {
  33149. serializationInstance.rotation = instance.rotation.asArray();
  33150. }
  33151. serializationObject.instances.push(serializationInstance);
  33152. // Animations
  33153. BABYLON.Animation.AppendSerializedAnimations(instance, serializationInstance);
  33154. serializationInstance.ranges = instance.serializeAnimationRanges();
  33155. }
  33156. //
  33157. // Animations
  33158. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  33159. serializationObject.ranges = this.serializeAnimationRanges();
  33160. // Layer mask
  33161. serializationObject.layerMask = this.layerMask;
  33162. // Alpha
  33163. serializationObject.alphaIndex = this.alphaIndex;
  33164. serializationObject.hasVertexAlpha = this.hasVertexAlpha;
  33165. // Overlay
  33166. serializationObject.overlayAlpha = this.overlayAlpha;
  33167. serializationObject.overlayColor = this.overlayColor.asArray();
  33168. serializationObject.renderOverlay = this.renderOverlay;
  33169. // Fog
  33170. serializationObject.applyFog = this.applyFog;
  33171. // Action Manager
  33172. if (this.actionManager) {
  33173. serializationObject.actions = this.actionManager.serialize(this.name);
  33174. }
  33175. };
  33176. Mesh.prototype._syncGeometryWithMorphTargetManager = function () {
  33177. if (!this.geometry) {
  33178. return;
  33179. }
  33180. this._markSubMeshesAsAttributesDirty();
  33181. var morphTargetManager = this._morphTargetManager;
  33182. if (morphTargetManager && morphTargetManager.vertexCount) {
  33183. if (morphTargetManager.vertexCount !== this.getTotalVertices()) {
  33184. BABYLON.Tools.Error("Mesh is incompatible with morph targets. Targets and mesh must all have the same vertices count.");
  33185. this.morphTargetManager = null;
  33186. return;
  33187. }
  33188. for (var index = 0; index < morphTargetManager.numInfluencers; index++) {
  33189. var morphTarget = morphTargetManager.getActiveTarget(index);
  33190. var positions = morphTarget.getPositions();
  33191. if (!positions) {
  33192. BABYLON.Tools.Error("Invalid morph target. Target must have positions.");
  33193. return;
  33194. }
  33195. this.geometry.setVerticesData(BABYLON.VertexBuffer.PositionKind + index, positions, false, 3);
  33196. var normals = morphTarget.getNormals();
  33197. if (normals) {
  33198. this.geometry.setVerticesData(BABYLON.VertexBuffer.NormalKind + index, normals, false, 3);
  33199. }
  33200. var tangents = morphTarget.getTangents();
  33201. if (tangents) {
  33202. this.geometry.setVerticesData(BABYLON.VertexBuffer.TangentKind + index, tangents, false, 3);
  33203. }
  33204. }
  33205. }
  33206. else {
  33207. var index = 0;
  33208. // Positions
  33209. while (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind + index)) {
  33210. this.geometry.removeVerticesData(BABYLON.VertexBuffer.PositionKind + index);
  33211. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind + index)) {
  33212. this.geometry.removeVerticesData(BABYLON.VertexBuffer.NormalKind + index);
  33213. }
  33214. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind + index)) {
  33215. this.geometry.removeVerticesData(BABYLON.VertexBuffer.TangentKind + index);
  33216. }
  33217. index++;
  33218. }
  33219. }
  33220. };
  33221. // Statics
  33222. /**
  33223. * Returns a new Mesh object parsed from the source provided.
  33224. * The parameter `parsedMesh` is the source.
  33225. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  33226. */
  33227. Mesh.Parse = function (parsedMesh, scene, rootUrl) {
  33228. var mesh;
  33229. if (parsedMesh.type && parsedMesh.type === "GroundMesh") {
  33230. mesh = BABYLON.GroundMesh.Parse(parsedMesh, scene);
  33231. }
  33232. else {
  33233. mesh = new Mesh(parsedMesh.name, scene);
  33234. }
  33235. mesh.id = parsedMesh.id;
  33236. if (BABYLON.Tags) {
  33237. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  33238. }
  33239. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  33240. if (parsedMesh.metadata !== undefined) {
  33241. mesh.metadata = parsedMesh.metadata;
  33242. }
  33243. if (parsedMesh.rotationQuaternion) {
  33244. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  33245. }
  33246. else if (parsedMesh.rotation) {
  33247. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  33248. }
  33249. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  33250. if (parsedMesh.localMatrix) {
  33251. mesh.setPreTransformMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  33252. }
  33253. else if (parsedMesh.pivotMatrix) {
  33254. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  33255. }
  33256. mesh.setEnabled(parsedMesh.isEnabled);
  33257. mesh.isVisible = parsedMesh.isVisible;
  33258. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  33259. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  33260. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  33261. if (parsedMesh.applyFog !== undefined) {
  33262. mesh.applyFog = parsedMesh.applyFog;
  33263. }
  33264. if (parsedMesh.pickable !== undefined) {
  33265. mesh.isPickable = parsedMesh.pickable;
  33266. }
  33267. if (parsedMesh.alphaIndex !== undefined) {
  33268. mesh.alphaIndex = parsedMesh.alphaIndex;
  33269. }
  33270. mesh.receiveShadows = parsedMesh.receiveShadows;
  33271. mesh.billboardMode = parsedMesh.billboardMode;
  33272. if (parsedMesh.visibility !== undefined) {
  33273. mesh.visibility = parsedMesh.visibility;
  33274. }
  33275. mesh.checkCollisions = parsedMesh.checkCollisions;
  33276. if (parsedMesh.isBlocker !== undefined) {
  33277. mesh.isBlocker = parsedMesh.isBlocker;
  33278. }
  33279. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  33280. // freezeWorldMatrix
  33281. if (parsedMesh.freezeWorldMatrix) {
  33282. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  33283. }
  33284. // Parent
  33285. if (parsedMesh.parentId) {
  33286. mesh._waitingParentId = parsedMesh.parentId;
  33287. }
  33288. // Actions
  33289. if (parsedMesh.actions !== undefined) {
  33290. mesh._waitingActions = parsedMesh.actions;
  33291. }
  33292. // Overlay
  33293. if (parsedMesh.overlayAlpha !== undefined) {
  33294. mesh.overlayAlpha = parsedMesh.overlayAlpha;
  33295. }
  33296. if (parsedMesh.overlayColor !== undefined) {
  33297. mesh.overlayColor = BABYLON.Color3.FromArray(parsedMesh.overlayColor);
  33298. }
  33299. if (parsedMesh.renderOverlay !== undefined) {
  33300. mesh.renderOverlay = parsedMesh.renderOverlay;
  33301. }
  33302. // Geometry
  33303. mesh.isUnIndexed = !!parsedMesh.isUnIndexed;
  33304. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  33305. if (parsedMesh.delayLoadingFile) {
  33306. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  33307. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  33308. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  33309. if (parsedMesh._binaryInfo) {
  33310. mesh._binaryInfo = parsedMesh._binaryInfo;
  33311. }
  33312. mesh._delayInfo = [];
  33313. if (parsedMesh.hasUVs) {
  33314. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  33315. }
  33316. if (parsedMesh.hasUVs2) {
  33317. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  33318. }
  33319. if (parsedMesh.hasUVs3) {
  33320. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  33321. }
  33322. if (parsedMesh.hasUVs4) {
  33323. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  33324. }
  33325. if (parsedMesh.hasUVs5) {
  33326. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  33327. }
  33328. if (parsedMesh.hasUVs6) {
  33329. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  33330. }
  33331. if (parsedMesh.hasColors) {
  33332. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  33333. }
  33334. if (parsedMesh.hasMatricesIndices) {
  33335. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  33336. }
  33337. if (parsedMesh.hasMatricesWeights) {
  33338. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  33339. }
  33340. mesh._delayLoadingFunction = BABYLON.Geometry._ImportGeometry;
  33341. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  33342. mesh._checkDelayState();
  33343. }
  33344. }
  33345. else {
  33346. BABYLON.Geometry._ImportGeometry(parsedMesh, mesh);
  33347. }
  33348. // Material
  33349. if (parsedMesh.materialId) {
  33350. mesh.setMaterialByID(parsedMesh.materialId);
  33351. }
  33352. else {
  33353. mesh.material = null;
  33354. }
  33355. // Morph targets
  33356. if (parsedMesh.morphTargetManagerId > -1) {
  33357. mesh.morphTargetManager = scene.getMorphTargetManagerById(parsedMesh.morphTargetManagerId);
  33358. }
  33359. // Skeleton
  33360. if (parsedMesh.skeletonId > -1) {
  33361. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  33362. if (parsedMesh.numBoneInfluencers) {
  33363. mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
  33364. }
  33365. }
  33366. // Animations
  33367. if (parsedMesh.animations) {
  33368. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  33369. var parsedAnimation = parsedMesh.animations[animationIndex];
  33370. mesh.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  33371. }
  33372. BABYLON.Node.ParseAnimationRanges(mesh, parsedMesh, scene);
  33373. }
  33374. if (parsedMesh.autoAnimate) {
  33375. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  33376. }
  33377. // Layer Mask
  33378. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  33379. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  33380. }
  33381. else {
  33382. mesh.layerMask = 0x0FFFFFFF;
  33383. }
  33384. // Physics
  33385. if (parsedMesh.physicsImpostor) {
  33386. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parsedMesh.physicsImpostor, {
  33387. mass: parsedMesh.physicsMass,
  33388. friction: parsedMesh.physicsFriction,
  33389. restitution: parsedMesh.physicsRestitution
  33390. }, scene);
  33391. }
  33392. // Instances
  33393. if (parsedMesh.instances) {
  33394. for (var index = 0; index < parsedMesh.instances.length; index++) {
  33395. var parsedInstance = parsedMesh.instances[index];
  33396. var instance = mesh.createInstance(parsedInstance.name);
  33397. if (parsedInstance.id) {
  33398. instance.id = parsedInstance.id;
  33399. }
  33400. if (BABYLON.Tags) {
  33401. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  33402. }
  33403. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  33404. if (parsedInstance.parentId) {
  33405. instance._waitingParentId = parsedInstance.parentId;
  33406. }
  33407. if (parsedInstance.rotationQuaternion) {
  33408. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  33409. }
  33410. else if (parsedInstance.rotation) {
  33411. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  33412. }
  33413. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  33414. instance.checkCollisions = mesh.checkCollisions;
  33415. if (parsedMesh.animations) {
  33416. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  33417. parsedAnimation = parsedMesh.animations[animationIndex];
  33418. instance.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  33419. }
  33420. BABYLON.Node.ParseAnimationRanges(instance, parsedMesh, scene);
  33421. }
  33422. }
  33423. }
  33424. return mesh;
  33425. };
  33426. /**
  33427. * Creates a ribbon mesh.
  33428. * Please consider using the same method from the MeshBuilder class instead.
  33429. * The ribbon is a parametric shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes. It has no predefined shape. Its final shape will depend on the input parameters.
  33430. *
  33431. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  33432. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  33433. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  33434. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  33435. * 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.
  33436. * It's the offset to join together the points from the same path. Ex : offset = 10 means the point 1 is joined to the point 11.
  33437. * 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
  33438. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33439. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33440. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33441. */
  33442. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
  33443. if (closeArray === void 0) { closeArray = false; }
  33444. if (updatable === void 0) { updatable = false; }
  33445. return BABYLON.MeshBuilder.CreateRibbon(name, {
  33446. pathArray: pathArray,
  33447. closeArray: closeArray,
  33448. closePath: closePath,
  33449. offset: offset,
  33450. updatable: updatable,
  33451. sideOrientation: sideOrientation,
  33452. instance: instance
  33453. }, scene);
  33454. };
  33455. /**
  33456. * Creates a plane polygonal mesh. By default, this is a disc.
  33457. * Please consider using the same method from the MeshBuilder class instead.
  33458. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  33459. * 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.
  33460. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33461. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33462. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33463. */
  33464. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  33465. if (scene === void 0) { scene = null; }
  33466. var options = {
  33467. radius: radius,
  33468. tessellation: tessellation,
  33469. sideOrientation: sideOrientation,
  33470. updatable: updatable
  33471. };
  33472. return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
  33473. };
  33474. /**
  33475. * Creates a box mesh.
  33476. * Please consider using the same method from the MeshBuilder class instead.
  33477. * The parameter `size` sets the size (float) of each box side (default 1).
  33478. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33479. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33480. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33481. */
  33482. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  33483. if (scene === void 0) { scene = null; }
  33484. var options = {
  33485. size: size,
  33486. sideOrientation: sideOrientation,
  33487. updatable: updatable
  33488. };
  33489. return BABYLON.MeshBuilder.CreateBox(name, options, scene);
  33490. };
  33491. /**
  33492. * Creates a sphere mesh.
  33493. * Please consider using the same method from the MeshBuilder class instead.
  33494. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  33495. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  33496. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33497. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33498. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33499. */
  33500. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  33501. var options = {
  33502. segments: segments,
  33503. diameterX: diameter,
  33504. diameterY: diameter,
  33505. diameterZ: diameter,
  33506. sideOrientation: sideOrientation,
  33507. updatable: updatable
  33508. };
  33509. return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
  33510. };
  33511. /**
  33512. * Creates a cylinder or a cone mesh.
  33513. * Please consider using the same method from the MeshBuilder class instead.
  33514. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  33515. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  33516. * 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.
  33517. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  33518. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  33519. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33520. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33521. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33522. */
  33523. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  33524. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  33525. if (scene !== undefined) {
  33526. sideOrientation = updatable || Mesh.DEFAULTSIDE;
  33527. updatable = scene;
  33528. }
  33529. scene = subdivisions;
  33530. subdivisions = 1;
  33531. }
  33532. var options = {
  33533. height: height,
  33534. diameterTop: diameterTop,
  33535. diameterBottom: diameterBottom,
  33536. tessellation: tessellation,
  33537. subdivisions: subdivisions,
  33538. sideOrientation: sideOrientation,
  33539. updatable: updatable
  33540. };
  33541. return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
  33542. };
  33543. // Torus (Code from SharpDX.org)
  33544. /**
  33545. * Creates a torus mesh.
  33546. * Please consider using the same method from the MeshBuilder class instead.
  33547. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  33548. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  33549. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  33550. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33551. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33552. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33553. */
  33554. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  33555. var options = {
  33556. diameter: diameter,
  33557. thickness: thickness,
  33558. tessellation: tessellation,
  33559. sideOrientation: sideOrientation,
  33560. updatable: updatable
  33561. };
  33562. return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
  33563. };
  33564. /**
  33565. * Creates a torus knot mesh.
  33566. * Please consider using the same method from the MeshBuilder class instead.
  33567. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  33568. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  33569. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  33570. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  33571. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33572. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33573. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33574. */
  33575. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  33576. var options = {
  33577. radius: radius,
  33578. tube: tube,
  33579. radialSegments: radialSegments,
  33580. tubularSegments: tubularSegments,
  33581. p: p,
  33582. q: q,
  33583. sideOrientation: sideOrientation,
  33584. updatable: updatable
  33585. };
  33586. return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
  33587. };
  33588. /**
  33589. * Creates a line mesh.
  33590. * Please consider using the same method from the MeshBuilder class instead.
  33591. * 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.
  33592. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  33593. * The parameter `points` is an array successive Vector3.
  33594. * 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
  33595. * When updating an instance, remember that only point positions can change, not the number of points.
  33596. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33597. */
  33598. Mesh.CreateLines = function (name, points, scene, updatable, instance) {
  33599. if (scene === void 0) { scene = null; }
  33600. if (updatable === void 0) { updatable = false; }
  33601. if (instance === void 0) { instance = null; }
  33602. var options = {
  33603. points: points,
  33604. updatable: updatable,
  33605. instance: instance
  33606. };
  33607. return BABYLON.MeshBuilder.CreateLines(name, options, scene);
  33608. };
  33609. /**
  33610. * Creates a dashed line mesh.
  33611. * Please consider using the same method from the MeshBuilder class instead.
  33612. * 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.
  33613. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  33614. * The parameter `points` is an array successive Vector3.
  33615. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  33616. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  33617. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  33618. * 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
  33619. * When updating an instance, remember that only point positions can change, not the number of points.
  33620. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33621. */
  33622. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
  33623. if (scene === void 0) { scene = null; }
  33624. var options = {
  33625. points: points,
  33626. dashSize: dashSize,
  33627. gapSize: gapSize,
  33628. dashNb: dashNb,
  33629. updatable: updatable,
  33630. instance: instance
  33631. };
  33632. return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
  33633. };
  33634. /**
  33635. * Creates a polygon mesh.
  33636. * Please consider using the same method from the MeshBuilder class instead.
  33637. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  33638. * 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.
  33639. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33640. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33641. * Remember you can only change the shape positions, not their number when updating a polygon.
  33642. */
  33643. Mesh.CreatePolygon = function (name, shape, scene, holes, updatable, sideOrientation) {
  33644. var options = {
  33645. shape: shape,
  33646. holes: holes,
  33647. updatable: updatable,
  33648. sideOrientation: sideOrientation
  33649. };
  33650. return BABYLON.MeshBuilder.CreatePolygon(name, options, scene);
  33651. };
  33652. /**
  33653. * Creates an extruded polygon mesh, with depth in the Y direction.
  33654. * Please consider using the same method from the MeshBuilder class instead.
  33655. */
  33656. Mesh.ExtrudePolygon = function (name, shape, depth, scene, holes, updatable, sideOrientation) {
  33657. var options = {
  33658. shape: shape,
  33659. holes: holes,
  33660. depth: depth,
  33661. updatable: updatable,
  33662. sideOrientation: sideOrientation
  33663. };
  33664. return BABYLON.MeshBuilder.ExtrudePolygon(name, options, scene);
  33665. };
  33666. /**
  33667. * Creates an extruded shape mesh.
  33668. * The extrusion is a parametric shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes. It has no predefined shape. Its final shape will depend on the input parameters.
  33669. * Please consider using the same method from the MeshBuilder class instead.
  33670. *
  33671. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  33672. * 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
  33673. * extruded along the Z axis.
  33674. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  33675. * 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.
  33676. * The parameter `scale` (float, default 1) is the value to scale the shape.
  33677. * 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
  33678. * 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
  33679. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  33680. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33681. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33682. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33683. */
  33684. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
  33685. if (scene === void 0) { scene = null; }
  33686. var options = {
  33687. shape: shape,
  33688. path: path,
  33689. scale: scale,
  33690. rotation: rotation,
  33691. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  33692. sideOrientation: sideOrientation,
  33693. instance: instance,
  33694. updatable: updatable
  33695. };
  33696. return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
  33697. };
  33698. /**
  33699. * Creates an custom extruded shape mesh.
  33700. * The custom extrusion is a parametric shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes. It has no predefined shape. Its final shape will depend on the input parameters.
  33701. * Please consider using the same method from the MeshBuilder class instead.
  33702. *
  33703. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  33704. * 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
  33705. * extruded along the Z axis.
  33706. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  33707. * 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
  33708. * and the distance of this point from the begining of the path :
  33709. * ```javascript
  33710. * var rotationFunction = function(i, distance) {
  33711. * // do things
  33712. * return rotationValue; }
  33713. * ```
  33714. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  33715. * 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
  33716. * and the distance of this point from the begining of the path :
  33717. * ```javascript
  33718. * var scaleFunction = function(i, distance) {
  33719. * // do things
  33720. * return scaleValue;}
  33721. * ```
  33722. * It must returns a float value that will be the scale value applied to the shape on each path point.
  33723. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  33724. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  33725. * 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
  33726. * 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
  33727. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  33728. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33729. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33730. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33731. */
  33732. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
  33733. var options = {
  33734. shape: shape,
  33735. path: path,
  33736. scaleFunction: scaleFunction,
  33737. rotationFunction: rotationFunction,
  33738. ribbonCloseArray: ribbonCloseArray,
  33739. ribbonClosePath: ribbonClosePath,
  33740. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  33741. sideOrientation: sideOrientation,
  33742. instance: instance,
  33743. updatable: updatable
  33744. };
  33745. return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  33746. };
  33747. /**
  33748. * Creates lathe mesh.
  33749. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  33750. * Please consider using the same method from the MeshBuilder class instead.
  33751. * 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
  33752. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  33753. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  33754. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  33755. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33756. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33757. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33758. */
  33759. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  33760. var options = {
  33761. shape: shape,
  33762. radius: radius,
  33763. tessellation: tessellation,
  33764. sideOrientation: sideOrientation,
  33765. updatable: updatable
  33766. };
  33767. return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
  33768. };
  33769. /**
  33770. * Creates a plane mesh.
  33771. * Please consider using the same method from the MeshBuilder class instead.
  33772. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  33773. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33774. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33775. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33776. */
  33777. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  33778. var options = {
  33779. size: size,
  33780. width: size,
  33781. height: size,
  33782. sideOrientation: sideOrientation,
  33783. updatable: updatable
  33784. };
  33785. return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
  33786. };
  33787. /**
  33788. * Creates a ground mesh.
  33789. * Please consider using the same method from the MeshBuilder class instead.
  33790. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  33791. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  33792. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33793. */
  33794. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  33795. var options = {
  33796. width: width,
  33797. height: height,
  33798. subdivisions: subdivisions,
  33799. updatable: updatable
  33800. };
  33801. return BABYLON.MeshBuilder.CreateGround(name, options, scene);
  33802. };
  33803. /**
  33804. * Creates a tiled ground mesh.
  33805. * Please consider using the same method from the MeshBuilder class instead.
  33806. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  33807. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  33808. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  33809. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  33810. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  33811. * numbers of subdivisions on the ground width and height of each tile.
  33812. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33813. */
  33814. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  33815. var options = {
  33816. xmin: xmin,
  33817. zmin: zmin,
  33818. xmax: xmax,
  33819. zmax: zmax,
  33820. subdivisions: subdivisions,
  33821. precision: precision,
  33822. updatable: updatable
  33823. };
  33824. return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
  33825. };
  33826. /**
  33827. * Creates a ground mesh from a height map.
  33828. * tuto : http://doc.babylonjs.com/babylon101/height_map
  33829. * Please consider using the same method from the MeshBuilder class instead.
  33830. * The parameter `url` sets the URL of the height map image resource.
  33831. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  33832. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  33833. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  33834. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  33835. * 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).
  33836. * This function is passed the newly built mesh :
  33837. * ```javascript
  33838. * function(mesh) { // do things
  33839. * return; }
  33840. * ```
  33841. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33842. */
  33843. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  33844. var options = {
  33845. width: width,
  33846. height: height,
  33847. subdivisions: subdivisions,
  33848. minHeight: minHeight,
  33849. maxHeight: maxHeight,
  33850. updatable: updatable,
  33851. onReady: onReady
  33852. };
  33853. return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  33854. };
  33855. /**
  33856. * Creates a tube mesh.
  33857. * The tube is a parametric shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes. It has no predefined shape. Its final shape will depend on the input parameters.
  33858. * Please consider using the same method from the MeshBuilder class instead.
  33859. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  33860. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  33861. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  33862. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  33863. * 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.
  33864. * It must return a radius value (positive float) :
  33865. * ```javascript
  33866. * var radiusFunction = function(i, distance) {
  33867. * // do things
  33868. * return radius; }
  33869. * ```
  33870. * 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
  33871. * 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
  33872. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33873. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33874. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33875. */
  33876. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  33877. var options = {
  33878. path: path,
  33879. radius: radius,
  33880. tessellation: tessellation,
  33881. radiusFunction: radiusFunction,
  33882. arc: 1,
  33883. cap: cap,
  33884. updatable: updatable,
  33885. sideOrientation: sideOrientation,
  33886. instance: instance
  33887. };
  33888. return BABYLON.MeshBuilder.CreateTube(name, options, scene);
  33889. };
  33890. /**
  33891. * Creates a polyhedron mesh.
  33892. * Please consider using the same method from the MeshBuilder class instead.
  33893. * 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
  33894. * to choose the wanted type.
  33895. * The parameter `size` (positive float, default 1) sets the polygon size.
  33896. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  33897. * 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`.
  33898. * 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
  33899. * 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)`).
  33900. * 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
  33901. * 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.
  33902. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33903. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33904. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33905. */
  33906. Mesh.CreatePolyhedron = function (name, options, scene) {
  33907. return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
  33908. };
  33909. /**
  33910. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  33911. * Please consider using the same method from the MeshBuilder class instead.
  33912. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  33913. * 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`).
  33914. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  33915. * 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.
  33916. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33917. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33918. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33919. */
  33920. Mesh.CreateIcoSphere = function (name, options, scene) {
  33921. return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene);
  33922. };
  33923. /**
  33924. * Creates a decal mesh.
  33925. * Please consider using the same method from the MeshBuilder class instead.
  33926. * 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.
  33927. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  33928. * The parameter `normal` (Vector3, default Vector3.Up) sets the normal of the mesh where the decal is applied onto in World coordinates.
  33929. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  33930. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  33931. */
  33932. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  33933. var options = {
  33934. position: position,
  33935. normal: normal,
  33936. size: size,
  33937. angle: angle
  33938. };
  33939. return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
  33940. };
  33941. // Skeletons
  33942. /**
  33943. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  33944. */
  33945. Mesh.prototype.setPositionsForCPUSkinning = function () {
  33946. if (!this._sourcePositions) {
  33947. var source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  33948. if (!source) {
  33949. return this._sourcePositions;
  33950. }
  33951. this._sourcePositions = new Float32Array(source);
  33952. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  33953. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  33954. }
  33955. }
  33956. return this._sourcePositions;
  33957. };
  33958. /**
  33959. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  33960. */
  33961. Mesh.prototype.setNormalsForCPUSkinning = function () {
  33962. if (!this._sourceNormals) {
  33963. var source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  33964. if (!source) {
  33965. return this._sourceNormals;
  33966. }
  33967. this._sourceNormals = new Float32Array(source);
  33968. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  33969. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  33970. }
  33971. }
  33972. return this._sourceNormals;
  33973. };
  33974. /**
  33975. * Updates the vertex buffer by applying transformation from the bones.
  33976. * Returns the Mesh.
  33977. *
  33978. * @param {skeleton} skeleton to apply
  33979. */
  33980. Mesh.prototype.applySkeleton = function (skeleton) {
  33981. if (!this.geometry) {
  33982. return this;
  33983. }
  33984. if (this.geometry._softwareSkinningRenderId == this.getScene().getRenderId()) {
  33985. return this;
  33986. }
  33987. this.geometry._softwareSkinningRenderId = this.getScene().getRenderId();
  33988. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  33989. return this;
  33990. }
  33991. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  33992. return this;
  33993. }
  33994. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  33995. return this;
  33996. }
  33997. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  33998. return this;
  33999. }
  34000. if (!this._sourcePositions) {
  34001. var submeshes = this.subMeshes.slice();
  34002. this.setPositionsForCPUSkinning();
  34003. this.subMeshes = submeshes;
  34004. }
  34005. if (!this._sourceNormals) {
  34006. this.setNormalsForCPUSkinning();
  34007. }
  34008. // positionsData checks for not being Float32Array will only pass at most once
  34009. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  34010. if (!positionsData) {
  34011. return this;
  34012. }
  34013. if (!(positionsData instanceof Float32Array)) {
  34014. positionsData = new Float32Array(positionsData);
  34015. }
  34016. // normalsData checks for not being Float32Array will only pass at most once
  34017. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  34018. if (!normalsData) {
  34019. return this;
  34020. }
  34021. if (!(normalsData instanceof Float32Array)) {
  34022. normalsData = new Float32Array(normalsData);
  34023. }
  34024. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  34025. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  34026. if (!matricesWeightsData || !matricesIndicesData) {
  34027. return this;
  34028. }
  34029. var needExtras = this.numBoneInfluencers > 4;
  34030. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  34031. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  34032. var skeletonMatrices = skeleton.getTransformMatrices(this);
  34033. var tempVector3 = BABYLON.Vector3.Zero();
  34034. var finalMatrix = new BABYLON.Matrix();
  34035. var tempMatrix = new BABYLON.Matrix();
  34036. var matWeightIdx = 0;
  34037. var inf;
  34038. for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
  34039. var weight;
  34040. for (inf = 0; inf < 4; inf++) {
  34041. weight = matricesWeightsData[matWeightIdx + inf];
  34042. if (weight > 0) {
  34043. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesData[matWeightIdx + inf] * 16), weight, tempMatrix);
  34044. finalMatrix.addToSelf(tempMatrix);
  34045. }
  34046. else
  34047. break;
  34048. }
  34049. if (needExtras) {
  34050. for (inf = 0; inf < 4; inf++) {
  34051. weight = matricesWeightsExtraData[matWeightIdx + inf];
  34052. if (weight > 0) {
  34053. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesExtraData[matWeightIdx + inf] * 16), weight, tempMatrix);
  34054. finalMatrix.addToSelf(tempMatrix);
  34055. }
  34056. else
  34057. break;
  34058. }
  34059. }
  34060. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  34061. tempVector3.toArray(positionsData, index);
  34062. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  34063. tempVector3.toArray(normalsData, index);
  34064. finalMatrix.reset();
  34065. }
  34066. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  34067. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  34068. return this;
  34069. };
  34070. // Tools
  34071. /**
  34072. * Returns an object `{min:` Vector3`, max:` Vector3`}`
  34073. * This min and max Vector3 are the minimum and maximum vectors of each mesh bounding box from the passed array, in the World system
  34074. */
  34075. Mesh.MinMax = function (meshes) {
  34076. var minVector = null;
  34077. var maxVector = null;
  34078. meshes.forEach(function (mesh, index, array) {
  34079. var boundingInfo = mesh.getBoundingInfo();
  34080. var boundingBox = boundingInfo.boundingBox;
  34081. if (!minVector || !maxVector) {
  34082. minVector = boundingBox.minimumWorld;
  34083. maxVector = boundingBox.maximumWorld;
  34084. }
  34085. else {
  34086. minVector.minimizeInPlace(boundingBox.minimumWorld);
  34087. maxVector.maximizeInPlace(boundingBox.maximumWorld);
  34088. }
  34089. });
  34090. if (!minVector || !maxVector) {
  34091. return {
  34092. min: BABYLON.Vector3.Zero(),
  34093. max: BABYLON.Vector3.Zero()
  34094. };
  34095. }
  34096. return {
  34097. min: minVector,
  34098. max: maxVector
  34099. };
  34100. };
  34101. /**
  34102. * Returns a Vector3, the center of the `{min:` Vector3`, max:` Vector3`}` or the center of MinMax vector3 computed from a mesh array.
  34103. */
  34104. Mesh.Center = function (meshesOrMinMaxVector) {
  34105. var minMaxVector = (meshesOrMinMaxVector instanceof Array) ? Mesh.MinMax(meshesOrMinMaxVector) : meshesOrMinMaxVector;
  34106. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  34107. };
  34108. /**
  34109. * Merge the array of meshes into a single mesh for performance reasons.
  34110. * @param {Array<Mesh>} meshes - The vertices source. They should all be of the same material. Entries can empty
  34111. * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes
  34112. * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  34113. * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  34114. * @param {boolean} subdivideWithSubMeshes - When true (false default), subdivide mesh to his subMesh array with meshes source.
  34115. */
  34116. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass, subdivideWithSubMeshes) {
  34117. if (disposeSource === void 0) { disposeSource = true; }
  34118. var index;
  34119. if (!allow32BitsIndices) {
  34120. var totalVertices = 0;
  34121. // Counting vertices
  34122. for (index = 0; index < meshes.length; index++) {
  34123. if (meshes[index]) {
  34124. totalVertices += meshes[index].getTotalVertices();
  34125. if (totalVertices > 65536) {
  34126. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  34127. return null;
  34128. }
  34129. }
  34130. }
  34131. }
  34132. // Merge
  34133. var vertexData = null;
  34134. var otherVertexData;
  34135. var indiceArray = new Array();
  34136. var source = null;
  34137. for (index = 0; index < meshes.length; index++) {
  34138. if (meshes[index]) {
  34139. meshes[index].computeWorldMatrix(true);
  34140. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true);
  34141. otherVertexData.transform(meshes[index].getWorldMatrix());
  34142. if (vertexData) {
  34143. vertexData.merge(otherVertexData);
  34144. }
  34145. else {
  34146. vertexData = otherVertexData;
  34147. source = meshes[index];
  34148. }
  34149. if (subdivideWithSubMeshes) {
  34150. indiceArray.push(meshes[index].getTotalIndices());
  34151. }
  34152. }
  34153. }
  34154. source = source;
  34155. if (!meshSubclass) {
  34156. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  34157. }
  34158. vertexData.applyToMesh(meshSubclass);
  34159. // Setting properties
  34160. meshSubclass.material = source.material;
  34161. meshSubclass.checkCollisions = source.checkCollisions;
  34162. // Cleaning
  34163. if (disposeSource) {
  34164. for (index = 0; index < meshes.length; index++) {
  34165. if (meshes[index]) {
  34166. meshes[index].dispose();
  34167. }
  34168. }
  34169. }
  34170. // Subdivide
  34171. if (subdivideWithSubMeshes) {
  34172. //-- Suppresions du submesh global
  34173. meshSubclass.releaseSubMeshes();
  34174. index = 0;
  34175. var offset = 0;
  34176. //-- aplique la subdivision en fonction du tableau d'indices
  34177. while (index < indiceArray.length) {
  34178. BABYLON.SubMesh.CreateFromIndices(0, offset, indiceArray[index], meshSubclass);
  34179. offset += indiceArray[index];
  34180. index++;
  34181. }
  34182. }
  34183. return meshSubclass;
  34184. };
  34185. // Consts
  34186. Mesh._FRONTSIDE = 0;
  34187. Mesh._BACKSIDE = 1;
  34188. Mesh._DOUBLESIDE = 2;
  34189. Mesh._DEFAULTSIDE = 0;
  34190. Mesh._NO_CAP = 0;
  34191. Mesh._CAP_START = 1;
  34192. Mesh._CAP_END = 2;
  34193. Mesh._CAP_ALL = 3;
  34194. return Mesh;
  34195. }(BABYLON.AbstractMesh));
  34196. BABYLON.Mesh = Mesh;
  34197. })(BABYLON || (BABYLON = {}));
  34198. //# sourceMappingURL=babylon.mesh.js.map
  34199. var BABYLON;
  34200. (function (BABYLON) {
  34201. var BaseSubMesh = /** @class */ (function () {
  34202. function BaseSubMesh() {
  34203. }
  34204. Object.defineProperty(BaseSubMesh.prototype, "effect", {
  34205. get: function () {
  34206. return this._materialEffect;
  34207. },
  34208. enumerable: true,
  34209. configurable: true
  34210. });
  34211. BaseSubMesh.prototype.setEffect = function (effect, defines) {
  34212. if (defines === void 0) { defines = null; }
  34213. if (this._materialEffect === effect) {
  34214. if (!effect) {
  34215. this._materialDefines = null;
  34216. }
  34217. return;
  34218. }
  34219. this._materialDefines = defines;
  34220. this._materialEffect = effect;
  34221. };
  34222. return BaseSubMesh;
  34223. }());
  34224. BABYLON.BaseSubMesh = BaseSubMesh;
  34225. var SubMesh = /** @class */ (function (_super) {
  34226. __extends(SubMesh, _super);
  34227. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  34228. if (createBoundingBox === void 0) { createBoundingBox = true; }
  34229. var _this = _super.call(this) || this;
  34230. _this.materialIndex = materialIndex;
  34231. _this.verticesStart = verticesStart;
  34232. _this.verticesCount = verticesCount;
  34233. _this.indexStart = indexStart;
  34234. _this.indexCount = indexCount;
  34235. _this._renderId = 0;
  34236. _this._mesh = mesh;
  34237. _this._renderingMesh = renderingMesh || mesh;
  34238. mesh.subMeshes.push(_this);
  34239. _this._trianglePlanes = [];
  34240. _this._id = mesh.subMeshes.length - 1;
  34241. if (createBoundingBox) {
  34242. _this.refreshBoundingInfo();
  34243. mesh.computeWorldMatrix(true);
  34244. }
  34245. return _this;
  34246. }
  34247. SubMesh.AddToMesh = function (materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  34248. if (createBoundingBox === void 0) { createBoundingBox = true; }
  34249. return new SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox);
  34250. };
  34251. Object.defineProperty(SubMesh.prototype, "IsGlobal", {
  34252. get: function () {
  34253. return (this.verticesStart === 0 && this.verticesCount == this._mesh.getTotalVertices());
  34254. },
  34255. enumerable: true,
  34256. configurable: true
  34257. });
  34258. /**
  34259. * Returns the submesh BoudingInfo object.
  34260. */
  34261. SubMesh.prototype.getBoundingInfo = function () {
  34262. if (this.IsGlobal) {
  34263. return this._mesh.getBoundingInfo();
  34264. }
  34265. return this._boundingInfo;
  34266. };
  34267. /**
  34268. * Sets the submesh BoundingInfo.
  34269. * Return the SubMesh.
  34270. */
  34271. SubMesh.prototype.setBoundingInfo = function (boundingInfo) {
  34272. this._boundingInfo = boundingInfo;
  34273. return this;
  34274. };
  34275. /**
  34276. * Returns the mesh of the current submesh.
  34277. */
  34278. SubMesh.prototype.getMesh = function () {
  34279. return this._mesh;
  34280. };
  34281. /**
  34282. * Returns the rendering mesh of the submesh.
  34283. */
  34284. SubMesh.prototype.getRenderingMesh = function () {
  34285. return this._renderingMesh;
  34286. };
  34287. /**
  34288. * Returns the submesh material.
  34289. */
  34290. SubMesh.prototype.getMaterial = function () {
  34291. var rootMaterial = this._renderingMesh.material;
  34292. if (rootMaterial === null || rootMaterial === undefined) {
  34293. return this._mesh.getScene().defaultMaterial;
  34294. }
  34295. else if (rootMaterial.getSubMaterial) {
  34296. var multiMaterial = rootMaterial;
  34297. var effectiveMaterial = multiMaterial.getSubMaterial(this.materialIndex);
  34298. if (this._currentMaterial !== effectiveMaterial) {
  34299. this._currentMaterial = effectiveMaterial;
  34300. this._materialDefines = null;
  34301. }
  34302. return effectiveMaterial;
  34303. }
  34304. return rootMaterial;
  34305. };
  34306. // Methods
  34307. /**
  34308. * Sets a new updated BoundingInfo object to the submesh.
  34309. * Returns the SubMesh.
  34310. */
  34311. SubMesh.prototype.refreshBoundingInfo = function () {
  34312. this._lastColliderWorldVertices = null;
  34313. if (this.IsGlobal || !this._renderingMesh || !this._renderingMesh.geometry) {
  34314. return this;
  34315. }
  34316. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  34317. if (!data) {
  34318. this._boundingInfo = this._mesh.getBoundingInfo();
  34319. return this;
  34320. }
  34321. var indices = this._renderingMesh.getIndices();
  34322. var extend;
  34323. //is this the only submesh?
  34324. if (this.indexStart === 0 && this.indexCount === indices.length) {
  34325. var boundingInfo = this._renderingMesh.getBoundingInfo();
  34326. //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
  34327. extend = { minimum: boundingInfo.minimum.clone(), maximum: boundingInfo.maximum.clone() };
  34328. }
  34329. else {
  34330. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount, this._renderingMesh.geometry.boundingBias);
  34331. }
  34332. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  34333. return this;
  34334. };
  34335. SubMesh.prototype._checkCollision = function (collider) {
  34336. var boundingInfo = this.getBoundingInfo();
  34337. return boundingInfo._checkCollision(collider);
  34338. };
  34339. /**
  34340. * Updates the submesh BoundingInfo.
  34341. * Returns the Submesh.
  34342. */
  34343. SubMesh.prototype.updateBoundingInfo = function (world) {
  34344. var boundingInfo = this.getBoundingInfo();
  34345. if (!boundingInfo) {
  34346. this.refreshBoundingInfo();
  34347. boundingInfo = this.getBoundingInfo();
  34348. }
  34349. boundingInfo.update(world);
  34350. return this;
  34351. };
  34352. /**
  34353. * True is the submesh bounding box intersects the frustum defined by the passed array of planes.
  34354. * Boolean returned.
  34355. */
  34356. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  34357. var boundingInfo = this.getBoundingInfo();
  34358. if (!boundingInfo) {
  34359. return false;
  34360. }
  34361. return boundingInfo.isInFrustum(frustumPlanes);
  34362. };
  34363. /**
  34364. * True is the submesh bounding box is completely inside the frustum defined by the passed array of planes.
  34365. * Boolean returned.
  34366. */
  34367. SubMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  34368. var boundingInfo = this.getBoundingInfo();
  34369. if (!boundingInfo) {
  34370. return false;
  34371. }
  34372. return boundingInfo.isCompletelyInFrustum(frustumPlanes);
  34373. };
  34374. /**
  34375. * Renders the submesh.
  34376. * Returns it.
  34377. */
  34378. SubMesh.prototype.render = function (enableAlphaMode) {
  34379. this._renderingMesh.render(this, enableAlphaMode);
  34380. return this;
  34381. };
  34382. /**
  34383. * Returns a new Index Buffer.
  34384. * Type returned : WebGLBuffer.
  34385. */
  34386. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  34387. if (!this._linesIndexBuffer) {
  34388. var linesIndices = [];
  34389. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  34390. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  34391. }
  34392. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  34393. this.linesIndexCount = linesIndices.length;
  34394. }
  34395. return this._linesIndexBuffer;
  34396. };
  34397. /**
  34398. * True is the passed Ray intersects the submesh bounding box.
  34399. * Boolean returned.
  34400. */
  34401. SubMesh.prototype.canIntersects = function (ray) {
  34402. var boundingInfo = this.getBoundingInfo();
  34403. if (!boundingInfo) {
  34404. return false;
  34405. }
  34406. return ray.intersectsBox(boundingInfo.boundingBox);
  34407. };
  34408. /**
  34409. * Returns an object IntersectionInfo.
  34410. */
  34411. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  34412. var intersectInfo = null;
  34413. var material = this.getMaterial();
  34414. if (!material) {
  34415. return null;
  34416. }
  34417. switch (material.fillMode) {
  34418. case BABYLON.Material.PointListDrawMode:
  34419. case BABYLON.Material.LineListDrawMode:
  34420. case BABYLON.Material.LineLoopDrawMode:
  34421. case BABYLON.Material.LineStripDrawMode:
  34422. case BABYLON.Material.TriangleFanDrawMode:
  34423. case BABYLON.Material.TriangleStripDrawMode:
  34424. return null;
  34425. }
  34426. // LineMesh first as it's also a Mesh...
  34427. if (BABYLON.LinesMesh && this._mesh instanceof BABYLON.LinesMesh) {
  34428. var lineMesh = this._mesh;
  34429. // Line test
  34430. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 2) {
  34431. var p0 = positions[indices[index]];
  34432. var p1 = positions[indices[index + 1]];
  34433. var length = ray.intersectionSegment(p0, p1, lineMesh.intersectionThreshold);
  34434. if (length < 0) {
  34435. continue;
  34436. }
  34437. if (fastCheck || !intersectInfo || length < intersectInfo.distance) {
  34438. intersectInfo = new BABYLON.IntersectionInfo(null, null, length);
  34439. if (fastCheck) {
  34440. break;
  34441. }
  34442. }
  34443. }
  34444. }
  34445. else {
  34446. // Triangles test
  34447. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  34448. var p0 = positions[indices[index]];
  34449. var p1 = positions[indices[index + 1]];
  34450. var p2 = positions[indices[index + 2]];
  34451. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  34452. if (currentIntersectInfo) {
  34453. if (currentIntersectInfo.distance < 0) {
  34454. continue;
  34455. }
  34456. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  34457. intersectInfo = currentIntersectInfo;
  34458. intersectInfo.faceId = index / 3;
  34459. if (fastCheck) {
  34460. break;
  34461. }
  34462. }
  34463. }
  34464. }
  34465. }
  34466. return intersectInfo;
  34467. };
  34468. SubMesh.prototype._rebuild = function () {
  34469. if (this._linesIndexBuffer) {
  34470. this._linesIndexBuffer = null;
  34471. }
  34472. };
  34473. // Clone
  34474. /**
  34475. * Creates a new Submesh from the passed Mesh.
  34476. */
  34477. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  34478. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  34479. if (!this.IsGlobal) {
  34480. var boundingInfo = this.getBoundingInfo();
  34481. if (!boundingInfo) {
  34482. return result;
  34483. }
  34484. result._boundingInfo = new BABYLON.BoundingInfo(boundingInfo.minimum, boundingInfo.maximum);
  34485. }
  34486. return result;
  34487. };
  34488. // Dispose
  34489. /**
  34490. * Disposes the Submesh.
  34491. * Returns nothing.
  34492. */
  34493. SubMesh.prototype.dispose = function () {
  34494. if (this._linesIndexBuffer) {
  34495. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  34496. this._linesIndexBuffer = null;
  34497. }
  34498. // Remove from mesh
  34499. var index = this._mesh.subMeshes.indexOf(this);
  34500. this._mesh.subMeshes.splice(index, 1);
  34501. };
  34502. // Statics
  34503. /**
  34504. * Creates a new Submesh from the passed parameters :
  34505. * - materialIndex (integer) : the index of the main mesh material.
  34506. * - startIndex (integer) : the index where to start the copy in the mesh indices array.
  34507. * - indexCount (integer) : the number of indices to copy then from the startIndex.
  34508. * - mesh (Mesh) : the main mesh to create the submesh from.
  34509. * - renderingMesh (optional Mesh) : rendering mesh.
  34510. */
  34511. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  34512. var minVertexIndex = Number.MAX_VALUE;
  34513. var maxVertexIndex = -Number.MAX_VALUE;
  34514. renderingMesh = (renderingMesh || mesh);
  34515. var indices = renderingMesh.getIndices();
  34516. for (var index = startIndex; index < startIndex + indexCount; index++) {
  34517. var vertexIndex = indices[index];
  34518. if (vertexIndex < minVertexIndex)
  34519. minVertexIndex = vertexIndex;
  34520. if (vertexIndex > maxVertexIndex)
  34521. maxVertexIndex = vertexIndex;
  34522. }
  34523. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  34524. };
  34525. return SubMesh;
  34526. }(BaseSubMesh));
  34527. BABYLON.SubMesh = SubMesh;
  34528. })(BABYLON || (BABYLON = {}));
  34529. //# sourceMappingURL=babylon.subMesh.js.map
  34530. var __assign = (this && this.__assign) || Object.assign || function(t) {
  34531. for (var s, i = 1, n = arguments.length; i < n; i++) {
  34532. s = arguments[i];
  34533. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  34534. t[p] = s[p];
  34535. }
  34536. return t;
  34537. };
  34538. var BABYLON;
  34539. (function (BABYLON) {
  34540. /**
  34541. * Manages the defines for the Material
  34542. */
  34543. var MaterialDefines = /** @class */ (function () {
  34544. function MaterialDefines() {
  34545. this._isDirty = true;
  34546. /** @hidden */
  34547. this._areLightsDirty = true;
  34548. /** @hidden */
  34549. this._areAttributesDirty = true;
  34550. /** @hidden */
  34551. this._areTexturesDirty = true;
  34552. /** @hidden */
  34553. this._areFresnelDirty = true;
  34554. /** @hidden */
  34555. this._areMiscDirty = true;
  34556. /** @hidden */
  34557. this._areImageProcessingDirty = true;
  34558. /** @hidden */
  34559. this._normals = false;
  34560. /** @hidden */
  34561. this._uvs = false;
  34562. /** @hidden */
  34563. this._needNormals = false;
  34564. /** @hidden */
  34565. this._needUVs = false;
  34566. }
  34567. Object.defineProperty(MaterialDefines.prototype, "isDirty", {
  34568. /**
  34569. * Specifies if the material needs to be re-calculated
  34570. */
  34571. get: function () {
  34572. return this._isDirty;
  34573. },
  34574. enumerable: true,
  34575. configurable: true
  34576. });
  34577. /**
  34578. * Marks the material to indicate that it has been re-calculated
  34579. */
  34580. MaterialDefines.prototype.markAsProcessed = function () {
  34581. this._isDirty = false;
  34582. this._areAttributesDirty = false;
  34583. this._areTexturesDirty = false;
  34584. this._areFresnelDirty = false;
  34585. this._areLightsDirty = false;
  34586. this._areMiscDirty = false;
  34587. this._areImageProcessingDirty = false;
  34588. };
  34589. /**
  34590. * Marks the material to indicate that it needs to be re-calculated
  34591. */
  34592. MaterialDefines.prototype.markAsUnprocessed = function () {
  34593. this._isDirty = true;
  34594. };
  34595. /**
  34596. * Marks the material to indicate all of its defines need to be re-calculated
  34597. */
  34598. MaterialDefines.prototype.markAllAsDirty = function () {
  34599. this._areTexturesDirty = true;
  34600. this._areAttributesDirty = true;
  34601. this._areLightsDirty = true;
  34602. this._areFresnelDirty = true;
  34603. this._areMiscDirty = true;
  34604. this._areImageProcessingDirty = true;
  34605. this._isDirty = true;
  34606. };
  34607. /**
  34608. * Marks the material to indicate that image processing needs to be re-calculated
  34609. */
  34610. MaterialDefines.prototype.markAsImageProcessingDirty = function () {
  34611. this._areImageProcessingDirty = true;
  34612. this._isDirty = true;
  34613. };
  34614. /**
  34615. * Marks the material to indicate the lights need to be re-calculated
  34616. */
  34617. MaterialDefines.prototype.markAsLightDirty = function () {
  34618. this._areLightsDirty = true;
  34619. this._isDirty = true;
  34620. };
  34621. /**
  34622. * Marks the attribute state as changed
  34623. */
  34624. MaterialDefines.prototype.markAsAttributesDirty = function () {
  34625. this._areAttributesDirty = true;
  34626. this._isDirty = true;
  34627. };
  34628. /**
  34629. * Marks the texture state as changed
  34630. */
  34631. MaterialDefines.prototype.markAsTexturesDirty = function () {
  34632. this._areTexturesDirty = true;
  34633. this._isDirty = true;
  34634. };
  34635. /**
  34636. * Marks the fresnel state as changed
  34637. */
  34638. MaterialDefines.prototype.markAsFresnelDirty = function () {
  34639. this._areFresnelDirty = true;
  34640. this._isDirty = true;
  34641. };
  34642. /**
  34643. * Marks the misc state as changed
  34644. */
  34645. MaterialDefines.prototype.markAsMiscDirty = function () {
  34646. this._areMiscDirty = true;
  34647. this._isDirty = true;
  34648. };
  34649. /**
  34650. * Rebuilds the material defines
  34651. */
  34652. MaterialDefines.prototype.rebuild = function () {
  34653. if (this._keys) {
  34654. delete this._keys;
  34655. }
  34656. this._keys = [];
  34657. for (var _i = 0, _a = Object.keys(this); _i < _a.length; _i++) {
  34658. var key = _a[_i];
  34659. if (key[0] === "_") {
  34660. continue;
  34661. }
  34662. this._keys.push(key);
  34663. }
  34664. };
  34665. /**
  34666. * Specifies if two material defines are equal
  34667. * @param other - A material define instance to compare to
  34668. * @returns - Boolean indicating if the material defines are equal (true) or not (false)
  34669. */
  34670. MaterialDefines.prototype.isEqual = function (other) {
  34671. if (this._keys.length !== other._keys.length) {
  34672. return false;
  34673. }
  34674. for (var index = 0; index < this._keys.length; index++) {
  34675. var prop = this._keys[index];
  34676. if (this[prop] !== other[prop]) {
  34677. return false;
  34678. }
  34679. }
  34680. return true;
  34681. };
  34682. /**
  34683. * Clones this instance's defines to another instance
  34684. * @param other - material defines to clone values to
  34685. */
  34686. MaterialDefines.prototype.cloneTo = function (other) {
  34687. if (this._keys.length !== other._keys.length) {
  34688. other._keys = this._keys.slice(0);
  34689. }
  34690. for (var index = 0; index < this._keys.length; index++) {
  34691. var prop = this._keys[index];
  34692. other[prop] = this[prop];
  34693. }
  34694. };
  34695. /**
  34696. * Resets the material define values
  34697. */
  34698. MaterialDefines.prototype.reset = function () {
  34699. for (var index = 0; index < this._keys.length; index++) {
  34700. var prop = this._keys[index];
  34701. var type = typeof this[prop];
  34702. switch (type) {
  34703. case "number":
  34704. this[prop] = 0;
  34705. break;
  34706. case "string":
  34707. this[prop] = "";
  34708. break;
  34709. default:
  34710. this[prop] = false;
  34711. break;
  34712. }
  34713. }
  34714. };
  34715. /**
  34716. * Converts the material define values to a string
  34717. * @returns - String of material define information
  34718. */
  34719. MaterialDefines.prototype.toString = function () {
  34720. var result = "";
  34721. for (var index = 0; index < this._keys.length; index++) {
  34722. var prop = this._keys[index];
  34723. var value = this[prop];
  34724. var type = typeof value;
  34725. switch (type) {
  34726. case "number":
  34727. case "string":
  34728. result += "#define " + prop + " " + value + "\n";
  34729. break;
  34730. default:
  34731. if (value) {
  34732. result += "#define " + prop + "\n";
  34733. }
  34734. break;
  34735. }
  34736. }
  34737. return result;
  34738. };
  34739. return MaterialDefines;
  34740. }());
  34741. BABYLON.MaterialDefines = MaterialDefines;
  34742. /**
  34743. * Base class for the main features of a material in Babylon.js
  34744. */
  34745. var Material = /** @class */ (function () {
  34746. /**
  34747. * Creates a material instance
  34748. * @param name defines the name of the material
  34749. * @param scene defines the scene to reference
  34750. * @param doNotAdd specifies if the material should be added to the scene
  34751. */
  34752. function Material(name, scene, doNotAdd) {
  34753. /**
  34754. * Specifies if the ready state should be checked on each call
  34755. */
  34756. this.checkReadyOnEveryCall = false;
  34757. /**
  34758. * Specifies if the ready state should be checked once
  34759. */
  34760. this.checkReadyOnlyOnce = false;
  34761. /**
  34762. * The state of the material
  34763. */
  34764. this.state = "";
  34765. /**
  34766. * The alpha value of the material
  34767. */
  34768. this._alpha = 1.0;
  34769. /**
  34770. * Specifies if back face culling is enabled
  34771. */
  34772. this._backFaceCulling = true;
  34773. /**
  34774. * Specifies if the material should be serialized
  34775. */
  34776. this.doNotSerialize = false;
  34777. /**
  34778. * Specifies if the effect should be stored on sub meshes
  34779. */
  34780. this.storeEffectOnSubMeshes = false;
  34781. /**
  34782. * An event triggered when the material is disposed
  34783. */
  34784. this.onDisposeObservable = new BABYLON.Observable();
  34785. /**
  34786. * An event triggered when the material is bound
  34787. */
  34788. this.onBindObservable = new BABYLON.Observable();
  34789. /**
  34790. * An event triggered when the material is unbound
  34791. */
  34792. this.onUnBindObservable = new BABYLON.Observable();
  34793. /**
  34794. * Stores the value of the alpha mode
  34795. */
  34796. this._alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  34797. /**
  34798. * Stores the state of the need depth pre-pass value
  34799. */
  34800. this._needDepthPrePass = false;
  34801. /**
  34802. * Specifies if depth writing should be disabled
  34803. */
  34804. this.disableDepthWrite = false;
  34805. /**
  34806. * Specifies if depth writing should be forced
  34807. */
  34808. this.forceDepthWrite = false;
  34809. /**
  34810. * Specifies if there should be a separate pass for culling
  34811. */
  34812. this.separateCullingPass = false;
  34813. /**
  34814. * Stores the state specifing if fog should be enabled
  34815. */
  34816. this._fogEnabled = true;
  34817. /**
  34818. * Stores the size of points
  34819. */
  34820. this.pointSize = 1.0;
  34821. /**
  34822. * Stores the z offset value
  34823. */
  34824. this.zOffset = 0;
  34825. /**
  34826. * Specifies if the material was previously ready
  34827. */
  34828. this._wasPreviouslyReady = false;
  34829. /**
  34830. * Stores the fill mode state
  34831. */
  34832. this._fillMode = Material.TriangleFillMode;
  34833. this.name = name;
  34834. this.id = name || BABYLON.Tools.RandomId();
  34835. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  34836. this.uniqueId = this._scene.getUniqueId();
  34837. if (this._scene.useRightHandedSystem) {
  34838. this.sideOrientation = Material.ClockWiseSideOrientation;
  34839. }
  34840. else {
  34841. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  34842. }
  34843. this._uniformBuffer = new BABYLON.UniformBuffer(this._scene.getEngine());
  34844. this._useUBO = this.getScene().getEngine().supportsUniformBuffers;
  34845. if (!doNotAdd) {
  34846. this._scene.materials.push(this);
  34847. }
  34848. }
  34849. Object.defineProperty(Material, "TriangleFillMode", {
  34850. /**
  34851. * Returns the triangle fill mode
  34852. */
  34853. get: function () {
  34854. return Material._TriangleFillMode;
  34855. },
  34856. enumerable: true,
  34857. configurable: true
  34858. });
  34859. Object.defineProperty(Material, "WireFrameFillMode", {
  34860. /**
  34861. * Returns the wireframe mode
  34862. */
  34863. get: function () {
  34864. return Material._WireFrameFillMode;
  34865. },
  34866. enumerable: true,
  34867. configurable: true
  34868. });
  34869. Object.defineProperty(Material, "PointFillMode", {
  34870. /**
  34871. * Returns the point fill mode
  34872. */
  34873. get: function () {
  34874. return Material._PointFillMode;
  34875. },
  34876. enumerable: true,
  34877. configurable: true
  34878. });
  34879. Object.defineProperty(Material, "PointListDrawMode", {
  34880. /**
  34881. * Returns the point list draw mode
  34882. */
  34883. get: function () {
  34884. return Material._PointListDrawMode;
  34885. },
  34886. enumerable: true,
  34887. configurable: true
  34888. });
  34889. Object.defineProperty(Material, "LineListDrawMode", {
  34890. /**
  34891. * Returns the line list draw mode
  34892. */
  34893. get: function () {
  34894. return Material._LineListDrawMode;
  34895. },
  34896. enumerable: true,
  34897. configurable: true
  34898. });
  34899. Object.defineProperty(Material, "LineLoopDrawMode", {
  34900. /**
  34901. * Returns the line loop draw mode
  34902. */
  34903. get: function () {
  34904. return Material._LineLoopDrawMode;
  34905. },
  34906. enumerable: true,
  34907. configurable: true
  34908. });
  34909. Object.defineProperty(Material, "LineStripDrawMode", {
  34910. /**
  34911. * Returns the line strip draw mode
  34912. */
  34913. get: function () {
  34914. return Material._LineStripDrawMode;
  34915. },
  34916. enumerable: true,
  34917. configurable: true
  34918. });
  34919. Object.defineProperty(Material, "TriangleStripDrawMode", {
  34920. /**
  34921. * Returns the triangle strip draw mode
  34922. */
  34923. get: function () {
  34924. return Material._TriangleStripDrawMode;
  34925. },
  34926. enumerable: true,
  34927. configurable: true
  34928. });
  34929. Object.defineProperty(Material, "TriangleFanDrawMode", {
  34930. /**
  34931. * Returns the triangle fan draw mode
  34932. */
  34933. get: function () {
  34934. return Material._TriangleFanDrawMode;
  34935. },
  34936. enumerable: true,
  34937. configurable: true
  34938. });
  34939. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  34940. /**
  34941. * Returns the clock-wise side orientation
  34942. */
  34943. get: function () {
  34944. return Material._ClockWiseSideOrientation;
  34945. },
  34946. enumerable: true,
  34947. configurable: true
  34948. });
  34949. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  34950. /**
  34951. * Returns the counter clock-wise side orientation
  34952. */
  34953. get: function () {
  34954. return Material._CounterClockWiseSideOrientation;
  34955. },
  34956. enumerable: true,
  34957. configurable: true
  34958. });
  34959. Object.defineProperty(Material, "TextureDirtyFlag", {
  34960. /**
  34961. * Returns the dirty texture flag value
  34962. */
  34963. get: function () {
  34964. return Material._TextureDirtyFlag;
  34965. },
  34966. enumerable: true,
  34967. configurable: true
  34968. });
  34969. Object.defineProperty(Material, "LightDirtyFlag", {
  34970. /**
  34971. * Returns the dirty light flag value
  34972. */
  34973. get: function () {
  34974. return Material._LightDirtyFlag;
  34975. },
  34976. enumerable: true,
  34977. configurable: true
  34978. });
  34979. Object.defineProperty(Material, "FresnelDirtyFlag", {
  34980. /**
  34981. * Returns the dirty fresnel flag value
  34982. */
  34983. get: function () {
  34984. return Material._FresnelDirtyFlag;
  34985. },
  34986. enumerable: true,
  34987. configurable: true
  34988. });
  34989. Object.defineProperty(Material, "AttributesDirtyFlag", {
  34990. /**
  34991. * Returns the dirty attributes flag value
  34992. */
  34993. get: function () {
  34994. return Material._AttributesDirtyFlag;
  34995. },
  34996. enumerable: true,
  34997. configurable: true
  34998. });
  34999. Object.defineProperty(Material, "MiscDirtyFlag", {
  35000. /**
  35001. * Returns the dirty misc flag value
  35002. */
  35003. get: function () {
  35004. return Material._MiscDirtyFlag;
  35005. },
  35006. enumerable: true,
  35007. configurable: true
  35008. });
  35009. Object.defineProperty(Material.prototype, "alpha", {
  35010. /**
  35011. * Gets the alpha value of the material
  35012. */
  35013. get: function () {
  35014. return this._alpha;
  35015. },
  35016. /**
  35017. * Sets the alpha value of the material
  35018. */
  35019. set: function (value) {
  35020. if (this._alpha === value) {
  35021. return;
  35022. }
  35023. this._alpha = value;
  35024. this.markAsDirty(Material.MiscDirtyFlag);
  35025. },
  35026. enumerable: true,
  35027. configurable: true
  35028. });
  35029. Object.defineProperty(Material.prototype, "backFaceCulling", {
  35030. /**
  35031. * Gets the back-face culling state
  35032. */
  35033. get: function () {
  35034. return this._backFaceCulling;
  35035. },
  35036. /**
  35037. * Sets the back-face culling state
  35038. */
  35039. set: function (value) {
  35040. if (this._backFaceCulling === value) {
  35041. return;
  35042. }
  35043. this._backFaceCulling = value;
  35044. this.markAsDirty(Material.TextureDirtyFlag);
  35045. },
  35046. enumerable: true,
  35047. configurable: true
  35048. });
  35049. Object.defineProperty(Material.prototype, "onDispose", {
  35050. /**
  35051. * Called during a dispose event
  35052. */
  35053. set: function (callback) {
  35054. if (this._onDisposeObserver) {
  35055. this.onDisposeObservable.remove(this._onDisposeObserver);
  35056. }
  35057. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  35058. },
  35059. enumerable: true,
  35060. configurable: true
  35061. });
  35062. Object.defineProperty(Material.prototype, "onBind", {
  35063. /**
  35064. * Called during a bind event
  35065. */
  35066. set: function (callback) {
  35067. if (this._onBindObserver) {
  35068. this.onBindObservable.remove(this._onBindObserver);
  35069. }
  35070. this._onBindObserver = this.onBindObservable.add(callback);
  35071. },
  35072. enumerable: true,
  35073. configurable: true
  35074. });
  35075. Object.defineProperty(Material.prototype, "alphaMode", {
  35076. /**
  35077. * Gets the value of the alpha mode
  35078. */
  35079. get: function () {
  35080. return this._alphaMode;
  35081. },
  35082. /**
  35083. * Sets the value of the alpha mode.
  35084. *
  35085. * | Value | Type | Description |
  35086. * | --- | --- | --- |
  35087. * | 0 | ALPHA_DISABLE | |
  35088. * | 1 | ALPHA_ADD | |
  35089. * | 2 | ALPHA_COMBINE | |
  35090. * | 3 | ALPHA_SUBTRACT | |
  35091. * | 4 | ALPHA_MULTIPLY | |
  35092. * | 5 | ALPHA_MAXIMIZED | |
  35093. * | 6 | ALPHA_ONEONE | |
  35094. * | 7 | ALPHA_PREMULTIPLIED | |
  35095. * | 8 | ALPHA_PREMULTIPLIED_PORTERDUFF | |
  35096. * | 9 | ALPHA_INTERPOLATE | |
  35097. * | 10 | ALPHA_SCREENMODE | |
  35098. *
  35099. */
  35100. set: function (value) {
  35101. if (this._alphaMode === value) {
  35102. return;
  35103. }
  35104. this._alphaMode = value;
  35105. this.markAsDirty(Material.TextureDirtyFlag);
  35106. },
  35107. enumerable: true,
  35108. configurable: true
  35109. });
  35110. Object.defineProperty(Material.prototype, "needDepthPrePass", {
  35111. /**
  35112. * Gets the depth pre-pass value
  35113. */
  35114. get: function () {
  35115. return this._needDepthPrePass;
  35116. },
  35117. /**
  35118. * Sets the need depth pre-pass value
  35119. */
  35120. set: function (value) {
  35121. if (this._needDepthPrePass === value) {
  35122. return;
  35123. }
  35124. this._needDepthPrePass = value;
  35125. if (this._needDepthPrePass) {
  35126. this.checkReadyOnEveryCall = true;
  35127. }
  35128. },
  35129. enumerable: true,
  35130. configurable: true
  35131. });
  35132. Object.defineProperty(Material.prototype, "fogEnabled", {
  35133. /**
  35134. * Gets the value of the fog enabled state
  35135. */
  35136. get: function () {
  35137. return this._fogEnabled;
  35138. },
  35139. /**
  35140. * Sets the state for enabling fog
  35141. */
  35142. set: function (value) {
  35143. if (this._fogEnabled === value) {
  35144. return;
  35145. }
  35146. this._fogEnabled = value;
  35147. this.markAsDirty(Material.MiscDirtyFlag);
  35148. },
  35149. enumerable: true,
  35150. configurable: true
  35151. });
  35152. Object.defineProperty(Material.prototype, "wireframe", {
  35153. /**
  35154. * Gets a value specifying if wireframe mode is enabled
  35155. */
  35156. get: function () {
  35157. switch (this._fillMode) {
  35158. case Material.WireFrameFillMode:
  35159. case Material.LineListDrawMode:
  35160. case Material.LineLoopDrawMode:
  35161. case Material.LineStripDrawMode:
  35162. return true;
  35163. }
  35164. return this._scene.forceWireframe;
  35165. },
  35166. /**
  35167. * Sets the state of wireframe mode
  35168. */
  35169. set: function (value) {
  35170. this.fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  35171. },
  35172. enumerable: true,
  35173. configurable: true
  35174. });
  35175. Object.defineProperty(Material.prototype, "pointsCloud", {
  35176. /**
  35177. * Gets the value specifying if point clouds are enabled
  35178. */
  35179. get: function () {
  35180. switch (this._fillMode) {
  35181. case Material.PointFillMode:
  35182. case Material.PointListDrawMode:
  35183. return true;
  35184. }
  35185. return this._scene.forcePointsCloud;
  35186. },
  35187. /**
  35188. * Sets the state of point cloud mode
  35189. */
  35190. set: function (value) {
  35191. this.fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  35192. },
  35193. enumerable: true,
  35194. configurable: true
  35195. });
  35196. Object.defineProperty(Material.prototype, "fillMode", {
  35197. /**
  35198. * Gets the material fill mode
  35199. */
  35200. get: function () {
  35201. return this._fillMode;
  35202. },
  35203. /**
  35204. * Sets the material fill mode
  35205. */
  35206. set: function (value) {
  35207. if (this._fillMode === value) {
  35208. return;
  35209. }
  35210. this._fillMode = value;
  35211. this.markAsDirty(Material.MiscDirtyFlag);
  35212. },
  35213. enumerable: true,
  35214. configurable: true
  35215. });
  35216. /**
  35217. * Returns a string representation of the current material
  35218. * @param fullDetails defines a boolean indicating which levels of logging is desired
  35219. * @returns a string with material information
  35220. */
  35221. Material.prototype.toString = function (fullDetails) {
  35222. var ret = "Name: " + this.name;
  35223. if (fullDetails) {
  35224. }
  35225. return ret;
  35226. };
  35227. /**
  35228. * Gets the class name of the material
  35229. * @returns a string with the class name of the material
  35230. */
  35231. Material.prototype.getClassName = function () {
  35232. return "Material";
  35233. };
  35234. Object.defineProperty(Material.prototype, "isFrozen", {
  35235. /**
  35236. * Specifies if updates for the material been locked
  35237. */
  35238. get: function () {
  35239. return this.checkReadyOnlyOnce;
  35240. },
  35241. enumerable: true,
  35242. configurable: true
  35243. });
  35244. /**
  35245. * Locks updates for the material
  35246. */
  35247. Material.prototype.freeze = function () {
  35248. this.checkReadyOnlyOnce = true;
  35249. };
  35250. /**
  35251. * Unlocks updates for the material
  35252. */
  35253. Material.prototype.unfreeze = function () {
  35254. this.checkReadyOnlyOnce = false;
  35255. };
  35256. /**
  35257. * Specifies if the material is ready to be used
  35258. * @param mesh defines the mesh to check
  35259. * @param useInstances specifies if instances should be used
  35260. * @returns a boolean indicating if the material is ready to be used
  35261. */
  35262. Material.prototype.isReady = function (mesh, useInstances) {
  35263. return true;
  35264. };
  35265. /**
  35266. * Specifies that the submesh is ready to be used
  35267. * @param mesh defines the mesh to check
  35268. * @param subMesh defines which submesh to check
  35269. * @param useInstances specifies that instances should be used
  35270. * @returns a boolean indicating that the submesh is ready or not
  35271. */
  35272. Material.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  35273. return false;
  35274. };
  35275. /**
  35276. * Returns the material effect
  35277. * @returns the effect associated with the material
  35278. */
  35279. Material.prototype.getEffect = function () {
  35280. return this._effect;
  35281. };
  35282. /**
  35283. * Returns the current scene
  35284. * @returns a Scene
  35285. */
  35286. Material.prototype.getScene = function () {
  35287. return this._scene;
  35288. };
  35289. /**
  35290. * Specifies if the material will require alpha blending
  35291. * @returns a boolean specifying if alpha blending is needed
  35292. */
  35293. Material.prototype.needAlphaBlending = function () {
  35294. return (this.alpha < 1.0);
  35295. };
  35296. /**
  35297. * Specifies if the mesh will require alpha blending
  35298. * @param mesh defines the mesh to check
  35299. * @returns a boolean specifying if alpha blending is needed for the mesh
  35300. */
  35301. Material.prototype.needAlphaBlendingForMesh = function (mesh) {
  35302. return this.needAlphaBlending() || (mesh.visibility < 1.0) || mesh.hasVertexAlpha;
  35303. };
  35304. /**
  35305. * Specifies if this material should be rendered in alpha test mode
  35306. * @returns a boolean specifying if an alpha test is needed.
  35307. */
  35308. Material.prototype.needAlphaTesting = function () {
  35309. return false;
  35310. };
  35311. /**
  35312. * Gets the texture used for the alpha test
  35313. * @returns the texture to use for alpha testing
  35314. */
  35315. Material.prototype.getAlphaTestTexture = function () {
  35316. return null;
  35317. };
  35318. /**
  35319. * Marks the material to indicate that it needs to be re-calculated
  35320. */
  35321. Material.prototype.markDirty = function () {
  35322. this._wasPreviouslyReady = false;
  35323. };
  35324. /** @hidden */
  35325. Material.prototype._preBind = function (effect, overrideOrientation) {
  35326. if (overrideOrientation === void 0) { overrideOrientation = null; }
  35327. var engine = this._scene.getEngine();
  35328. var orientation = (overrideOrientation == null) ? this.sideOrientation : overrideOrientation;
  35329. var reverse = orientation === Material.ClockWiseSideOrientation;
  35330. engine.enableEffect(effect ? effect : this._effect);
  35331. engine.setState(this.backFaceCulling, this.zOffset, false, reverse);
  35332. return reverse;
  35333. };
  35334. /**
  35335. * Binds the material to the mesh
  35336. * @param world defines the world transformation matrix
  35337. * @param mesh defines the mesh to bind the material to
  35338. */
  35339. Material.prototype.bind = function (world, mesh) {
  35340. };
  35341. /**
  35342. * Binds the submesh to the material
  35343. * @param world defines the world transformation matrix
  35344. * @param mesh defines the mesh containing the submesh
  35345. * @param subMesh defines the submesh to bind the material to
  35346. */
  35347. Material.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  35348. };
  35349. /**
  35350. * Binds the world matrix to the material
  35351. * @param world defines the world transformation matrix
  35352. */
  35353. Material.prototype.bindOnlyWorldMatrix = function (world) {
  35354. };
  35355. /**
  35356. * Binds the scene's uniform buffer to the effect.
  35357. * @param effect defines the effect to bind to the scene uniform buffer
  35358. * @param sceneUbo defines the uniform buffer storing scene data
  35359. */
  35360. Material.prototype.bindSceneUniformBuffer = function (effect, sceneUbo) {
  35361. sceneUbo.bindToEffect(effect, "Scene");
  35362. };
  35363. /**
  35364. * Binds the view matrix to the effect
  35365. * @param effect defines the effect to bind the view matrix to
  35366. */
  35367. Material.prototype.bindView = function (effect) {
  35368. if (!this._useUBO) {
  35369. effect.setMatrix("view", this.getScene().getViewMatrix());
  35370. }
  35371. else {
  35372. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  35373. }
  35374. };
  35375. /**
  35376. * Binds the view projection matrix to the effect
  35377. * @param effect defines the effect to bind the view projection matrix to
  35378. */
  35379. Material.prototype.bindViewProjection = function (effect) {
  35380. if (!this._useUBO) {
  35381. effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  35382. }
  35383. else {
  35384. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  35385. }
  35386. };
  35387. /**
  35388. * Specifies if material alpha testing should be turned on for the mesh
  35389. * @param mesh defines the mesh to check
  35390. */
  35391. Material.prototype._shouldTurnAlphaTestOn = function (mesh) {
  35392. return (!this.needAlphaBlendingForMesh(mesh) && this.needAlphaTesting());
  35393. };
  35394. /**
  35395. * Processes to execute after binding the material to a mesh
  35396. * @param mesh defines the rendered mesh
  35397. */
  35398. Material.prototype._afterBind = function (mesh) {
  35399. this._scene._cachedMaterial = this;
  35400. if (mesh) {
  35401. this._scene._cachedVisibility = mesh.visibility;
  35402. }
  35403. else {
  35404. this._scene._cachedVisibility = 1;
  35405. }
  35406. if (mesh) {
  35407. this.onBindObservable.notifyObservers(mesh);
  35408. }
  35409. if (this.disableDepthWrite) {
  35410. var engine = this._scene.getEngine();
  35411. this._cachedDepthWriteState = engine.getDepthWrite();
  35412. engine.setDepthWrite(false);
  35413. }
  35414. };
  35415. /**
  35416. * Unbinds the material from the mesh
  35417. */
  35418. Material.prototype.unbind = function () {
  35419. this.onUnBindObservable.notifyObservers(this);
  35420. if (this.disableDepthWrite) {
  35421. var engine = this._scene.getEngine();
  35422. engine.setDepthWrite(this._cachedDepthWriteState);
  35423. }
  35424. };
  35425. /**
  35426. * Gets the active textures from the material
  35427. * @returns an array of textures
  35428. */
  35429. Material.prototype.getActiveTextures = function () {
  35430. return [];
  35431. };
  35432. /**
  35433. * Specifies if the material uses a texture
  35434. * @param texture defines the texture to check against the material
  35435. * @returns a boolean specifying if the material uses the texture
  35436. */
  35437. Material.prototype.hasTexture = function (texture) {
  35438. return false;
  35439. };
  35440. /**
  35441. * Makes a duplicate of the material, and gives it a new name
  35442. * @param name defines the new name for the duplicated material
  35443. * @returns the cloned material
  35444. */
  35445. Material.prototype.clone = function (name) {
  35446. return null;
  35447. };
  35448. /**
  35449. * Gets the meshes bound to the material
  35450. * @returns an array of meshes bound to the material
  35451. */
  35452. Material.prototype.getBindedMeshes = function () {
  35453. var result = new Array();
  35454. for (var index = 0; index < this._scene.meshes.length; index++) {
  35455. var mesh = this._scene.meshes[index];
  35456. if (mesh.material === this) {
  35457. result.push(mesh);
  35458. }
  35459. }
  35460. return result;
  35461. };
  35462. /**
  35463. * Force shader compilation
  35464. * @param mesh defines the mesh associated with this material
  35465. * @param onCompiled defines a function to execute once the material is compiled
  35466. * @param options defines the options to configure the compilation
  35467. */
  35468. Material.prototype.forceCompilation = function (mesh, onCompiled, options) {
  35469. var _this = this;
  35470. var localOptions = __assign({ clipPlane: false }, options);
  35471. var subMesh = new BABYLON.BaseSubMesh();
  35472. var scene = this.getScene();
  35473. var checkReady = function () {
  35474. if (!_this._scene || !_this._scene.getEngine()) {
  35475. return;
  35476. }
  35477. if (subMesh._materialDefines) {
  35478. subMesh._materialDefines._renderId = -1;
  35479. }
  35480. var clipPlaneState = scene.clipPlane;
  35481. if (localOptions.clipPlane) {
  35482. scene.clipPlane = new BABYLON.Plane(0, 0, 0, 1);
  35483. }
  35484. if (_this.storeEffectOnSubMeshes) {
  35485. if (_this.isReadyForSubMesh(mesh, subMesh)) {
  35486. if (onCompiled) {
  35487. onCompiled(_this);
  35488. }
  35489. }
  35490. else {
  35491. setTimeout(checkReady, 16);
  35492. }
  35493. }
  35494. else {
  35495. if (_this.isReady(mesh)) {
  35496. if (onCompiled) {
  35497. onCompiled(_this);
  35498. }
  35499. }
  35500. else {
  35501. setTimeout(checkReady, 16);
  35502. }
  35503. }
  35504. if (localOptions.clipPlane) {
  35505. scene.clipPlane = clipPlaneState;
  35506. }
  35507. };
  35508. checkReady();
  35509. };
  35510. /**
  35511. * Force shader compilation
  35512. * @param mesh defines the mesh that will use this material
  35513. * @param options defines additional options for compiling the shaders
  35514. * @returns a promise that resolves when the compilation completes
  35515. */
  35516. Material.prototype.forceCompilationAsync = function (mesh, options) {
  35517. var _this = this;
  35518. return new Promise(function (resolve) {
  35519. _this.forceCompilation(mesh, function () {
  35520. resolve();
  35521. }, options);
  35522. });
  35523. };
  35524. /**
  35525. * Marks a define in the material to indicate that it needs to be re-computed
  35526. * @param flag defines a flag used to determine which parts of the material have to be marked as dirty
  35527. */
  35528. Material.prototype.markAsDirty = function (flag) {
  35529. if (flag & Material.TextureDirtyFlag) {
  35530. this._markAllSubMeshesAsTexturesDirty();
  35531. }
  35532. if (flag & Material.LightDirtyFlag) {
  35533. this._markAllSubMeshesAsLightsDirty();
  35534. }
  35535. if (flag & Material.FresnelDirtyFlag) {
  35536. this._markAllSubMeshesAsFresnelDirty();
  35537. }
  35538. if (flag & Material.AttributesDirtyFlag) {
  35539. this._markAllSubMeshesAsAttributesDirty();
  35540. }
  35541. if (flag & Material.MiscDirtyFlag) {
  35542. this._markAllSubMeshesAsMiscDirty();
  35543. }
  35544. this.getScene().resetCachedMaterial();
  35545. };
  35546. /**
  35547. * Marks all submeshes of a material to indicate that their material defines need to be re-calculated
  35548. * @param func defines a function which checks material defines against the submeshes
  35549. */
  35550. Material.prototype._markAllSubMeshesAsDirty = function (func) {
  35551. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  35552. var mesh = _a[_i];
  35553. if (!mesh.subMeshes) {
  35554. continue;
  35555. }
  35556. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  35557. var subMesh = _c[_b];
  35558. if (subMesh.getMaterial() !== this) {
  35559. continue;
  35560. }
  35561. if (!subMesh._materialDefines) {
  35562. continue;
  35563. }
  35564. func(subMesh._materialDefines);
  35565. }
  35566. }
  35567. };
  35568. /**
  35569. * Indicates that image processing needs to be re-calculated for all submeshes
  35570. */
  35571. Material.prototype._markAllSubMeshesAsImageProcessingDirty = function () {
  35572. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsImageProcessingDirty(); });
  35573. };
  35574. /**
  35575. * Indicates that textures need to be re-calculated for all submeshes
  35576. */
  35577. Material.prototype._markAllSubMeshesAsTexturesDirty = function () {
  35578. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsTexturesDirty(); });
  35579. };
  35580. /**
  35581. * Indicates that fresnel needs to be re-calculated for all submeshes
  35582. */
  35583. Material.prototype._markAllSubMeshesAsFresnelDirty = function () {
  35584. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsFresnelDirty(); });
  35585. };
  35586. /**
  35587. * Indicates that fresnel and misc need to be re-calculated for all submeshes
  35588. */
  35589. Material.prototype._markAllSubMeshesAsFresnelAndMiscDirty = function () {
  35590. this._markAllSubMeshesAsDirty(function (defines) {
  35591. defines.markAsFresnelDirty();
  35592. defines.markAsMiscDirty();
  35593. });
  35594. };
  35595. /**
  35596. * Indicates that lights need to be re-calculated for all submeshes
  35597. */
  35598. Material.prototype._markAllSubMeshesAsLightsDirty = function () {
  35599. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  35600. };
  35601. /**
  35602. * Indicates that attributes need to be re-calculated for all submeshes
  35603. */
  35604. Material.prototype._markAllSubMeshesAsAttributesDirty = function () {
  35605. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  35606. };
  35607. /**
  35608. * Indicates that misc needs to be re-calculated for all submeshes
  35609. */
  35610. Material.prototype._markAllSubMeshesAsMiscDirty = function () {
  35611. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsMiscDirty(); });
  35612. };
  35613. /**
  35614. * Indicates that textures and misc need to be re-calculated for all submeshes
  35615. */
  35616. Material.prototype._markAllSubMeshesAsTexturesAndMiscDirty = function () {
  35617. this._markAllSubMeshesAsDirty(function (defines) {
  35618. defines.markAsTexturesDirty();
  35619. defines.markAsMiscDirty();
  35620. });
  35621. };
  35622. /**
  35623. * Disposes the material
  35624. * @param forceDisposeEffect specifies if effects should be forcefully disposed
  35625. * @param forceDisposeTextures specifies if textures should be forcefully disposed
  35626. */
  35627. Material.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  35628. // Animations
  35629. this.getScene().stopAnimation(this);
  35630. this.getScene().freeProcessedMaterials();
  35631. // Remove from scene
  35632. var index = this._scene.materials.indexOf(this);
  35633. if (index >= 0) {
  35634. this._scene.materials.splice(index, 1);
  35635. }
  35636. // Remove from meshes
  35637. for (index = 0; index < this._scene.meshes.length; index++) {
  35638. var mesh = this._scene.meshes[index];
  35639. if (mesh.material === this) {
  35640. mesh.material = null;
  35641. if (mesh.geometry) {
  35642. var geometry = (mesh.geometry);
  35643. if (this.storeEffectOnSubMeshes) {
  35644. for (var _i = 0, _a = mesh.subMeshes; _i < _a.length; _i++) {
  35645. var subMesh = _a[_i];
  35646. geometry._releaseVertexArrayObject(subMesh._materialEffect);
  35647. if (forceDisposeEffect && subMesh._materialEffect) {
  35648. this._scene.getEngine()._releaseEffect(subMesh._materialEffect);
  35649. }
  35650. }
  35651. }
  35652. else {
  35653. geometry._releaseVertexArrayObject(this._effect);
  35654. }
  35655. }
  35656. }
  35657. }
  35658. this._uniformBuffer.dispose();
  35659. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  35660. if (forceDisposeEffect && this._effect) {
  35661. if (!this.storeEffectOnSubMeshes) {
  35662. this._scene.getEngine()._releaseEffect(this._effect);
  35663. }
  35664. this._effect = null;
  35665. }
  35666. // Callback
  35667. this.onDisposeObservable.notifyObservers(this);
  35668. this.onDisposeObservable.clear();
  35669. this.onBindObservable.clear();
  35670. this.onUnBindObservable.clear();
  35671. };
  35672. /**
  35673. * Serializes this material
  35674. * @returns the serialized material object
  35675. */
  35676. Material.prototype.serialize = function () {
  35677. return BABYLON.SerializationHelper.Serialize(this);
  35678. };
  35679. /**
  35680. * Creates a MultiMaterial from parsed MultiMaterial data.
  35681. * @param parsedMultiMaterial defines parsed MultiMaterial data.
  35682. * @param scene defines the hosting scene
  35683. * @returns a new MultiMaterial
  35684. */
  35685. Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) {
  35686. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  35687. multiMaterial.id = parsedMultiMaterial.id;
  35688. if (BABYLON.Tags) {
  35689. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  35690. }
  35691. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  35692. var subMatId = parsedMultiMaterial.materials[matIndex];
  35693. if (subMatId) {
  35694. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  35695. }
  35696. else {
  35697. multiMaterial.subMaterials.push(null);
  35698. }
  35699. }
  35700. return multiMaterial;
  35701. };
  35702. /**
  35703. * Creates a material from parsed material data
  35704. * @param parsedMaterial defines parsed material data
  35705. * @param scene defines the hosting scene
  35706. * @param rootUrl defines the root URL to use to load textures
  35707. * @returns a new material
  35708. */
  35709. Material.Parse = function (parsedMaterial, scene, rootUrl) {
  35710. if (!parsedMaterial.customType || parsedMaterial.customType === "BABYLON.StandardMaterial") {
  35711. return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
  35712. }
  35713. if (parsedMaterial.customType === "BABYLON.PBRMaterial" && parsedMaterial.overloadedAlbedo) {
  35714. parsedMaterial.customType = "BABYLON.LegacyPBRMaterial";
  35715. if (!BABYLON.LegacyPBRMaterial) {
  35716. BABYLON.Tools.Error("Your scene is trying to load a legacy version of the PBRMaterial, please, include it from the materials library.");
  35717. return;
  35718. }
  35719. }
  35720. var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType);
  35721. return materialType.Parse(parsedMaterial, scene, rootUrl);
  35722. };
  35723. // Triangle views
  35724. Material._TriangleFillMode = 0;
  35725. Material._WireFrameFillMode = 1;
  35726. Material._PointFillMode = 2;
  35727. // Draw modes
  35728. Material._PointListDrawMode = 3;
  35729. Material._LineListDrawMode = 4;
  35730. Material._LineLoopDrawMode = 5;
  35731. Material._LineStripDrawMode = 6;
  35732. Material._TriangleStripDrawMode = 7;
  35733. Material._TriangleFanDrawMode = 8;
  35734. /**
  35735. * Stores the clock-wise side orientation
  35736. */
  35737. Material._ClockWiseSideOrientation = 0;
  35738. /**
  35739. * Stores the counter clock-wise side orientation
  35740. */
  35741. Material._CounterClockWiseSideOrientation = 1;
  35742. /**
  35743. * The dirty texture flag value
  35744. */
  35745. Material._TextureDirtyFlag = 1;
  35746. /**
  35747. * The dirty light flag value
  35748. */
  35749. Material._LightDirtyFlag = 2;
  35750. /**
  35751. * The dirty fresnel flag value
  35752. */
  35753. Material._FresnelDirtyFlag = 4;
  35754. /**
  35755. * The dirty attribute flag value
  35756. */
  35757. Material._AttributesDirtyFlag = 8;
  35758. /**
  35759. * The dirty misc flag value
  35760. */
  35761. Material._MiscDirtyFlag = 16;
  35762. __decorate([
  35763. BABYLON.serialize()
  35764. ], Material.prototype, "id", void 0);
  35765. __decorate([
  35766. BABYLON.serialize()
  35767. ], Material.prototype, "uniqueId", void 0);
  35768. __decorate([
  35769. BABYLON.serialize()
  35770. ], Material.prototype, "name", void 0);
  35771. __decorate([
  35772. BABYLON.serialize()
  35773. ], Material.prototype, "checkReadyOnEveryCall", void 0);
  35774. __decorate([
  35775. BABYLON.serialize()
  35776. ], Material.prototype, "checkReadyOnlyOnce", void 0);
  35777. __decorate([
  35778. BABYLON.serialize()
  35779. ], Material.prototype, "state", void 0);
  35780. __decorate([
  35781. BABYLON.serialize("alpha")
  35782. ], Material.prototype, "_alpha", void 0);
  35783. __decorate([
  35784. BABYLON.serialize("backFaceCulling")
  35785. ], Material.prototype, "_backFaceCulling", void 0);
  35786. __decorate([
  35787. BABYLON.serialize()
  35788. ], Material.prototype, "sideOrientation", void 0);
  35789. __decorate([
  35790. BABYLON.serialize("alphaMode")
  35791. ], Material.prototype, "_alphaMode", void 0);
  35792. __decorate([
  35793. BABYLON.serialize()
  35794. ], Material.prototype, "_needDepthPrePass", void 0);
  35795. __decorate([
  35796. BABYLON.serialize()
  35797. ], Material.prototype, "disableDepthWrite", void 0);
  35798. __decorate([
  35799. BABYLON.serialize()
  35800. ], Material.prototype, "forceDepthWrite", void 0);
  35801. __decorate([
  35802. BABYLON.serialize()
  35803. ], Material.prototype, "separateCullingPass", void 0);
  35804. __decorate([
  35805. BABYLON.serialize("fogEnabled")
  35806. ], Material.prototype, "_fogEnabled", void 0);
  35807. __decorate([
  35808. BABYLON.serialize()
  35809. ], Material.prototype, "pointSize", void 0);
  35810. __decorate([
  35811. BABYLON.serialize()
  35812. ], Material.prototype, "zOffset", void 0);
  35813. __decorate([
  35814. BABYLON.serialize()
  35815. ], Material.prototype, "wireframe", null);
  35816. __decorate([
  35817. BABYLON.serialize()
  35818. ], Material.prototype, "pointsCloud", null);
  35819. __decorate([
  35820. BABYLON.serialize()
  35821. ], Material.prototype, "fillMode", null);
  35822. return Material;
  35823. }());
  35824. BABYLON.Material = Material;
  35825. })(BABYLON || (BABYLON = {}));
  35826. //# sourceMappingURL=babylon.material.js.map
  35827. var BABYLON;
  35828. (function (BABYLON) {
  35829. var UniformBuffer = /** @class */ (function () {
  35830. /**
  35831. * Uniform buffer objects.
  35832. *
  35833. * Handles blocks of uniform on the GPU.
  35834. *
  35835. * If WebGL 2 is not available, this class falls back on traditionnal setUniformXXX calls.
  35836. *
  35837. * For more information, please refer to :
  35838. * https://www.khronos.org/opengl/wiki/Uniform_Buffer_Object
  35839. */
  35840. function UniformBuffer(engine, data, dynamic) {
  35841. this._engine = engine;
  35842. this._noUBO = !engine.supportsUniformBuffers;
  35843. this._dynamic = dynamic;
  35844. this._data = data || [];
  35845. this._uniformLocations = {};
  35846. this._uniformSizes = {};
  35847. this._uniformLocationPointer = 0;
  35848. this._needSync = false;
  35849. if (this._noUBO) {
  35850. this.updateMatrix3x3 = this._updateMatrix3x3ForEffect;
  35851. this.updateMatrix2x2 = this._updateMatrix2x2ForEffect;
  35852. this.updateFloat = this._updateFloatForEffect;
  35853. this.updateFloat2 = this._updateFloat2ForEffect;
  35854. this.updateFloat3 = this._updateFloat3ForEffect;
  35855. this.updateFloat4 = this._updateFloat4ForEffect;
  35856. this.updateMatrix = this._updateMatrixForEffect;
  35857. this.updateVector3 = this._updateVector3ForEffect;
  35858. this.updateVector4 = this._updateVector4ForEffect;
  35859. this.updateColor3 = this._updateColor3ForEffect;
  35860. this.updateColor4 = this._updateColor4ForEffect;
  35861. }
  35862. else {
  35863. this._engine._uniformBuffers.push(this);
  35864. this.updateMatrix3x3 = this._updateMatrix3x3ForUniform;
  35865. this.updateMatrix2x2 = this._updateMatrix2x2ForUniform;
  35866. this.updateFloat = this._updateFloatForUniform;
  35867. this.updateFloat2 = this._updateFloat2ForUniform;
  35868. this.updateFloat3 = this._updateFloat3ForUniform;
  35869. this.updateFloat4 = this._updateFloat4ForUniform;
  35870. this.updateMatrix = this._updateMatrixForUniform;
  35871. this.updateVector3 = this._updateVector3ForUniform;
  35872. this.updateVector4 = this._updateVector4ForUniform;
  35873. this.updateColor3 = this._updateColor3ForUniform;
  35874. this.updateColor4 = this._updateColor4ForUniform;
  35875. }
  35876. }
  35877. Object.defineProperty(UniformBuffer.prototype, "useUbo", {
  35878. // Properties
  35879. /**
  35880. * Indicates if the buffer is using the WebGL2 UBO implementation,
  35881. * or just falling back on setUniformXXX calls.
  35882. */
  35883. get: function () {
  35884. return !this._noUBO;
  35885. },
  35886. enumerable: true,
  35887. configurable: true
  35888. });
  35889. Object.defineProperty(UniformBuffer.prototype, "isSync", {
  35890. /**
  35891. * Indicates if the WebGL underlying uniform buffer is in sync
  35892. * with the javascript cache data.
  35893. */
  35894. get: function () {
  35895. return !this._needSync;
  35896. },
  35897. enumerable: true,
  35898. configurable: true
  35899. });
  35900. /**
  35901. * Indicates if the WebGL underlying uniform buffer is dynamic.
  35902. * Also, a dynamic UniformBuffer will disable cache verification and always
  35903. * update the underlying WebGL uniform buffer to the GPU.
  35904. */
  35905. UniformBuffer.prototype.isDynamic = function () {
  35906. return this._dynamic !== undefined;
  35907. };
  35908. /**
  35909. * The data cache on JS side.
  35910. */
  35911. UniformBuffer.prototype.getData = function () {
  35912. return this._bufferData;
  35913. };
  35914. /**
  35915. * The underlying WebGL Uniform buffer.
  35916. */
  35917. UniformBuffer.prototype.getBuffer = function () {
  35918. return this._buffer;
  35919. };
  35920. /**
  35921. * std140 layout specifies how to align data within an UBO structure.
  35922. * See https://khronos.org/registry/OpenGL/specs/gl/glspec45.core.pdf#page=159
  35923. * for specs.
  35924. */
  35925. UniformBuffer.prototype._fillAlignment = function (size) {
  35926. // This code has been simplified because we only use floats, vectors of 1, 2, 3, 4 components
  35927. // and 4x4 matrices
  35928. // TODO : change if other types are used
  35929. var alignment;
  35930. if (size <= 2) {
  35931. alignment = size;
  35932. }
  35933. else {
  35934. alignment = 4;
  35935. }
  35936. if ((this._uniformLocationPointer % alignment) !== 0) {
  35937. var oldPointer = this._uniformLocationPointer;
  35938. this._uniformLocationPointer += alignment - (this._uniformLocationPointer % alignment);
  35939. var diff = this._uniformLocationPointer - oldPointer;
  35940. for (var i = 0; i < diff; i++) {
  35941. this._data.push(0);
  35942. }
  35943. }
  35944. };
  35945. /**
  35946. * Adds an uniform in the buffer.
  35947. * Warning : the subsequents calls of this function must be in the same order as declared in the shader
  35948. * for the layout to be correct !
  35949. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35950. * @param {number|number[]} size Data size, or data directly.
  35951. */
  35952. UniformBuffer.prototype.addUniform = function (name, size) {
  35953. if (this._noUBO) {
  35954. return;
  35955. }
  35956. if (this._uniformLocations[name] !== undefined) {
  35957. // Already existing uniform
  35958. return;
  35959. }
  35960. // This function must be called in the order of the shader layout !
  35961. // size can be the size of the uniform, or data directly
  35962. var data;
  35963. if (size instanceof Array) {
  35964. data = size;
  35965. size = data.length;
  35966. }
  35967. else {
  35968. size = size;
  35969. data = [];
  35970. // Fill with zeros
  35971. for (var i = 0; i < size; i++) {
  35972. data.push(0);
  35973. }
  35974. }
  35975. this._fillAlignment(size);
  35976. this._uniformSizes[name] = size;
  35977. this._uniformLocations[name] = this._uniformLocationPointer;
  35978. this._uniformLocationPointer += size;
  35979. for (var i = 0; i < size; i++) {
  35980. this._data.push(data[i]);
  35981. }
  35982. this._needSync = true;
  35983. };
  35984. /**
  35985. * Wrapper for addUniform.
  35986. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35987. * @param {Matrix} mat A 4x4 matrix.
  35988. */
  35989. UniformBuffer.prototype.addMatrix = function (name, mat) {
  35990. this.addUniform(name, Array.prototype.slice.call(mat.toArray()));
  35991. };
  35992. /**
  35993. * Wrapper for addUniform.
  35994. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35995. * @param {number} x
  35996. * @param {number} y
  35997. */
  35998. UniformBuffer.prototype.addFloat2 = function (name, x, y) {
  35999. var temp = [x, y];
  36000. this.addUniform(name, temp);
  36001. };
  36002. /**
  36003. * Wrapper for addUniform.
  36004. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36005. * @param {number} x
  36006. * @param {number} y
  36007. * @param {number} z
  36008. */
  36009. UniformBuffer.prototype.addFloat3 = function (name, x, y, z) {
  36010. var temp = [x, y, z];
  36011. this.addUniform(name, temp);
  36012. };
  36013. /**
  36014. * Wrapper for addUniform.
  36015. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36016. * @param {Color3} color
  36017. */
  36018. UniformBuffer.prototype.addColor3 = function (name, color) {
  36019. var temp = new Array();
  36020. color.toArray(temp);
  36021. this.addUniform(name, temp);
  36022. };
  36023. /**
  36024. * Wrapper for addUniform.
  36025. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36026. * @param {Color3} color
  36027. * @param {number} alpha
  36028. */
  36029. UniformBuffer.prototype.addColor4 = function (name, color, alpha) {
  36030. var temp = new Array();
  36031. color.toArray(temp);
  36032. temp.push(alpha);
  36033. this.addUniform(name, temp);
  36034. };
  36035. /**
  36036. * Wrapper for addUniform.
  36037. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36038. * @param {Vector3} vector
  36039. */
  36040. UniformBuffer.prototype.addVector3 = function (name, vector) {
  36041. var temp = new Array();
  36042. vector.toArray(temp);
  36043. this.addUniform(name, temp);
  36044. };
  36045. /**
  36046. * Wrapper for addUniform.
  36047. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36048. */
  36049. UniformBuffer.prototype.addMatrix3x3 = function (name) {
  36050. this.addUniform(name, 12);
  36051. };
  36052. /**
  36053. * Wrapper for addUniform.
  36054. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36055. */
  36056. UniformBuffer.prototype.addMatrix2x2 = function (name) {
  36057. this.addUniform(name, 8);
  36058. };
  36059. /**
  36060. * Effectively creates the WebGL Uniform Buffer, once layout is completed with `addUniform`.
  36061. */
  36062. UniformBuffer.prototype.create = function () {
  36063. if (this._noUBO) {
  36064. return;
  36065. }
  36066. if (this._buffer) {
  36067. return; // nothing to do
  36068. }
  36069. // See spec, alignment must be filled as a vec4
  36070. this._fillAlignment(4);
  36071. this._bufferData = new Float32Array(this._data);
  36072. this._rebuild();
  36073. this._needSync = true;
  36074. };
  36075. UniformBuffer.prototype._rebuild = function () {
  36076. if (this._noUBO) {
  36077. return;
  36078. }
  36079. if (this._dynamic) {
  36080. this._buffer = this._engine.createDynamicUniformBuffer(this._bufferData);
  36081. }
  36082. else {
  36083. this._buffer = this._engine.createUniformBuffer(this._bufferData);
  36084. }
  36085. };
  36086. /**
  36087. * Updates the WebGL Uniform Buffer on the GPU.
  36088. * If the `dynamic` flag is set to true, no cache comparison is done.
  36089. * Otherwise, the buffer will be updated only if the cache differs.
  36090. */
  36091. UniformBuffer.prototype.update = function () {
  36092. if (!this._buffer) {
  36093. this.create();
  36094. return;
  36095. }
  36096. if (!this._dynamic && !this._needSync) {
  36097. return;
  36098. }
  36099. this._engine.updateUniformBuffer(this._buffer, this._bufferData);
  36100. this._needSync = false;
  36101. };
  36102. /**
  36103. * Updates the value of an uniform. The `update` method must be called afterwards to make it effective in the GPU.
  36104. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  36105. * @param {number[]|Float32Array} data Flattened data
  36106. * @param {number} size Size of the data.
  36107. */
  36108. UniformBuffer.prototype.updateUniform = function (uniformName, data, size) {
  36109. var location = this._uniformLocations[uniformName];
  36110. if (location === undefined) {
  36111. if (this._buffer) {
  36112. // Cannot add an uniform if the buffer is already created
  36113. BABYLON.Tools.Error("Cannot add an uniform after UBO has been created.");
  36114. return;
  36115. }
  36116. this.addUniform(uniformName, size);
  36117. location = this._uniformLocations[uniformName];
  36118. }
  36119. if (!this._buffer) {
  36120. this.create();
  36121. }
  36122. if (!this._dynamic) {
  36123. // Cache for static uniform buffers
  36124. var changed = false;
  36125. for (var i = 0; i < size; i++) {
  36126. if (this._bufferData[location + i] !== data[i]) {
  36127. changed = true;
  36128. this._bufferData[location + i] = data[i];
  36129. }
  36130. }
  36131. this._needSync = this._needSync || changed;
  36132. }
  36133. else {
  36134. // No cache for dynamic
  36135. for (var i = 0; i < size; i++) {
  36136. this._bufferData[location + i] = data[i];
  36137. }
  36138. }
  36139. };
  36140. // Update methods
  36141. UniformBuffer.prototype._updateMatrix3x3ForUniform = function (name, matrix) {
  36142. // To match std140, matrix must be realigned
  36143. for (var i = 0; i < 3; i++) {
  36144. UniformBuffer._tempBuffer[i * 4] = matrix[i * 3];
  36145. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 3 + 1];
  36146. UniformBuffer._tempBuffer[i * 4 + 2] = matrix[i * 3 + 2];
  36147. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  36148. }
  36149. this.updateUniform(name, UniformBuffer._tempBuffer, 12);
  36150. };
  36151. UniformBuffer.prototype._updateMatrix3x3ForEffect = function (name, matrix) {
  36152. this._currentEffect.setMatrix3x3(name, matrix);
  36153. };
  36154. UniformBuffer.prototype._updateMatrix2x2ForEffect = function (name, matrix) {
  36155. this._currentEffect.setMatrix2x2(name, matrix);
  36156. };
  36157. UniformBuffer.prototype._updateMatrix2x2ForUniform = function (name, matrix) {
  36158. // To match std140, matrix must be realigned
  36159. for (var i = 0; i < 2; i++) {
  36160. UniformBuffer._tempBuffer[i * 4] = matrix[i * 2];
  36161. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 2 + 1];
  36162. UniformBuffer._tempBuffer[i * 4 + 2] = 0.0;
  36163. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  36164. }
  36165. this.updateUniform(name, UniformBuffer._tempBuffer, 8);
  36166. };
  36167. UniformBuffer.prototype._updateFloatForEffect = function (name, x) {
  36168. this._currentEffect.setFloat(name, x);
  36169. };
  36170. UniformBuffer.prototype._updateFloatForUniform = function (name, x) {
  36171. UniformBuffer._tempBuffer[0] = x;
  36172. this.updateUniform(name, UniformBuffer._tempBuffer, 1);
  36173. };
  36174. UniformBuffer.prototype._updateFloat2ForEffect = function (name, x, y, suffix) {
  36175. if (suffix === void 0) { suffix = ""; }
  36176. this._currentEffect.setFloat2(name + suffix, x, y);
  36177. };
  36178. UniformBuffer.prototype._updateFloat2ForUniform = function (name, x, y, suffix) {
  36179. if (suffix === void 0) { suffix = ""; }
  36180. UniformBuffer._tempBuffer[0] = x;
  36181. UniformBuffer._tempBuffer[1] = y;
  36182. this.updateUniform(name, UniformBuffer._tempBuffer, 2);
  36183. };
  36184. UniformBuffer.prototype._updateFloat3ForEffect = function (name, x, y, z, suffix) {
  36185. if (suffix === void 0) { suffix = ""; }
  36186. this._currentEffect.setFloat3(name + suffix, x, y, z);
  36187. };
  36188. UniformBuffer.prototype._updateFloat3ForUniform = function (name, x, y, z, suffix) {
  36189. if (suffix === void 0) { suffix = ""; }
  36190. UniformBuffer._tempBuffer[0] = x;
  36191. UniformBuffer._tempBuffer[1] = y;
  36192. UniformBuffer._tempBuffer[2] = z;
  36193. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  36194. };
  36195. UniformBuffer.prototype._updateFloat4ForEffect = function (name, x, y, z, w, suffix) {
  36196. if (suffix === void 0) { suffix = ""; }
  36197. this._currentEffect.setFloat4(name + suffix, x, y, z, w);
  36198. };
  36199. UniformBuffer.prototype._updateFloat4ForUniform = function (name, x, y, z, w, suffix) {
  36200. if (suffix === void 0) { suffix = ""; }
  36201. UniformBuffer._tempBuffer[0] = x;
  36202. UniformBuffer._tempBuffer[1] = y;
  36203. UniformBuffer._tempBuffer[2] = z;
  36204. UniformBuffer._tempBuffer[3] = w;
  36205. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  36206. };
  36207. UniformBuffer.prototype._updateMatrixForEffect = function (name, mat) {
  36208. this._currentEffect.setMatrix(name, mat);
  36209. };
  36210. UniformBuffer.prototype._updateMatrixForUniform = function (name, mat) {
  36211. this.updateUniform(name, mat.toArray(), 16);
  36212. };
  36213. UniformBuffer.prototype._updateVector3ForEffect = function (name, vector) {
  36214. this._currentEffect.setVector3(name, vector);
  36215. };
  36216. UniformBuffer.prototype._updateVector3ForUniform = function (name, vector) {
  36217. vector.toArray(UniformBuffer._tempBuffer);
  36218. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  36219. };
  36220. UniformBuffer.prototype._updateVector4ForEffect = function (name, vector) {
  36221. this._currentEffect.setVector4(name, vector);
  36222. };
  36223. UniformBuffer.prototype._updateVector4ForUniform = function (name, vector) {
  36224. vector.toArray(UniformBuffer._tempBuffer);
  36225. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  36226. };
  36227. UniformBuffer.prototype._updateColor3ForEffect = function (name, color, suffix) {
  36228. if (suffix === void 0) { suffix = ""; }
  36229. this._currentEffect.setColor3(name + suffix, color);
  36230. };
  36231. UniformBuffer.prototype._updateColor3ForUniform = function (name, color, suffix) {
  36232. if (suffix === void 0) { suffix = ""; }
  36233. color.toArray(UniformBuffer._tempBuffer);
  36234. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  36235. };
  36236. UniformBuffer.prototype._updateColor4ForEffect = function (name, color, alpha, suffix) {
  36237. if (suffix === void 0) { suffix = ""; }
  36238. this._currentEffect.setColor4(name + suffix, color, alpha);
  36239. };
  36240. UniformBuffer.prototype._updateColor4ForUniform = function (name, color, alpha, suffix) {
  36241. if (suffix === void 0) { suffix = ""; }
  36242. color.toArray(UniformBuffer._tempBuffer);
  36243. UniformBuffer._tempBuffer[3] = alpha;
  36244. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  36245. };
  36246. /**
  36247. * Sets a sampler uniform on the effect.
  36248. * @param {string} name Name of the sampler.
  36249. * @param {Texture} texture
  36250. */
  36251. UniformBuffer.prototype.setTexture = function (name, texture) {
  36252. this._currentEffect.setTexture(name, texture);
  36253. };
  36254. /**
  36255. * Directly updates the value of the uniform in the cache AND on the GPU.
  36256. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  36257. * @param {number[]|Float32Array} data Flattened data
  36258. */
  36259. UniformBuffer.prototype.updateUniformDirectly = function (uniformName, data) {
  36260. this.updateUniform(uniformName, data, data.length);
  36261. this.update();
  36262. };
  36263. /**
  36264. * Binds this uniform buffer to an effect.
  36265. * @param {Effect} effect
  36266. * @param {string} name Name of the uniform block in the shader.
  36267. */
  36268. UniformBuffer.prototype.bindToEffect = function (effect, name) {
  36269. this._currentEffect = effect;
  36270. if (this._noUBO || !this._buffer) {
  36271. return;
  36272. }
  36273. effect.bindUniformBuffer(this._buffer, name);
  36274. };
  36275. /**
  36276. * Disposes the uniform buffer.
  36277. */
  36278. UniformBuffer.prototype.dispose = function () {
  36279. if (this._noUBO) {
  36280. return;
  36281. }
  36282. var index = this._engine._uniformBuffers.indexOf(this);
  36283. if (index !== -1) {
  36284. this._engine._uniformBuffers.splice(index, 1);
  36285. }
  36286. if (!this._buffer) {
  36287. return;
  36288. }
  36289. if (this._engine._releaseBuffer(this._buffer)) {
  36290. this._buffer = null;
  36291. }
  36292. };
  36293. // Pool for avoiding memory leaks
  36294. UniformBuffer._MAX_UNIFORM_SIZE = 256;
  36295. UniformBuffer._tempBuffer = new Float32Array(UniformBuffer._MAX_UNIFORM_SIZE);
  36296. return UniformBuffer;
  36297. }());
  36298. BABYLON.UniformBuffer = UniformBuffer;
  36299. })(BABYLON || (BABYLON = {}));
  36300. //# sourceMappingURL=babylon.uniformBuffer.js.map
  36301. var BABYLON;
  36302. (function (BABYLON) {
  36303. /**
  36304. * This class contains the various kinds of data on every vertex of a mesh used in determining its shape and appearance
  36305. */
  36306. var VertexData = /** @class */ (function () {
  36307. function VertexData() {
  36308. }
  36309. /**
  36310. * Uses the passed data array to set the set the values for the specified kind of data
  36311. * @param data a linear array of floating numbers
  36312. * @param kind the type of data that is being set, eg positions, colors etc
  36313. */
  36314. VertexData.prototype.set = function (data, kind) {
  36315. switch (kind) {
  36316. case BABYLON.VertexBuffer.PositionKind:
  36317. this.positions = data;
  36318. break;
  36319. case BABYLON.VertexBuffer.NormalKind:
  36320. this.normals = data;
  36321. break;
  36322. case BABYLON.VertexBuffer.TangentKind:
  36323. this.tangents = data;
  36324. break;
  36325. case BABYLON.VertexBuffer.UVKind:
  36326. this.uvs = data;
  36327. break;
  36328. case BABYLON.VertexBuffer.UV2Kind:
  36329. this.uvs2 = data;
  36330. break;
  36331. case BABYLON.VertexBuffer.UV3Kind:
  36332. this.uvs3 = data;
  36333. break;
  36334. case BABYLON.VertexBuffer.UV4Kind:
  36335. this.uvs4 = data;
  36336. break;
  36337. case BABYLON.VertexBuffer.UV5Kind:
  36338. this.uvs5 = data;
  36339. break;
  36340. case BABYLON.VertexBuffer.UV6Kind:
  36341. this.uvs6 = data;
  36342. break;
  36343. case BABYLON.VertexBuffer.ColorKind:
  36344. this.colors = data;
  36345. break;
  36346. case BABYLON.VertexBuffer.MatricesIndicesKind:
  36347. this.matricesIndices = data;
  36348. break;
  36349. case BABYLON.VertexBuffer.MatricesWeightsKind:
  36350. this.matricesWeights = data;
  36351. break;
  36352. case BABYLON.VertexBuffer.MatricesIndicesExtraKind:
  36353. this.matricesIndicesExtra = data;
  36354. break;
  36355. case BABYLON.VertexBuffer.MatricesWeightsExtraKind:
  36356. this.matricesWeightsExtra = data;
  36357. break;
  36358. }
  36359. };
  36360. /**
  36361. * Associates the vertexData to the passed Mesh.
  36362. * Sets it as updatable or not (default `false`)
  36363. * @param mesh the mesh the vertexData is applied to
  36364. * @param updatable when used and having the value true allows new data to update the vertexData
  36365. * @returns the VertexData
  36366. */
  36367. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  36368. this._applyTo(mesh, updatable);
  36369. return this;
  36370. };
  36371. /**
  36372. * Associates the vertexData to the passed Geometry.
  36373. * Sets it as updatable or not (default `false`)
  36374. * @param geometry the geometry the vertexData is applied to
  36375. * @param updatable when used and having the value true allows new data to update the vertexData
  36376. * @returns VertexData
  36377. */
  36378. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  36379. this._applyTo(geometry, updatable);
  36380. return this;
  36381. };
  36382. /**
  36383. * Updates the associated mesh
  36384. * @param mesh the mesh to be updated
  36385. * @param updateExtends when true the mesh BoundingInfo will be renewed when and if position kind is updated, optional with default false
  36386. * @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
  36387. * @returns VertexData
  36388. */
  36389. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  36390. this._update(mesh);
  36391. return this;
  36392. };
  36393. /**
  36394. * Updates the associated geometry
  36395. * @param geometry the geometry to be updated
  36396. * @param updateExtends when true BoundingInfo will be renewed when and if position kind is updated, optional with default false
  36397. * @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
  36398. * @returns VertexData.
  36399. */
  36400. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  36401. this._update(geometry);
  36402. return this;
  36403. };
  36404. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  36405. if (updatable === void 0) { updatable = false; }
  36406. if (this.positions) {
  36407. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  36408. }
  36409. if (this.normals) {
  36410. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  36411. }
  36412. if (this.tangents) {
  36413. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updatable);
  36414. }
  36415. if (this.uvs) {
  36416. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  36417. }
  36418. if (this.uvs2) {
  36419. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  36420. }
  36421. if (this.uvs3) {
  36422. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  36423. }
  36424. if (this.uvs4) {
  36425. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  36426. }
  36427. if (this.uvs5) {
  36428. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  36429. }
  36430. if (this.uvs6) {
  36431. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  36432. }
  36433. if (this.colors) {
  36434. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  36435. }
  36436. if (this.matricesIndices) {
  36437. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  36438. }
  36439. if (this.matricesWeights) {
  36440. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  36441. }
  36442. if (this.matricesIndicesExtra) {
  36443. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
  36444. }
  36445. if (this.matricesWeightsExtra) {
  36446. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
  36447. }
  36448. if (this.indices) {
  36449. meshOrGeometry.setIndices(this.indices, null, updatable);
  36450. }
  36451. return this;
  36452. };
  36453. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  36454. if (this.positions) {
  36455. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  36456. }
  36457. if (this.normals) {
  36458. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  36459. }
  36460. if (this.tangents) {
  36461. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updateExtends, makeItUnique);
  36462. }
  36463. if (this.uvs) {
  36464. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  36465. }
  36466. if (this.uvs2) {
  36467. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  36468. }
  36469. if (this.uvs3) {
  36470. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  36471. }
  36472. if (this.uvs4) {
  36473. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  36474. }
  36475. if (this.uvs5) {
  36476. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  36477. }
  36478. if (this.uvs6) {
  36479. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  36480. }
  36481. if (this.colors) {
  36482. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  36483. }
  36484. if (this.matricesIndices) {
  36485. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  36486. }
  36487. if (this.matricesWeights) {
  36488. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  36489. }
  36490. if (this.matricesIndicesExtra) {
  36491. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
  36492. }
  36493. if (this.matricesWeightsExtra) {
  36494. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
  36495. }
  36496. if (this.indices) {
  36497. meshOrGeometry.setIndices(this.indices, null);
  36498. }
  36499. return this;
  36500. };
  36501. /**
  36502. * Transforms each position and each normal of the vertexData according to the passed Matrix
  36503. * @param matrix the transforming matrix
  36504. * @returns the VertexData
  36505. */
  36506. VertexData.prototype.transform = function (matrix) {
  36507. var transformed = BABYLON.Vector3.Zero();
  36508. var index;
  36509. if (this.positions) {
  36510. var position = BABYLON.Vector3.Zero();
  36511. for (index = 0; index < this.positions.length; index += 3) {
  36512. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  36513. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  36514. this.positions[index] = transformed.x;
  36515. this.positions[index + 1] = transformed.y;
  36516. this.positions[index + 2] = transformed.z;
  36517. }
  36518. }
  36519. if (this.normals) {
  36520. var normal = BABYLON.Vector3.Zero();
  36521. for (index = 0; index < this.normals.length; index += 3) {
  36522. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  36523. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  36524. this.normals[index] = transformed.x;
  36525. this.normals[index + 1] = transformed.y;
  36526. this.normals[index + 2] = transformed.z;
  36527. }
  36528. }
  36529. if (this.tangents) {
  36530. var tangent = BABYLON.Vector4.Zero();
  36531. var tangentTransformed = BABYLON.Vector4.Zero();
  36532. for (index = 0; index < this.tangents.length; index += 4) {
  36533. BABYLON.Vector4.FromArrayToRef(this.tangents, index, tangent);
  36534. BABYLON.Vector4.TransformNormalToRef(tangent, matrix, tangentTransformed);
  36535. this.tangents[index] = tangentTransformed.x;
  36536. this.tangents[index + 1] = tangentTransformed.y;
  36537. this.tangents[index + 2] = tangentTransformed.z;
  36538. this.tangents[index + 3] = tangentTransformed.w;
  36539. }
  36540. }
  36541. return this;
  36542. };
  36543. /**
  36544. * Merges the passed VertexData into the current one
  36545. * @param other the VertexData to be merged into the current one
  36546. * @returns the modified VertexData
  36547. */
  36548. VertexData.prototype.merge = function (other) {
  36549. this._validate();
  36550. other._validate();
  36551. if (!this.normals !== !other.normals ||
  36552. !this.tangents !== !other.tangents ||
  36553. !this.uvs !== !other.uvs ||
  36554. !this.uvs2 !== !other.uvs2 ||
  36555. !this.uvs3 !== !other.uvs3 ||
  36556. !this.uvs4 !== !other.uvs4 ||
  36557. !this.uvs5 !== !other.uvs5 ||
  36558. !this.uvs6 !== !other.uvs6 ||
  36559. !this.colors !== !other.colors ||
  36560. !this.matricesIndices !== !other.matricesIndices ||
  36561. !this.matricesWeights !== !other.matricesWeights ||
  36562. !this.matricesIndicesExtra !== !other.matricesIndicesExtra ||
  36563. !this.matricesWeightsExtra !== !other.matricesWeightsExtra) {
  36564. throw new Error("Cannot merge vertex data that do not have the same set of attributes");
  36565. }
  36566. if (other.indices) {
  36567. if (!this.indices) {
  36568. this.indices = [];
  36569. }
  36570. var offset = this.positions ? this.positions.length / 3 : 0;
  36571. for (var index = 0; index < other.indices.length; index++) {
  36572. //TODO check type - if Int32Array | Uint32Array | Uint16Array!
  36573. this.indices.push(other.indices[index] + offset);
  36574. }
  36575. }
  36576. this.positions = this._mergeElement(this.positions, other.positions);
  36577. this.normals = this._mergeElement(this.normals, other.normals);
  36578. this.tangents = this._mergeElement(this.tangents, other.tangents);
  36579. this.uvs = this._mergeElement(this.uvs, other.uvs);
  36580. this.uvs2 = this._mergeElement(this.uvs2, other.uvs2);
  36581. this.uvs3 = this._mergeElement(this.uvs3, other.uvs3);
  36582. this.uvs4 = this._mergeElement(this.uvs4, other.uvs4);
  36583. this.uvs5 = this._mergeElement(this.uvs5, other.uvs5);
  36584. this.uvs6 = this._mergeElement(this.uvs6, other.uvs6);
  36585. this.colors = this._mergeElement(this.colors, other.colors);
  36586. this.matricesIndices = this._mergeElement(this.matricesIndices, other.matricesIndices);
  36587. this.matricesWeights = this._mergeElement(this.matricesWeights, other.matricesWeights);
  36588. this.matricesIndicesExtra = this._mergeElement(this.matricesIndicesExtra, other.matricesIndicesExtra);
  36589. this.matricesWeightsExtra = this._mergeElement(this.matricesWeightsExtra, other.matricesWeightsExtra);
  36590. return this;
  36591. };
  36592. VertexData.prototype._mergeElement = function (source, other) {
  36593. if (!source) {
  36594. return other;
  36595. }
  36596. if (!other) {
  36597. return source;
  36598. }
  36599. var len = other.length + source.length;
  36600. var isSrcTypedArray = source instanceof Float32Array;
  36601. var isOthTypedArray = other instanceof Float32Array;
  36602. // use non-loop method when the source is Float32Array
  36603. if (isSrcTypedArray) {
  36604. var ret32 = new Float32Array(len);
  36605. ret32.set(source);
  36606. ret32.set(other, source.length);
  36607. return ret32;
  36608. // source is number[], when other is also use concat
  36609. }
  36610. else if (!isOthTypedArray) {
  36611. return source.concat(other);
  36612. // source is a number[], but other is a Float32Array, loop required
  36613. }
  36614. else {
  36615. var ret = source.slice(0); // copy source to a separate array
  36616. for (var i = 0, len = other.length; i < len; i++) {
  36617. ret.push(other[i]);
  36618. }
  36619. return ret;
  36620. }
  36621. };
  36622. VertexData.prototype._validate = function () {
  36623. if (!this.positions) {
  36624. throw new Error("Positions are required");
  36625. }
  36626. var getElementCount = function (kind, values) {
  36627. var stride = BABYLON.VertexBuffer.DeduceStride(kind);
  36628. if ((values.length % stride) !== 0) {
  36629. throw new Error("The " + kind + "s array count must be a multiple of " + stride);
  36630. }
  36631. return values.length / stride;
  36632. };
  36633. var positionsElementCount = getElementCount(BABYLON.VertexBuffer.PositionKind, this.positions);
  36634. var validateElementCount = function (kind, values) {
  36635. var elementCount = getElementCount(kind, values);
  36636. if (elementCount !== positionsElementCount) {
  36637. throw new Error("The " + kind + "s element count (" + elementCount + ") does not match the positions count (" + positionsElementCount + ")");
  36638. }
  36639. };
  36640. if (this.normals)
  36641. validateElementCount(BABYLON.VertexBuffer.NormalKind, this.normals);
  36642. if (this.tangents)
  36643. validateElementCount(BABYLON.VertexBuffer.TangentKind, this.tangents);
  36644. if (this.uvs)
  36645. validateElementCount(BABYLON.VertexBuffer.UVKind, this.uvs);
  36646. if (this.uvs2)
  36647. validateElementCount(BABYLON.VertexBuffer.UV2Kind, this.uvs2);
  36648. if (this.uvs3)
  36649. validateElementCount(BABYLON.VertexBuffer.UV3Kind, this.uvs3);
  36650. if (this.uvs4)
  36651. validateElementCount(BABYLON.VertexBuffer.UV4Kind, this.uvs4);
  36652. if (this.uvs5)
  36653. validateElementCount(BABYLON.VertexBuffer.UV5Kind, this.uvs5);
  36654. if (this.uvs6)
  36655. validateElementCount(BABYLON.VertexBuffer.UV6Kind, this.uvs6);
  36656. if (this.colors)
  36657. validateElementCount(BABYLON.VertexBuffer.ColorKind, this.colors);
  36658. if (this.matricesIndices)
  36659. validateElementCount(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices);
  36660. if (this.matricesWeights)
  36661. validateElementCount(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights);
  36662. if (this.matricesIndicesExtra)
  36663. validateElementCount(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra);
  36664. if (this.matricesWeightsExtra)
  36665. validateElementCount(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra);
  36666. };
  36667. /**
  36668. * Serializes the VertexData
  36669. * @returns a serialized object
  36670. */
  36671. VertexData.prototype.serialize = function () {
  36672. var serializationObject = this.serialize();
  36673. if (this.positions) {
  36674. serializationObject.positions = this.positions;
  36675. }
  36676. if (this.normals) {
  36677. serializationObject.normals = this.normals;
  36678. }
  36679. if (this.tangents) {
  36680. serializationObject.tangents = this.tangents;
  36681. }
  36682. if (this.uvs) {
  36683. serializationObject.uvs = this.uvs;
  36684. }
  36685. if (this.uvs2) {
  36686. serializationObject.uvs2 = this.uvs2;
  36687. }
  36688. if (this.uvs3) {
  36689. serializationObject.uvs3 = this.uvs3;
  36690. }
  36691. if (this.uvs4) {
  36692. serializationObject.uvs4 = this.uvs4;
  36693. }
  36694. if (this.uvs5) {
  36695. serializationObject.uvs5 = this.uvs5;
  36696. }
  36697. if (this.uvs6) {
  36698. serializationObject.uvs6 = this.uvs6;
  36699. }
  36700. if (this.colors) {
  36701. serializationObject.colors = this.colors;
  36702. }
  36703. if (this.matricesIndices) {
  36704. serializationObject.matricesIndices = this.matricesIndices;
  36705. serializationObject.matricesIndices._isExpanded = true;
  36706. }
  36707. if (this.matricesWeights) {
  36708. serializationObject.matricesWeights = this.matricesWeights;
  36709. }
  36710. if (this.matricesIndicesExtra) {
  36711. serializationObject.matricesIndicesExtra = this.matricesIndicesExtra;
  36712. serializationObject.matricesIndicesExtra._isExpanded = true;
  36713. }
  36714. if (this.matricesWeightsExtra) {
  36715. serializationObject.matricesWeightsExtra = this.matricesWeightsExtra;
  36716. }
  36717. serializationObject.indices = this.indices;
  36718. return serializationObject;
  36719. };
  36720. // Statics
  36721. /**
  36722. * Extracts the vertexData from a mesh
  36723. * @param mesh the mesh from which to extract the VertexData
  36724. * @param copyWhenShared defines if the VertexData must be cloned when shared between multiple meshes, optional, default false
  36725. * @param forceCopy indicating that the VertexData must be cloned, optional, default false
  36726. * @returns the object VertexData associated to the passed mesh
  36727. */
  36728. VertexData.ExtractFromMesh = function (mesh, copyWhenShared, forceCopy) {
  36729. return VertexData._ExtractFrom(mesh, copyWhenShared, forceCopy);
  36730. };
  36731. /**
  36732. * Extracts the vertexData from the geometry
  36733. * @param geometry the geometry from which to extract the VertexData
  36734. * @param copyWhenShared defines if the VertexData must be cloned when the geometrty is shared between multiple meshes, optional, default false
  36735. * @param forceCopy indicating that the VertexData must be cloned, optional, default false
  36736. * @returns the object VertexData associated to the passed mesh
  36737. */
  36738. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared, forceCopy) {
  36739. return VertexData._ExtractFrom(geometry, copyWhenShared, forceCopy);
  36740. };
  36741. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared, forceCopy) {
  36742. var result = new VertexData();
  36743. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  36744. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared, forceCopy);
  36745. }
  36746. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  36747. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared, forceCopy);
  36748. }
  36749. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  36750. result.tangents = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.TangentKind, copyWhenShared, forceCopy);
  36751. }
  36752. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  36753. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared, forceCopy);
  36754. }
  36755. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  36756. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared, forceCopy);
  36757. }
  36758. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  36759. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared, forceCopy);
  36760. }
  36761. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  36762. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared, forceCopy);
  36763. }
  36764. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  36765. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared, forceCopy);
  36766. }
  36767. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  36768. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared, forceCopy);
  36769. }
  36770. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  36771. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared, forceCopy);
  36772. }
  36773. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  36774. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared, forceCopy);
  36775. }
  36776. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  36777. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared, forceCopy);
  36778. }
  36779. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {
  36780. result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared, forceCopy);
  36781. }
  36782. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  36783. result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared, forceCopy);
  36784. }
  36785. result.indices = meshOrGeometry.getIndices(copyWhenShared);
  36786. return result;
  36787. };
  36788. /**
  36789. * Creates the VertexData for a Ribbon
  36790. * @param options an object used to set the following optional parameters for the ribbon, required but can be empty
  36791. * * pathArray array of paths, each of which an array of successive Vector3
  36792. * * closeArray creates a seam between the first and the last paths of the pathArray, optional, default false
  36793. * * closePath creates a seam between the first and the last points of each path of the path array, optional, default false
  36794. * * 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
  36795. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  36796. * * 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)
  36797. * * 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)
  36798. * * invertUV swaps in the U and V coordinates when applying a texture, optional, default false
  36799. * * uvs a linear array, of length 2 * number of vertices, of custom UV values, optional
  36800. * * colors a linear array, of length 4 * number of vertices, of custom color values, optional
  36801. * @returns the VertexData of the ribbon
  36802. */
  36803. VertexData.CreateRibbon = function (options) {
  36804. var pathArray = options.pathArray;
  36805. var closeArray = options.closeArray || false;
  36806. var closePath = options.closePath || false;
  36807. var invertUV = options.invertUV || false;
  36808. var defaultOffset = Math.floor(pathArray[0].length / 2);
  36809. var offset = options.offset || defaultOffset;
  36810. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  36811. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  36812. var customUV = options.uvs;
  36813. var customColors = options.colors;
  36814. var positions = [];
  36815. var indices = [];
  36816. var normals = [];
  36817. var uvs = [];
  36818. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  36819. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  36820. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  36821. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  36822. var minlg; // minimal length among all paths from pathArray
  36823. var lg = []; // array of path lengths : nb of vertex per path
  36824. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  36825. var p; // path iterator
  36826. var i; // point iterator
  36827. var j; // point iterator
  36828. // if single path in pathArray
  36829. if (pathArray.length < 2) {
  36830. var ar1 = [];
  36831. var ar2 = [];
  36832. for (i = 0; i < pathArray[0].length - offset; i++) {
  36833. ar1.push(pathArray[0][i]);
  36834. ar2.push(pathArray[0][i + offset]);
  36835. }
  36836. pathArray = [ar1, ar2];
  36837. }
  36838. // positions and horizontal distances (u)
  36839. var idc = 0;
  36840. var closePathCorr = (closePath) ? 1 : 0; // the final index will be +1 if closePath
  36841. var path;
  36842. var l;
  36843. minlg = pathArray[0].length;
  36844. var vectlg;
  36845. var dist;
  36846. for (p = 0; p < pathArray.length; p++) {
  36847. uTotalDistance[p] = 0;
  36848. us[p] = [0];
  36849. path = pathArray[p];
  36850. l = path.length;
  36851. minlg = (minlg < l) ? minlg : l;
  36852. j = 0;
  36853. while (j < l) {
  36854. positions.push(path[j].x, path[j].y, path[j].z);
  36855. if (j > 0) {
  36856. vectlg = path[j].subtract(path[j - 1]).length();
  36857. dist = vectlg + uTotalDistance[p];
  36858. us[p].push(dist);
  36859. uTotalDistance[p] = dist;
  36860. }
  36861. j++;
  36862. }
  36863. if (closePath) { // an extra hidden vertex is added in the "positions" array
  36864. j--;
  36865. positions.push(path[0].x, path[0].y, path[0].z);
  36866. vectlg = path[j].subtract(path[0]).length();
  36867. dist = vectlg + uTotalDistance[p];
  36868. us[p].push(dist);
  36869. uTotalDistance[p] = dist;
  36870. }
  36871. lg[p] = l + closePathCorr;
  36872. idx[p] = idc;
  36873. idc += (l + closePathCorr);
  36874. }
  36875. // vertical distances (v)
  36876. var path1;
  36877. var path2;
  36878. var vertex1 = null;
  36879. var vertex2 = null;
  36880. for (i = 0; i < minlg + closePathCorr; i++) {
  36881. vTotalDistance[i] = 0;
  36882. vs[i] = [0];
  36883. for (p = 0; p < pathArray.length - 1; p++) {
  36884. path1 = pathArray[p];
  36885. path2 = pathArray[p + 1];
  36886. if (i === minlg) { // closePath
  36887. vertex1 = path1[0];
  36888. vertex2 = path2[0];
  36889. }
  36890. else {
  36891. vertex1 = path1[i];
  36892. vertex2 = path2[i];
  36893. }
  36894. vectlg = vertex2.subtract(vertex1).length();
  36895. dist = vectlg + vTotalDistance[i];
  36896. vs[i].push(dist);
  36897. vTotalDistance[i] = dist;
  36898. }
  36899. if (closeArray && vertex2 && vertex1) {
  36900. path1 = pathArray[p];
  36901. path2 = pathArray[0];
  36902. if (i === minlg) { // closePath
  36903. vertex2 = path2[0];
  36904. }
  36905. vectlg = vertex2.subtract(vertex1).length();
  36906. dist = vectlg + vTotalDistance[i];
  36907. vTotalDistance[i] = dist;
  36908. }
  36909. }
  36910. // uvs
  36911. var u;
  36912. var v;
  36913. if (customUV) {
  36914. for (p = 0; p < customUV.length; p++) {
  36915. uvs.push(customUV[p].x, customUV[p].y);
  36916. }
  36917. }
  36918. else {
  36919. for (p = 0; p < pathArray.length; p++) {
  36920. for (i = 0; i < minlg + closePathCorr; i++) {
  36921. u = (uTotalDistance[p] != 0.0) ? us[p][i] / uTotalDistance[p] : 0.0;
  36922. v = (vTotalDistance[i] != 0.0) ? vs[i][p] / vTotalDistance[i] : 0.0;
  36923. if (invertUV) {
  36924. uvs.push(v, u);
  36925. }
  36926. else {
  36927. uvs.push(u, v);
  36928. }
  36929. }
  36930. }
  36931. }
  36932. // indices
  36933. p = 0; // path index
  36934. var pi = 0; // positions array index
  36935. var l1 = lg[p] - 1; // path1 length
  36936. var l2 = lg[p + 1] - 1; // path2 length
  36937. var min = (l1 < l2) ? l1 : l2; // current path stop index
  36938. var shft = idx[1] - idx[0]; // shift
  36939. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  36940. while (pi <= min && p < path1nb) { // stay under min and don't go over next to last path
  36941. // 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
  36942. indices.push(pi, pi + shft, pi + 1);
  36943. indices.push(pi + shft + 1, pi + 1, pi + shft);
  36944. pi += 1;
  36945. if (pi === min) { // if end of one of two consecutive paths reached, go to next existing path
  36946. p++;
  36947. if (p === lg.length - 1) { // last path of pathArray reached <=> closeArray == true
  36948. shft = idx[0] - idx[p];
  36949. l1 = lg[p] - 1;
  36950. l2 = lg[0] - 1;
  36951. }
  36952. else {
  36953. shft = idx[p + 1] - idx[p];
  36954. l1 = lg[p] - 1;
  36955. l2 = lg[p + 1] - 1;
  36956. }
  36957. pi = idx[p];
  36958. min = (l1 < l2) ? l1 + pi : l2 + pi;
  36959. }
  36960. }
  36961. // normals
  36962. VertexData.ComputeNormals(positions, indices, normals);
  36963. if (closePath) { // update both the first and last vertex normals to their average value
  36964. var indexFirst = 0;
  36965. var indexLast = 0;
  36966. for (p = 0; p < pathArray.length; p++) {
  36967. indexFirst = idx[p] * 3;
  36968. if (p + 1 < pathArray.length) {
  36969. indexLast = (idx[p + 1] - 1) * 3;
  36970. }
  36971. else {
  36972. indexLast = normals.length - 3;
  36973. }
  36974. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  36975. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  36976. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  36977. normals[indexLast] = normals[indexFirst];
  36978. normals[indexLast + 1] = normals[indexFirst + 1];
  36979. normals[indexLast + 2] = normals[indexFirst + 2];
  36980. }
  36981. }
  36982. // sides
  36983. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  36984. // Colors
  36985. var colors = null;
  36986. if (customColors) {
  36987. colors = new Float32Array(customColors.length * 4);
  36988. for (var c = 0; c < customColors.length; c++) {
  36989. colors[c * 4] = customColors[c].r;
  36990. colors[c * 4 + 1] = customColors[c].g;
  36991. colors[c * 4 + 2] = customColors[c].b;
  36992. colors[c * 4 + 3] = customColors[c].a;
  36993. }
  36994. }
  36995. // Result
  36996. var vertexData = new VertexData();
  36997. var positions32 = new Float32Array(positions);
  36998. var normals32 = new Float32Array(normals);
  36999. var uvs32 = new Float32Array(uvs);
  37000. vertexData.indices = indices;
  37001. vertexData.positions = positions32;
  37002. vertexData.normals = normals32;
  37003. vertexData.uvs = uvs32;
  37004. if (colors) {
  37005. vertexData.set(colors, BABYLON.VertexBuffer.ColorKind);
  37006. }
  37007. if (closePath) {
  37008. vertexData._idx = idx;
  37009. }
  37010. return vertexData;
  37011. };
  37012. /**
  37013. * Creates the VertexData for a box
  37014. * @param options an object used to set the following optional parameters for the box, required but can be empty
  37015. * * size sets the width, height and depth of the box to the value of size, optional default 1
  37016. * * width sets the width (x direction) of the box, overwrites the width set by size, optional, default size
  37017. * * height sets the height (y direction) of the box, overwrites the height set by size, optional, default size
  37018. * * depth sets the depth (z direction) of the box, overwrites the depth set by size, optional, default size
  37019. * * faceUV an array of 6 Vector4 elements used to set different images to each box side
  37020. * * faceColors an array of 6 Color3 elements used to set different colors to each box side
  37021. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37022. * * 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)
  37023. * * 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)
  37024. * @returns the VertexData of the box
  37025. */
  37026. VertexData.CreateBox = function (options) {
  37027. var normalsSource = [
  37028. new BABYLON.Vector3(0, 0, 1),
  37029. new BABYLON.Vector3(0, 0, -1),
  37030. new BABYLON.Vector3(1, 0, 0),
  37031. new BABYLON.Vector3(-1, 0, 0),
  37032. new BABYLON.Vector3(0, 1, 0),
  37033. new BABYLON.Vector3(0, -1, 0)
  37034. ];
  37035. var indices = [];
  37036. var positions = [];
  37037. var normals = [];
  37038. var uvs = [];
  37039. var width = options.width || options.size || 1;
  37040. var height = options.height || options.size || 1;
  37041. var depth = options.depth || options.size || 1;
  37042. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37043. var faceUV = options.faceUV || new Array(6);
  37044. var faceColors = options.faceColors;
  37045. var colors = [];
  37046. // default face colors and UV if undefined
  37047. for (var f = 0; f < 6; f++) {
  37048. if (faceUV[f] === undefined) {
  37049. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  37050. }
  37051. if (faceColors && faceColors[f] === undefined) {
  37052. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  37053. }
  37054. }
  37055. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  37056. // Create each face in turn.
  37057. for (var index = 0; index < normalsSource.length; index++) {
  37058. var normal = normalsSource[index];
  37059. // Get two vectors perpendicular to the face normal and to each other.
  37060. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  37061. var side2 = BABYLON.Vector3.Cross(normal, side1);
  37062. // Six indices (two triangles) per face.
  37063. var verticesLength = positions.length / 3;
  37064. indices.push(verticesLength);
  37065. indices.push(verticesLength + 1);
  37066. indices.push(verticesLength + 2);
  37067. indices.push(verticesLength);
  37068. indices.push(verticesLength + 2);
  37069. indices.push(verticesLength + 3);
  37070. // Four vertices per face.
  37071. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  37072. positions.push(vertex.x, vertex.y, vertex.z);
  37073. normals.push(normal.x, normal.y, normal.z);
  37074. uvs.push(faceUV[index].z, faceUV[index].w);
  37075. if (faceColors) {
  37076. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  37077. }
  37078. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  37079. positions.push(vertex.x, vertex.y, vertex.z);
  37080. normals.push(normal.x, normal.y, normal.z);
  37081. uvs.push(faceUV[index].x, faceUV[index].w);
  37082. if (faceColors) {
  37083. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  37084. }
  37085. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  37086. positions.push(vertex.x, vertex.y, vertex.z);
  37087. normals.push(normal.x, normal.y, normal.z);
  37088. uvs.push(faceUV[index].x, faceUV[index].y);
  37089. if (faceColors) {
  37090. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  37091. }
  37092. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  37093. positions.push(vertex.x, vertex.y, vertex.z);
  37094. normals.push(normal.x, normal.y, normal.z);
  37095. uvs.push(faceUV[index].z, faceUV[index].y);
  37096. if (faceColors) {
  37097. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  37098. }
  37099. }
  37100. // sides
  37101. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37102. // Result
  37103. var vertexData = new VertexData();
  37104. vertexData.indices = indices;
  37105. vertexData.positions = positions;
  37106. vertexData.normals = normals;
  37107. vertexData.uvs = uvs;
  37108. if (faceColors) {
  37109. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  37110. vertexData.colors = totalColors;
  37111. }
  37112. return vertexData;
  37113. };
  37114. /**
  37115. * Creates the VertexData for an ellipsoid, defaults to a sphere
  37116. * @param options an object used to set the following optional parameters for the box, required but can be empty
  37117. * * segments sets the number of horizontal strips optional, default 32
  37118. * * diameter sets the axes dimensions, diameterX, diameterY and diameterZ to the value of diameter, optional default 1
  37119. * * diameterX sets the diameterX (x direction) of the ellipsoid, overwrites the diameterX set by diameter, optional, default diameter
  37120. * * diameterY sets the diameterY (y direction) of the ellipsoid, overwrites the diameterY set by diameter, optional, default diameter
  37121. * * diameterZ sets the diameterZ (z direction) of the ellipsoid, overwrites the diameterZ set by diameter, optional, default diameter
  37122. * * 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
  37123. * * 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
  37124. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37125. * * 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)
  37126. * * 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)
  37127. * @returns the VertexData of the ellipsoid
  37128. */
  37129. VertexData.CreateSphere = function (options) {
  37130. var segments = options.segments || 32;
  37131. var diameterX = options.diameterX || options.diameter || 1;
  37132. var diameterY = options.diameterY || options.diameter || 1;
  37133. var diameterZ = options.diameterZ || options.diameter || 1;
  37134. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  37135. var slice = options.slice && (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  37136. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37137. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  37138. var totalZRotationSteps = 2 + segments;
  37139. var totalYRotationSteps = 2 * totalZRotationSteps;
  37140. var indices = [];
  37141. var positions = [];
  37142. var normals = [];
  37143. var uvs = [];
  37144. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  37145. var normalizedZ = zRotationStep / totalZRotationSteps;
  37146. var angleZ = normalizedZ * Math.PI * slice;
  37147. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  37148. var normalizedY = yRotationStep / totalYRotationSteps;
  37149. var angleY = normalizedY * Math.PI * 2 * arc;
  37150. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  37151. var rotationY = BABYLON.Matrix.RotationY(angleY);
  37152. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  37153. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  37154. var vertex = complete.multiply(radius);
  37155. var normal = complete.divide(radius).normalize();
  37156. positions.push(vertex.x, vertex.y, vertex.z);
  37157. normals.push(normal.x, normal.y, normal.z);
  37158. uvs.push(normalizedY, normalizedZ);
  37159. }
  37160. if (zRotationStep > 0) {
  37161. var verticesCount = positions.length / 3;
  37162. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  37163. indices.push((firstIndex));
  37164. indices.push((firstIndex + 1));
  37165. indices.push(firstIndex + totalYRotationSteps + 1);
  37166. indices.push((firstIndex + totalYRotationSteps + 1));
  37167. indices.push((firstIndex + 1));
  37168. indices.push((firstIndex + totalYRotationSteps + 2));
  37169. }
  37170. }
  37171. }
  37172. // Sides
  37173. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37174. // Result
  37175. var vertexData = new VertexData();
  37176. vertexData.indices = indices;
  37177. vertexData.positions = positions;
  37178. vertexData.normals = normals;
  37179. vertexData.uvs = uvs;
  37180. return vertexData;
  37181. };
  37182. /**
  37183. * Creates the VertexData for a cylinder, cone or prism
  37184. * @param options an object used to set the following optional parameters for the box, required but can be empty
  37185. * * height sets the height (y direction) of the cylinder, optional, default 2
  37186. * * diameterTop sets the diameter of the top of the cone, overwrites diameter, optional, default diameter
  37187. * * diameterBottom sets the diameter of the bottom of the cone, overwrites diameter, optional, default diameter
  37188. * * diameter sets the diameter of the top and bottom of the cone, optional default 1
  37189. * * tessellation the number of prism sides, 3 for a triangular prism, optional, default 24
  37190. * * subdivisions` the number of rings along the cylinder height, optional, default 1
  37191. * * 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
  37192. * * faceColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively
  37193. * * faceUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively
  37194. * * hasRings when true makes each subdivision independantly treated as a face for faceUV and faceColors, optional, default false
  37195. * * enclose when true closes an open cylinder by adding extra flat faces between the height axis and vertical edges, think cut cake
  37196. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37197. * * 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)
  37198. * * 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)
  37199. * @returns the VertexData of the cylinder, cone or prism
  37200. */
  37201. VertexData.CreateCylinder = function (options) {
  37202. var height = options.height || 2;
  37203. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
  37204. var diameterBottom = (options.diameterBottom === 0) ? 0 : options.diameterBottom || options.diameter || 1;
  37205. var tessellation = options.tessellation || 24;
  37206. var subdivisions = options.subdivisions || 1;
  37207. var hasRings = options.hasRings ? true : false;
  37208. var enclose = options.enclose ? true : false;
  37209. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  37210. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37211. var faceUV = options.faceUV || new Array(3);
  37212. var faceColors = options.faceColors;
  37213. // default face colors and UV if undefined
  37214. var quadNb = (arc !== 1 && enclose) ? 2 : 0;
  37215. var ringNb = (hasRings) ? subdivisions : 1;
  37216. var surfaceNb = 2 + (1 + quadNb) * ringNb;
  37217. var f;
  37218. for (f = 0; f < surfaceNb; f++) {
  37219. if (faceColors && faceColors[f] === undefined) {
  37220. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  37221. }
  37222. }
  37223. for (f = 0; f < surfaceNb; f++) {
  37224. if (faceUV && faceUV[f] === undefined) {
  37225. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  37226. }
  37227. }
  37228. var indices = new Array();
  37229. var positions = new Array();
  37230. var normals = new Array();
  37231. var uvs = new Array();
  37232. var colors = new Array();
  37233. var angle_step = Math.PI * 2 * arc / tessellation;
  37234. var angle;
  37235. var h;
  37236. var radius;
  37237. var tan = (diameterBottom - diameterTop) / 2 / height;
  37238. var ringVertex = BABYLON.Vector3.Zero();
  37239. var ringNormal = BABYLON.Vector3.Zero();
  37240. var ringFirstVertex = BABYLON.Vector3.Zero();
  37241. var ringFirstNormal = BABYLON.Vector3.Zero();
  37242. var quadNormal = BABYLON.Vector3.Zero();
  37243. var Y = BABYLON.Axis.Y;
  37244. // positions, normals, uvs
  37245. var i;
  37246. var j;
  37247. var r;
  37248. var ringIdx = 1;
  37249. var s = 1; // surface index
  37250. var cs = 0;
  37251. var v = 0;
  37252. for (i = 0; i <= subdivisions; i++) {
  37253. h = i / subdivisions;
  37254. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  37255. ringIdx = (hasRings && i !== 0 && i !== subdivisions) ? 2 : 1;
  37256. for (r = 0; r < ringIdx; r++) {
  37257. if (hasRings) {
  37258. s += r;
  37259. }
  37260. if (enclose) {
  37261. s += 2 * r;
  37262. }
  37263. for (j = 0; j <= tessellation; j++) {
  37264. angle = j * angle_step;
  37265. // position
  37266. ringVertex.x = Math.cos(-angle) * radius;
  37267. ringVertex.y = -height / 2 + h * height;
  37268. ringVertex.z = Math.sin(-angle) * radius;
  37269. // normal
  37270. if (diameterTop === 0 && i === subdivisions) {
  37271. // if no top cap, reuse former normals
  37272. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  37273. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  37274. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  37275. }
  37276. else {
  37277. ringNormal.x = ringVertex.x;
  37278. ringNormal.z = ringVertex.z;
  37279. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  37280. ringNormal.normalize();
  37281. }
  37282. // keep first ring vertex values for enclose
  37283. if (j === 0) {
  37284. ringFirstVertex.copyFrom(ringVertex);
  37285. ringFirstNormal.copyFrom(ringNormal);
  37286. }
  37287. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  37288. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  37289. if (hasRings) {
  37290. v = (cs !== s) ? faceUV[s].y : faceUV[s].w;
  37291. }
  37292. else {
  37293. v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;
  37294. }
  37295. uvs.push(faceUV[s].x + (faceUV[s].z - faceUV[s].x) * j / tessellation, v);
  37296. if (faceColors) {
  37297. colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);
  37298. }
  37299. }
  37300. // if enclose, add four vertices and their dedicated normals
  37301. if (arc !== 1 && enclose) {
  37302. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  37303. positions.push(0, ringVertex.y, 0);
  37304. positions.push(0, ringVertex.y, 0);
  37305. positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);
  37306. BABYLON.Vector3.CrossToRef(Y, ringNormal, quadNormal);
  37307. quadNormal.normalize();
  37308. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  37309. BABYLON.Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);
  37310. quadNormal.normalize();
  37311. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  37312. if (hasRings) {
  37313. v = (cs !== s) ? faceUV[s + 1].y : faceUV[s + 1].w;
  37314. }
  37315. else {
  37316. v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;
  37317. }
  37318. uvs.push(faceUV[s + 1].x, v);
  37319. uvs.push(faceUV[s + 1].z, v);
  37320. if (hasRings) {
  37321. v = (cs !== s) ? faceUV[s + 2].y : faceUV[s + 2].w;
  37322. }
  37323. else {
  37324. v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;
  37325. }
  37326. uvs.push(faceUV[s + 2].x, v);
  37327. uvs.push(faceUV[s + 2].z, v);
  37328. if (faceColors) {
  37329. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  37330. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  37331. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  37332. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  37333. }
  37334. }
  37335. if (cs !== s) {
  37336. cs = s;
  37337. }
  37338. }
  37339. }
  37340. // indices
  37341. var e = (arc !== 1 && enclose) ? tessellation + 4 : tessellation; // correction of number of iteration if enclose
  37342. var s;
  37343. i = 0;
  37344. for (s = 0; s < subdivisions; s++) {
  37345. var i0 = 0;
  37346. var i1 = 0;
  37347. var i2 = 0;
  37348. var i3 = 0;
  37349. for (j = 0; j < tessellation; j++) {
  37350. i0 = i * (e + 1) + j;
  37351. i1 = (i + 1) * (e + 1) + j;
  37352. i2 = i * (e + 1) + (j + 1);
  37353. i3 = (i + 1) * (e + 1) + (j + 1);
  37354. indices.push(i0, i1, i2);
  37355. indices.push(i3, i2, i1);
  37356. }
  37357. if (arc !== 1 && enclose) { // if enclose, add two quads
  37358. indices.push(i0 + 2, i1 + 2, i2 + 2);
  37359. indices.push(i3 + 2, i2 + 2, i1 + 2);
  37360. indices.push(i0 + 4, i1 + 4, i2 + 4);
  37361. indices.push(i3 + 4, i2 + 4, i1 + 4);
  37362. }
  37363. i = (hasRings) ? (i + 2) : (i + 1);
  37364. }
  37365. // Caps
  37366. var createCylinderCap = function (isTop) {
  37367. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  37368. if (radius === 0) {
  37369. return;
  37370. }
  37371. // Cap positions, normals & uvs
  37372. var angle;
  37373. var circleVector;
  37374. var i;
  37375. var u = (isTop) ? faceUV[surfaceNb - 1] : faceUV[0];
  37376. var c = null;
  37377. if (faceColors) {
  37378. c = (isTop) ? faceColors[surfaceNb - 1] : faceColors[0];
  37379. }
  37380. // cap center
  37381. var vbase = positions.length / 3;
  37382. var offset = isTop ? height / 2 : -height / 2;
  37383. var center = new BABYLON.Vector3(0, offset, 0);
  37384. positions.push(center.x, center.y, center.z);
  37385. normals.push(0, isTop ? 1 : -1, 0);
  37386. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  37387. if (c) {
  37388. colors.push(c.r, c.g, c.b, c.a);
  37389. }
  37390. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  37391. for (i = 0; i <= tessellation; i++) {
  37392. angle = Math.PI * 2 * i * arc / tessellation;
  37393. var cos = Math.cos(-angle);
  37394. var sin = Math.sin(-angle);
  37395. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  37396. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  37397. positions.push(circleVector.x, circleVector.y, circleVector.z);
  37398. normals.push(0, isTop ? 1 : -1, 0);
  37399. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  37400. if (c) {
  37401. colors.push(c.r, c.g, c.b, c.a);
  37402. }
  37403. }
  37404. // Cap indices
  37405. for (i = 0; i < tessellation; i++) {
  37406. if (!isTop) {
  37407. indices.push(vbase);
  37408. indices.push(vbase + (i + 1));
  37409. indices.push(vbase + (i + 2));
  37410. }
  37411. else {
  37412. indices.push(vbase);
  37413. indices.push(vbase + (i + 2));
  37414. indices.push(vbase + (i + 1));
  37415. }
  37416. }
  37417. };
  37418. // add caps to geometry
  37419. createCylinderCap(false);
  37420. createCylinderCap(true);
  37421. // Sides
  37422. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37423. var vertexData = new VertexData();
  37424. vertexData.indices = indices;
  37425. vertexData.positions = positions;
  37426. vertexData.normals = normals;
  37427. vertexData.uvs = uvs;
  37428. if (faceColors) {
  37429. vertexData.colors = colors;
  37430. }
  37431. return vertexData;
  37432. };
  37433. /**
  37434. * Creates the VertexData for a torus
  37435. * @param options an object used to set the following optional parameters for the box, required but can be empty
  37436. * * diameter the diameter of the torus, optional default 1
  37437. * * thickness the diameter of the tube forming the torus, optional default 0.5
  37438. * * tessellation the number of prism sides, 3 for a triangular prism, optional, default 24
  37439. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37440. * * 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)
  37441. * * 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)
  37442. * @returns the VertexData of the torus
  37443. */
  37444. VertexData.CreateTorus = function (options) {
  37445. var indices = [];
  37446. var positions = [];
  37447. var normals = [];
  37448. var uvs = [];
  37449. var diameter = options.diameter || 1;
  37450. var thickness = options.thickness || 0.5;
  37451. var tessellation = options.tessellation || 16;
  37452. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37453. var stride = tessellation + 1;
  37454. for (var i = 0; i <= tessellation; i++) {
  37455. var u = i / tessellation;
  37456. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  37457. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  37458. for (var j = 0; j <= tessellation; j++) {
  37459. var v = 1 - j / tessellation;
  37460. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  37461. var dx = Math.cos(innerAngle);
  37462. var dy = Math.sin(innerAngle);
  37463. // Create a vertex.
  37464. var normal = new BABYLON.Vector3(dx, dy, 0);
  37465. var position = normal.scale(thickness / 2);
  37466. var textureCoordinate = new BABYLON.Vector2(u, v);
  37467. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  37468. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  37469. positions.push(position.x, position.y, position.z);
  37470. normals.push(normal.x, normal.y, normal.z);
  37471. uvs.push(textureCoordinate.x, textureCoordinate.y);
  37472. // And create indices for two triangles.
  37473. var nextI = (i + 1) % stride;
  37474. var nextJ = (j + 1) % stride;
  37475. indices.push(i * stride + j);
  37476. indices.push(i * stride + nextJ);
  37477. indices.push(nextI * stride + j);
  37478. indices.push(i * stride + nextJ);
  37479. indices.push(nextI * stride + nextJ);
  37480. indices.push(nextI * stride + j);
  37481. }
  37482. }
  37483. // Sides
  37484. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37485. // Result
  37486. var vertexData = new VertexData();
  37487. vertexData.indices = indices;
  37488. vertexData.positions = positions;
  37489. vertexData.normals = normals;
  37490. vertexData.uvs = uvs;
  37491. return vertexData;
  37492. };
  37493. /**
  37494. * Creates the VertexData of the LineSystem
  37495. * @param options an object used to set the following optional parameters for the LineSystem, required but can be empty
  37496. * - lines an array of lines, each line being an array of successive Vector3
  37497. * - colors an array of line colors, each of the line colors being an array of successive Color4, one per line point
  37498. * @returns the VertexData of the LineSystem
  37499. */
  37500. VertexData.CreateLineSystem = function (options) {
  37501. var indices = [];
  37502. var positions = [];
  37503. var lines = options.lines;
  37504. var colors = options.colors;
  37505. var vertexColors = [];
  37506. var idx = 0;
  37507. for (var l = 0; l < lines.length; l++) {
  37508. var points = lines[l];
  37509. for (var index = 0; index < points.length; index++) {
  37510. positions.push(points[index].x, points[index].y, points[index].z);
  37511. if (colors) {
  37512. var color = colors[l];
  37513. vertexColors.push(color[index].r, color[index].g, color[index].b, color[index].a);
  37514. }
  37515. if (index > 0) {
  37516. indices.push(idx - 1);
  37517. indices.push(idx);
  37518. }
  37519. idx++;
  37520. }
  37521. }
  37522. var vertexData = new VertexData();
  37523. vertexData.indices = indices;
  37524. vertexData.positions = positions;
  37525. if (colors) {
  37526. vertexData.colors = vertexColors;
  37527. }
  37528. return vertexData;
  37529. };
  37530. /**
  37531. * Create the VertexData for a DashedLines
  37532. * @param options an object used to set the following optional parameters for the DashedLines, required but can be empty
  37533. * - points an array successive Vector3
  37534. * - dashSize the size of the dashes relative to the dash number, optional, default 3
  37535. * - gapSize the size of the gap between two successive dashes relative to the dash number, optional, default 1
  37536. * - dashNb the intended total number of dashes, optional, default 200
  37537. * @returns the VertexData for the DashedLines
  37538. */
  37539. VertexData.CreateDashedLines = function (options) {
  37540. var dashSize = options.dashSize || 3;
  37541. var gapSize = options.gapSize || 1;
  37542. var dashNb = options.dashNb || 200;
  37543. var points = options.points;
  37544. var positions = new Array();
  37545. var indices = new Array();
  37546. var curvect = BABYLON.Vector3.Zero();
  37547. var lg = 0;
  37548. var nb = 0;
  37549. var shft = 0;
  37550. var dashshft = 0;
  37551. var curshft = 0;
  37552. var idx = 0;
  37553. var i = 0;
  37554. for (i = 0; i < points.length - 1; i++) {
  37555. points[i + 1].subtractToRef(points[i], curvect);
  37556. lg += curvect.length();
  37557. }
  37558. shft = lg / dashNb;
  37559. dashshft = dashSize * shft / (dashSize + gapSize);
  37560. for (i = 0; i < points.length - 1; i++) {
  37561. points[i + 1].subtractToRef(points[i], curvect);
  37562. nb = Math.floor(curvect.length() / shft);
  37563. curvect.normalize();
  37564. for (var j = 0; j < nb; j++) {
  37565. curshft = shft * j;
  37566. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  37567. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  37568. indices.push(idx, idx + 1);
  37569. idx += 2;
  37570. }
  37571. }
  37572. // Result
  37573. var vertexData = new VertexData();
  37574. vertexData.positions = positions;
  37575. vertexData.indices = indices;
  37576. return vertexData;
  37577. };
  37578. /**
  37579. * Creates the VertexData for a Ground
  37580. * @param options an object used to set the following optional parameters for the Ground, required but can be empty
  37581. * - width the width (x direction) of the ground, optional, default 1
  37582. * - height the height (z direction) of the ground, optional, default 1
  37583. * - subdivisions the number of subdivisions per side, optional, default 1
  37584. * @returns the VertexData of the Ground
  37585. */
  37586. VertexData.CreateGround = function (options) {
  37587. var indices = [];
  37588. var positions = [];
  37589. var normals = [];
  37590. var uvs = [];
  37591. var row, col;
  37592. var width = options.width || 1;
  37593. var height = options.height || 1;
  37594. var subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  37595. var subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  37596. for (row = 0; row <= subdivisionsY; row++) {
  37597. for (col = 0; col <= subdivisionsX; col++) {
  37598. var position = new BABYLON.Vector3((col * width) / subdivisionsX - (width / 2.0), 0, ((subdivisionsY - row) * height) / subdivisionsY - (height / 2.0));
  37599. var normal = new BABYLON.Vector3(0, 1.0, 0);
  37600. positions.push(position.x, position.y, position.z);
  37601. normals.push(normal.x, normal.y, normal.z);
  37602. uvs.push(col / subdivisionsX, 1.0 - row / subdivisionsY);
  37603. }
  37604. }
  37605. for (row = 0; row < subdivisionsY; row++) {
  37606. for (col = 0; col < subdivisionsX; col++) {
  37607. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  37608. indices.push(col + 1 + row * (subdivisionsX + 1));
  37609. indices.push(col + row * (subdivisionsX + 1));
  37610. indices.push(col + (row + 1) * (subdivisionsX + 1));
  37611. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  37612. indices.push(col + row * (subdivisionsX + 1));
  37613. }
  37614. }
  37615. // Result
  37616. var vertexData = new VertexData();
  37617. vertexData.indices = indices;
  37618. vertexData.positions = positions;
  37619. vertexData.normals = normals;
  37620. vertexData.uvs = uvs;
  37621. return vertexData;
  37622. };
  37623. /**
  37624. * Creates the VertexData for a TiledGround by subdividing the ground into tiles
  37625. * @param options an object used to set the following optional parameters for the Ground, required but can be empty
  37626. * * xmin the ground minimum X coordinate, optional, default -1
  37627. * * zmin the ground minimum Z coordinate, optional, default -1
  37628. * * xmax the ground maximum X coordinate, optional, default 1
  37629. * * zmax the ground maximum Z coordinate, optional, default 1
  37630. * * 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}
  37631. * * 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}
  37632. * @returns the VertexData of the TiledGround
  37633. */
  37634. VertexData.CreateTiledGround = function (options) {
  37635. var xmin = (options.xmin !== undefined && options.xmin !== null) ? options.xmin : -1.0;
  37636. var zmin = (options.zmin !== undefined && options.zmin !== null) ? options.zmin : -1.0;
  37637. var xmax = (options.xmax !== undefined && options.xmax !== null) ? options.xmax : 1.0;
  37638. var zmax = (options.zmax !== undefined && options.zmax !== null) ? options.zmax : 1.0;
  37639. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  37640. var precision = options.precision || { w: 1, h: 1 };
  37641. var indices = new Array();
  37642. var positions = new Array();
  37643. var normals = new Array();
  37644. var uvs = new Array();
  37645. var row, col, tileRow, tileCol;
  37646. subdivisions.h = (subdivisions.h < 1) ? 1 : subdivisions.h;
  37647. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  37648. precision.w = (precision.w < 1) ? 1 : precision.w;
  37649. precision.h = (precision.h < 1) ? 1 : precision.h;
  37650. var tileSize = {
  37651. 'w': (xmax - xmin) / subdivisions.w,
  37652. 'h': (zmax - zmin) / subdivisions.h
  37653. };
  37654. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  37655. // Indices
  37656. var base = positions.length / 3;
  37657. var rowLength = precision.w + 1;
  37658. for (row = 0; row < precision.h; row++) {
  37659. for (col = 0; col < precision.w; col++) {
  37660. var square = [
  37661. base + col + row * rowLength,
  37662. base + (col + 1) + row * rowLength,
  37663. base + (col + 1) + (row + 1) * rowLength,
  37664. base + col + (row + 1) * rowLength
  37665. ];
  37666. indices.push(square[1]);
  37667. indices.push(square[2]);
  37668. indices.push(square[3]);
  37669. indices.push(square[0]);
  37670. indices.push(square[1]);
  37671. indices.push(square[3]);
  37672. }
  37673. }
  37674. // Position, normals and uvs
  37675. var position = BABYLON.Vector3.Zero();
  37676. var normal = new BABYLON.Vector3(0, 1.0, 0);
  37677. for (row = 0; row <= precision.h; row++) {
  37678. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  37679. for (col = 0; col <= precision.w; col++) {
  37680. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  37681. position.y = 0;
  37682. positions.push(position.x, position.y, position.z);
  37683. normals.push(normal.x, normal.y, normal.z);
  37684. uvs.push(col / precision.w, row / precision.h);
  37685. }
  37686. }
  37687. }
  37688. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  37689. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  37690. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  37691. }
  37692. }
  37693. // Result
  37694. var vertexData = new VertexData();
  37695. vertexData.indices = indices;
  37696. vertexData.positions = positions;
  37697. vertexData.normals = normals;
  37698. vertexData.uvs = uvs;
  37699. return vertexData;
  37700. };
  37701. /**
  37702. * Creates the VertexData of the Ground designed from a heightmap
  37703. * @param options an object used to set the following parameters for the Ground, required and provided by MeshBuilder.CreateGroundFromHeightMap
  37704. * * width the width (x direction) of the ground
  37705. * * height the height (z direction) of the ground
  37706. * * subdivisions the number of subdivisions per side
  37707. * * minHeight the minimum altitude on the ground, optional, default 0
  37708. * * maxHeight the maximum altitude on the ground, optional default 1
  37709. * * colorFilter the filter to apply to the image pixel colors to compute the height, optional Color3, default (0.3, 0.59, 0.11)
  37710. * * buffer the array holding the image color data
  37711. * * bufferWidth the width of image
  37712. * * bufferHeight the height of image
  37713. * @returns the VertexData of the Ground designed from a heightmap
  37714. */
  37715. VertexData.CreateGroundFromHeightMap = function (options) {
  37716. var indices = [];
  37717. var positions = [];
  37718. var normals = [];
  37719. var uvs = [];
  37720. var row, col;
  37721. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  37722. // Vertices
  37723. for (row = 0; row <= options.subdivisions; row++) {
  37724. for (col = 0; col <= options.subdivisions; col++) {
  37725. 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));
  37726. // Compute height
  37727. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  37728. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  37729. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  37730. var r = options.buffer[pos] / 255.0;
  37731. var g = options.buffer[pos + 1] / 255.0;
  37732. var b = options.buffer[pos + 2] / 255.0;
  37733. var gradient = r * filter.r + g * filter.g + b * filter.b;
  37734. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  37735. // Add vertex
  37736. positions.push(position.x, position.y, position.z);
  37737. normals.push(0, 0, 0);
  37738. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  37739. }
  37740. }
  37741. // Indices
  37742. for (row = 0; row < options.subdivisions; row++) {
  37743. for (col = 0; col < options.subdivisions; col++) {
  37744. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  37745. indices.push(col + 1 + row * (options.subdivisions + 1));
  37746. indices.push(col + row * (options.subdivisions + 1));
  37747. indices.push(col + (row + 1) * (options.subdivisions + 1));
  37748. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  37749. indices.push(col + row * (options.subdivisions + 1));
  37750. }
  37751. }
  37752. // Normals
  37753. VertexData.ComputeNormals(positions, indices, normals);
  37754. // Result
  37755. var vertexData = new VertexData();
  37756. vertexData.indices = indices;
  37757. vertexData.positions = positions;
  37758. vertexData.normals = normals;
  37759. vertexData.uvs = uvs;
  37760. return vertexData;
  37761. };
  37762. /**
  37763. * Creates the VertexData for a Plane
  37764. * @param options an object used to set the following optional parameters for the plane, required but can be empty
  37765. * * size sets the width and height of the plane to the value of size, optional default 1
  37766. * * width sets the width (x direction) of the plane, overwrites the width set by size, optional, default size
  37767. * * height sets the height (y direction) of the plane, overwrites the height set by size, optional, default size
  37768. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37769. * * 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)
  37770. * * 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)
  37771. * @returns the VertexData of the box
  37772. */
  37773. VertexData.CreatePlane = function (options) {
  37774. var indices = [];
  37775. var positions = [];
  37776. var normals = [];
  37777. var uvs = [];
  37778. var width = options.width || options.size || 1;
  37779. var height = options.height || options.size || 1;
  37780. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37781. // Vertices
  37782. var halfWidth = width / 2.0;
  37783. var halfHeight = height / 2.0;
  37784. positions.push(-halfWidth, -halfHeight, 0);
  37785. normals.push(0, 0, -1.0);
  37786. uvs.push(0.0, 0.0);
  37787. positions.push(halfWidth, -halfHeight, 0);
  37788. normals.push(0, 0, -1.0);
  37789. uvs.push(1.0, 0.0);
  37790. positions.push(halfWidth, halfHeight, 0);
  37791. normals.push(0, 0, -1.0);
  37792. uvs.push(1.0, 1.0);
  37793. positions.push(-halfWidth, halfHeight, 0);
  37794. normals.push(0, 0, -1.0);
  37795. uvs.push(0.0, 1.0);
  37796. // Indices
  37797. indices.push(0);
  37798. indices.push(1);
  37799. indices.push(2);
  37800. indices.push(0);
  37801. indices.push(2);
  37802. indices.push(3);
  37803. // Sides
  37804. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37805. // Result
  37806. var vertexData = new VertexData();
  37807. vertexData.indices = indices;
  37808. vertexData.positions = positions;
  37809. vertexData.normals = normals;
  37810. vertexData.uvs = uvs;
  37811. return vertexData;
  37812. };
  37813. /**
  37814. * Creates the VertexData of the Disc or regular Polygon
  37815. * @param options an object used to set the following optional parameters for the disc, required but can be empty
  37816. * * radius the radius of the disc, optional default 0.5
  37817. * * tessellation the number of polygon sides, optional, default 64
  37818. * * 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
  37819. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37820. * * 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)
  37821. * * 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)
  37822. * @returns the VertexData of the box
  37823. */
  37824. VertexData.CreateDisc = function (options) {
  37825. var positions = new Array();
  37826. var indices = new Array();
  37827. var normals = new Array();
  37828. var uvs = new Array();
  37829. var radius = options.radius || 0.5;
  37830. var tessellation = options.tessellation || 64;
  37831. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  37832. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37833. // positions and uvs
  37834. positions.push(0, 0, 0); // disc center first
  37835. uvs.push(0.5, 0.5);
  37836. var theta = Math.PI * 2 * arc;
  37837. var step = theta / tessellation;
  37838. for (var a = 0; a < theta; a += step) {
  37839. var x = Math.cos(a);
  37840. var y = Math.sin(a);
  37841. var u = (x + 1) / 2;
  37842. var v = (1 - y) / 2;
  37843. positions.push(radius * x, radius * y, 0);
  37844. uvs.push(u, v);
  37845. }
  37846. if (arc === 1) {
  37847. positions.push(positions[3], positions[4], positions[5]); // close the circle
  37848. uvs.push(uvs[2], uvs[3]);
  37849. }
  37850. //indices
  37851. var vertexNb = positions.length / 3;
  37852. for (var i = 1; i < vertexNb - 1; i++) {
  37853. indices.push(i + 1, 0, i);
  37854. }
  37855. // result
  37856. VertexData.ComputeNormals(positions, indices, normals);
  37857. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37858. var vertexData = new VertexData();
  37859. vertexData.indices = indices;
  37860. vertexData.positions = positions;
  37861. vertexData.normals = normals;
  37862. vertexData.uvs = uvs;
  37863. return vertexData;
  37864. };
  37865. /**
  37866. * Creates the VertexData for an irregular Polygon in the XoZ plane using a mesh built by polygonTriangulation.build()
  37867. * All parameters are provided by MeshBuilder.CreatePolygon as needed
  37868. * @param polygon a mesh built from polygonTriangulation.build()
  37869. * @param sideOrientation takes the values BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37870. * @param fUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively
  37871. * @param fColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively
  37872. * @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)
  37873. * @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)
  37874. * @returns the VertexData of the Polygon
  37875. */
  37876. VertexData.CreatePolygon = function (polygon, sideOrientation, fUV, fColors, frontUVs, backUVs) {
  37877. var faceUV = fUV || new Array(3);
  37878. var faceColors = fColors;
  37879. var colors = [];
  37880. // default face colors and UV if undefined
  37881. for (var f = 0; f < 3; f++) {
  37882. if (faceUV[f] === undefined) {
  37883. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  37884. }
  37885. if (faceColors && faceColors[f] === undefined) {
  37886. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  37887. }
  37888. }
  37889. var positions = polygon.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  37890. var normals = polygon.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  37891. var uvs = polygon.getVerticesData(BABYLON.VertexBuffer.UVKind);
  37892. var indices = polygon.getIndices();
  37893. // set face colours and textures
  37894. var idx = 0;
  37895. var face = 0;
  37896. for (var index = 0; index < normals.length; index += 3) {
  37897. //Edge Face no. 1
  37898. if (Math.abs(normals[index + 1]) < 0.001) {
  37899. face = 1;
  37900. }
  37901. //Top Face no. 0
  37902. if (Math.abs(normals[index + 1] - 1) < 0.001) {
  37903. face = 0;
  37904. }
  37905. //Bottom Face no. 2
  37906. if (Math.abs(normals[index + 1] + 1) < 0.001) {
  37907. face = 2;
  37908. }
  37909. idx = index / 3;
  37910. uvs[2 * idx] = (1 - uvs[2 * idx]) * faceUV[face].x + uvs[2 * idx] * faceUV[face].z;
  37911. uvs[2 * idx + 1] = (1 - uvs[2 * idx + 1]) * faceUV[face].y + uvs[2 * idx + 1] * faceUV[face].w;
  37912. if (faceColors) {
  37913. colors.push(faceColors[face].r, faceColors[face].g, faceColors[face].b, faceColors[face].a);
  37914. }
  37915. }
  37916. // sides
  37917. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs);
  37918. // Result
  37919. var vertexData = new VertexData();
  37920. vertexData.indices = indices;
  37921. vertexData.positions = positions;
  37922. vertexData.normals = normals;
  37923. vertexData.uvs = uvs;
  37924. if (faceColors) {
  37925. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  37926. vertexData.colors = totalColors;
  37927. }
  37928. return vertexData;
  37929. };
  37930. /**
  37931. * Creates the VertexData of the IcoSphere
  37932. * @param options an object used to set the following optional parameters for the IcoSphere, required but can be empty
  37933. * * radius the radius of the IcoSphere, optional default 1
  37934. * * radiusX allows stretching in the x direction, optional, default radius
  37935. * * radiusY allows stretching in the y direction, optional, default radius
  37936. * * radiusZ allows stretching in the z direction, optional, default radius
  37937. * * flat when true creates a flat shaded mesh, optional, default true
  37938. * * subdivisions increasing the subdivisions increases the number of faces, optional, default 4
  37939. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37940. * * 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)
  37941. * * 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)
  37942. * @returns the VertexData of the IcoSphere
  37943. */
  37944. VertexData.CreateIcoSphere = function (options) {
  37945. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37946. var radius = options.radius || 1;
  37947. var flat = (options.flat === undefined) ? true : options.flat;
  37948. var subdivisions = options.subdivisions || 4;
  37949. var radiusX = options.radiusX || radius;
  37950. var radiusY = options.radiusY || radius;
  37951. var radiusZ = options.radiusZ || radius;
  37952. var t = (1 + Math.sqrt(5)) / 2;
  37953. // 12 vertex x,y,z
  37954. var ico_vertices = [
  37955. -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,
  37956. 0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,
  37957. t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11
  37958. ];
  37959. // index of 3 vertex makes a face of icopshere
  37960. var ico_indices = [
  37961. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23,
  37962. 1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8,
  37963. 14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9,
  37964. 4, 21, 5, 13, 17, 23, 6, 13, 22, 19, 6, 18, 9, 8, 1
  37965. ];
  37966. // vertex for uv have aliased position, not for UV
  37967. var vertices_unalias_id = [
  37968. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
  37969. // vertex alias
  37970. 0,
  37971. 2,
  37972. 3,
  37973. 3,
  37974. 3,
  37975. 4,
  37976. 7,
  37977. 8,
  37978. 9,
  37979. 9,
  37980. 10,
  37981. 11 // 23: B + 12
  37982. ];
  37983. // uv as integer step (not pixels !)
  37984. var ico_vertexuv = [
  37985. 5, 1, 3, 1, 6, 4, 0, 0,
  37986. 5, 3, 4, 2, 2, 2, 4, 0,
  37987. 2, 0, 1, 1, 6, 0, 6, 2,
  37988. // vertex alias (for same vertex on different faces)
  37989. 0, 4,
  37990. 3, 3,
  37991. 4, 4,
  37992. 3, 1,
  37993. 4, 2,
  37994. 4, 4,
  37995. 0, 2,
  37996. 1, 1,
  37997. 2, 2,
  37998. 3, 3,
  37999. 1, 3,
  38000. 2, 4 // 23: B + 12
  38001. ];
  38002. // Vertices[0, 1, ...9, A, B] : position on UV plane
  38003. // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B)
  38004. // First island of uv mapping
  38005. // v = 4h 3+ 2
  38006. // v = 3h 9+ 4
  38007. // v = 2h 9+ 5 B
  38008. // v = 1h 9 1 0
  38009. // v = 0h 3 8 7 A
  38010. // u = 0 1 2 3 4 5 6 *a
  38011. // Second island of uv mapping
  38012. // v = 4h 0+ B+ 4+
  38013. // v = 3h A+ 2+
  38014. // v = 2h 7+ 6 3+
  38015. // v = 1h 8+ 3+
  38016. // v = 0h
  38017. // u = 0 1 2 3 4 5 6 *a
  38018. // Face layout on texture UV mapping
  38019. // ============
  38020. // \ 4 /\ 16 / ======
  38021. // \ / \ / /\ 11 /
  38022. // \/ 7 \/ / \ /
  38023. // ======= / 10 \/
  38024. // /\ 17 /\ =======
  38025. // / \ / \ \ 15 /\
  38026. // / 8 \/ 12 \ \ / \
  38027. // ============ \/ 6 \
  38028. // \ 18 /\ ============
  38029. // \ / \ \ 5 /\ 0 /
  38030. // \/ 13 \ \ / \ /
  38031. // ======= \/ 1 \/
  38032. // =============
  38033. // /\ 19 /\ 2 /\
  38034. // / \ / \ / \
  38035. // / 14 \/ 9 \/ 3 \
  38036. // ===================
  38037. // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97
  38038. var ustep = 138 / 1024;
  38039. var vstep = 239 / 1024;
  38040. var uoffset = 60 / 1024;
  38041. var voffset = 26 / 1024;
  38042. // Second island should have margin, not to touch the first island
  38043. // avoid any borderline artefact in pixel rounding
  38044. var island_u_offset = -40 / 1024;
  38045. var island_v_offset = +20 / 1024;
  38046. // face is either island 0 or 1 :
  38047. // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18]
  38048. var island = [
  38049. 0, 0, 0, 0, 1,
  38050. 0, 0, 1, 1, 0,
  38051. 0, 0, 1, 1, 0,
  38052. 0, 1, 1, 1, 0 // 15 - 19
  38053. ];
  38054. var indices = new Array();
  38055. var positions = new Array();
  38056. var normals = new Array();
  38057. var uvs = new Array();
  38058. var current_indice = 0;
  38059. // prepare array of 3 vector (empty) (to be worked in place, shared for each face)
  38060. var face_vertex_pos = new Array(3);
  38061. var face_vertex_uv = new Array(3);
  38062. var v012;
  38063. for (v012 = 0; v012 < 3; v012++) {
  38064. face_vertex_pos[v012] = BABYLON.Vector3.Zero();
  38065. face_vertex_uv[v012] = BABYLON.Vector2.Zero();
  38066. }
  38067. // create all with normals
  38068. for (var face = 0; face < 20; face++) {
  38069. // 3 vertex per face
  38070. for (v012 = 0; v012 < 3; v012++) {
  38071. // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias)
  38072. var v_id = ico_indices[3 * face + v012];
  38073. // vertex have 3D position (x,y,z)
  38074. 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]);
  38075. // Normalize to get normal, then scale to radius
  38076. face_vertex_pos[v012].normalize().scaleInPlace(radius);
  38077. // uv Coordinates from vertex ID
  38078. 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);
  38079. }
  38080. // Subdivide the face (interpolate pos, norm, uv)
  38081. // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)
  38082. // - norm is linear interpolation of vertex corner normal
  38083. // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )
  38084. // - uv is linear interpolation
  38085. //
  38086. // Topology is as below for sub-divide by 2
  38087. // vertex shown as v0,v1,v2
  38088. // interp index is i1 to progress in range [v0,v1[
  38089. // interp index is i2 to progress in range [v0,v2[
  38090. // face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1)
  38091. // and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  38092. //
  38093. //
  38094. // i2 v2
  38095. // ^ ^
  38096. // / / \
  38097. // / / \
  38098. // / / \
  38099. // / / (0,1) \
  38100. // / #---------\
  38101. // / / \ (0,0)'/ \
  38102. // / / \ / \
  38103. // / / \ / \
  38104. // / / (0,0) \ / (1,0) \
  38105. // / #---------#---------\
  38106. // v0 v1
  38107. //
  38108. // --------------------> i1
  38109. //
  38110. // interp of (i1,i2):
  38111. // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)
  38112. // along i1 : lerp(x0,x1, i1/(S-i2))
  38113. //
  38114. // centroid of triangle is needed to get help normal computation
  38115. // (c1,c2) are used for centroid location
  38116. var interp_vertex = function (i1, i2, c1, c2) {
  38117. // vertex is interpolated from
  38118. // - face_vertex_pos[0..2]
  38119. // - face_vertex_uv[0..2]
  38120. var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
  38121. var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
  38122. var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
  38123. pos_interp.normalize();
  38124. var vertex_normal;
  38125. if (flat) {
  38126. // in flat mode, recalculate normal as face centroid normal
  38127. var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
  38128. var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
  38129. vertex_normal = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
  38130. }
  38131. else {
  38132. // in smooth mode, recalculate normal from each single vertex position
  38133. vertex_normal = new BABYLON.Vector3(pos_interp.x, pos_interp.y, pos_interp.z);
  38134. }
  38135. // Vertex normal need correction due to X,Y,Z radius scaling
  38136. vertex_normal.x /= radiusX;
  38137. vertex_normal.y /= radiusY;
  38138. vertex_normal.z /= radiusZ;
  38139. vertex_normal.normalize();
  38140. var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
  38141. var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
  38142. var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
  38143. positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);
  38144. normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
  38145. uvs.push(uv_interp.x, uv_interp.y);
  38146. // push each vertex has member of a face
  38147. // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)
  38148. indices.push(current_indice);
  38149. current_indice++;
  38150. };
  38151. for (var i2 = 0; i2 < subdivisions; i2++) {
  38152. for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
  38153. // face : (i1,i2) for /\ :
  38154. // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)
  38155. interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  38156. interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  38157. interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);
  38158. if (i1 + i2 + 1 < subdivisions) {
  38159. // face : (i1,i2)' for \/ :
  38160. // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  38161. interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);
  38162. interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  38163. interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  38164. }
  38165. }
  38166. }
  38167. }
  38168. // Sides
  38169. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  38170. // Result
  38171. var vertexData = new VertexData();
  38172. vertexData.indices = indices;
  38173. vertexData.positions = positions;
  38174. vertexData.normals = normals;
  38175. vertexData.uvs = uvs;
  38176. return vertexData;
  38177. };
  38178. // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
  38179. /**
  38180. * Creates the VertexData for a Polyhedron
  38181. * @param options an object used to set the following optional parameters for the polyhedron, required but can be empty
  38182. * * type provided types are:
  38183. * * 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  38184. * * 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)
  38185. * * size the size of the IcoSphere, optional default 1
  38186. * * sizeX allows stretching in the x direction, optional, default size
  38187. * * sizeY allows stretching in the y direction, optional, default size
  38188. * * sizeZ allows stretching in the z direction, optional, default size
  38189. * * 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
  38190. * * faceUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively
  38191. * * faceColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively
  38192. * * flat when true creates a flat shaded mesh, optional, default true
  38193. * * subdivisions increasing the subdivisions increases the number of faces, optional, default 4
  38194. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38195. * * 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)
  38196. * * 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)
  38197. * @returns the VertexData of the Polyhedron
  38198. */
  38199. VertexData.CreatePolyhedron = function (options) {
  38200. // provided polyhedron types :
  38201. // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  38202. // 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)
  38203. var polyhedra = [];
  38204. 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]] };
  38205. 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]] };
  38206. polyhedra[2] = {
  38207. 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]],
  38208. 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]]
  38209. };
  38210. polyhedra[3] = {
  38211. 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]],
  38212. 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]]
  38213. };
  38214. polyhedra[4] = {
  38215. 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]],
  38216. 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]]
  38217. };
  38218. 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]] };
  38219. 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]] };
  38220. 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]] };
  38221. 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]] };
  38222. 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]] };
  38223. 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]] };
  38224. 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]] };
  38225. 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]] };
  38226. 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]] };
  38227. polyhedra[14] = {
  38228. 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]],
  38229. 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]]
  38230. };
  38231. var type = options.type && (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
  38232. var size = options.size;
  38233. var sizeX = options.sizeX || size || 1;
  38234. var sizeY = options.sizeY || size || 1;
  38235. var sizeZ = options.sizeZ || size || 1;
  38236. var data = options.custom || polyhedra[type];
  38237. var nbfaces = data.face.length;
  38238. var faceUV = options.faceUV || new Array(nbfaces);
  38239. var faceColors = options.faceColors;
  38240. var flat = (options.flat === undefined) ? true : options.flat;
  38241. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38242. var positions = new Array();
  38243. var indices = new Array();
  38244. var normals = new Array();
  38245. var uvs = new Array();
  38246. var colors = new Array();
  38247. var index = 0;
  38248. var faceIdx = 0; // face cursor in the array "indexes"
  38249. var indexes = new Array();
  38250. var i = 0;
  38251. var f = 0;
  38252. var u, v, ang, x, y, tmp;
  38253. // default face colors and UV if undefined
  38254. if (flat) {
  38255. for (f = 0; f < nbfaces; f++) {
  38256. if (faceColors && faceColors[f] === undefined) {
  38257. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  38258. }
  38259. if (faceUV && faceUV[f] === undefined) {
  38260. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  38261. }
  38262. }
  38263. }
  38264. if (!flat) {
  38265. for (i = 0; i < data.vertex.length; i++) {
  38266. positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
  38267. uvs.push(0, 0);
  38268. }
  38269. for (f = 0; f < nbfaces; f++) {
  38270. for (i = 0; i < data.face[f].length - 2; i++) {
  38271. indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
  38272. }
  38273. }
  38274. }
  38275. else {
  38276. for (f = 0; f < nbfaces; f++) {
  38277. var fl = data.face[f].length; // number of vertices of the current face
  38278. ang = 2 * Math.PI / fl;
  38279. x = 0.5 * Math.tan(ang / 2);
  38280. y = 0.5;
  38281. // positions, uvs, colors
  38282. for (i = 0; i < fl; i++) {
  38283. // positions
  38284. 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);
  38285. indexes.push(index);
  38286. index++;
  38287. // uvs
  38288. u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
  38289. v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
  38290. uvs.push(u, v);
  38291. tmp = x * Math.cos(ang) - y * Math.sin(ang);
  38292. y = x * Math.sin(ang) + y * Math.cos(ang);
  38293. x = tmp;
  38294. // colors
  38295. if (faceColors) {
  38296. colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
  38297. }
  38298. }
  38299. // indices from indexes
  38300. for (i = 0; i < fl - 2; i++) {
  38301. indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
  38302. }
  38303. faceIdx += fl;
  38304. }
  38305. }
  38306. VertexData.ComputeNormals(positions, indices, normals);
  38307. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  38308. var vertexData = new VertexData();
  38309. vertexData.positions = positions;
  38310. vertexData.indices = indices;
  38311. vertexData.normals = normals;
  38312. vertexData.uvs = uvs;
  38313. if (faceColors && flat) {
  38314. vertexData.colors = colors;
  38315. }
  38316. return vertexData;
  38317. };
  38318. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  38319. /**
  38320. * Creates the VertexData for a TorusKnot
  38321. * @param options an object used to set the following optional parameters for the TorusKnot, required but can be empty
  38322. * * radius the radius of the torus knot, optional, default 2
  38323. * * tube the thickness of the tube, optional, default 0.5
  38324. * * radialSegments the number of sides on each tube segments, optional, default 32
  38325. * * tubularSegments the number of tubes to decompose the knot into, optional, default 32
  38326. * * p the number of windings around the z axis, optional, default 2
  38327. * * q the number of windings around the x axis, optional, default 3
  38328. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38329. * * 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)
  38330. * * 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)
  38331. * @returns the VertexData of the Torus Knot
  38332. */
  38333. VertexData.CreateTorusKnot = function (options) {
  38334. var indices = new Array();
  38335. var positions = new Array();
  38336. var normals = new Array();
  38337. var uvs = new Array();
  38338. var radius = options.radius || 2;
  38339. var tube = options.tube || 0.5;
  38340. var radialSegments = options.radialSegments || 32;
  38341. var tubularSegments = options.tubularSegments || 32;
  38342. var p = options.p || 2;
  38343. var q = options.q || 3;
  38344. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38345. // Helper
  38346. var getPos = function (angle) {
  38347. var cu = Math.cos(angle);
  38348. var su = Math.sin(angle);
  38349. var quOverP = q / p * angle;
  38350. var cs = Math.cos(quOverP);
  38351. var tx = radius * (2 + cs) * 0.5 * cu;
  38352. var ty = radius * (2 + cs) * su * 0.5;
  38353. var tz = radius * Math.sin(quOverP) * 0.5;
  38354. return new BABYLON.Vector3(tx, ty, tz);
  38355. };
  38356. // Vertices
  38357. var i;
  38358. var j;
  38359. for (i = 0; i <= radialSegments; i++) {
  38360. var modI = i % radialSegments;
  38361. var u = modI / radialSegments * 2 * p * Math.PI;
  38362. var p1 = getPos(u);
  38363. var p2 = getPos(u + 0.01);
  38364. var tang = p2.subtract(p1);
  38365. var n = p2.add(p1);
  38366. var bitan = BABYLON.Vector3.Cross(tang, n);
  38367. n = BABYLON.Vector3.Cross(bitan, tang);
  38368. bitan.normalize();
  38369. n.normalize();
  38370. for (j = 0; j < tubularSegments; j++) {
  38371. var modJ = j % tubularSegments;
  38372. var v = modJ / tubularSegments * 2 * Math.PI;
  38373. var cx = -tube * Math.cos(v);
  38374. var cy = tube * Math.sin(v);
  38375. positions.push(p1.x + cx * n.x + cy * bitan.x);
  38376. positions.push(p1.y + cx * n.y + cy * bitan.y);
  38377. positions.push(p1.z + cx * n.z + cy * bitan.z);
  38378. uvs.push(i / radialSegments);
  38379. uvs.push(j / tubularSegments);
  38380. }
  38381. }
  38382. for (i = 0; i < radialSegments; i++) {
  38383. for (j = 0; j < tubularSegments; j++) {
  38384. var jNext = (j + 1) % tubularSegments;
  38385. var a = i * tubularSegments + j;
  38386. var b = (i + 1) * tubularSegments + j;
  38387. var c = (i + 1) * tubularSegments + jNext;
  38388. var d = i * tubularSegments + jNext;
  38389. indices.push(d);
  38390. indices.push(b);
  38391. indices.push(a);
  38392. indices.push(d);
  38393. indices.push(c);
  38394. indices.push(b);
  38395. }
  38396. }
  38397. // Normals
  38398. VertexData.ComputeNormals(positions, indices, normals);
  38399. // Sides
  38400. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  38401. // Result
  38402. var vertexData = new VertexData();
  38403. vertexData.indices = indices;
  38404. vertexData.positions = positions;
  38405. vertexData.normals = normals;
  38406. vertexData.uvs = uvs;
  38407. return vertexData;
  38408. };
  38409. // Tools
  38410. /**
  38411. * Compute normals for given positions and indices
  38412. * @param positions an array of vertex positions, [...., x, y, z, ......]
  38413. * @param indices an array of indices in groups of three for each triangular facet, [...., i, j, k, ......]
  38414. * @param normals an array of vertex normals, [...., x, y, z, ......]
  38415. * @param options an object used to set the following optional parameters for the TorusKnot, optional
  38416. * * facetNormals : optional array of facet normals (vector3)
  38417. * * facetPositions : optional array of facet positions (vector3)
  38418. * * facetPartitioning : optional partitioning array. facetPositions is required for facetPartitioning computation
  38419. * * ratio : optional partitioning ratio / bounding box, required for facetPartitioning computation
  38420. * * bInfo : optional bounding info, required for facetPartitioning computation
  38421. * * bbSize : optional bounding box size data, required for facetPartitioning computation
  38422. * * subDiv : optional partitioning data about subdivsions on each axis (int), required for facetPartitioning computation
  38423. * * useRightHandedSystem: optional boolean to for right handed system computation
  38424. * * depthSort : optional boolean to enable the facet depth sort computation
  38425. * * distanceTo : optional Vector3 to compute the facet depth from this location
  38426. * * depthSortedFacets : optional array of depthSortedFacets to store the facet distances from the reference location
  38427. */
  38428. VertexData.ComputeNormals = function (positions, indices, normals, options) {
  38429. // temporary scalar variables
  38430. var index = 0; // facet index
  38431. var p1p2x = 0.0; // p1p2 vector x coordinate
  38432. var p1p2y = 0.0; // p1p2 vector y coordinate
  38433. var p1p2z = 0.0; // p1p2 vector z coordinate
  38434. var p3p2x = 0.0; // p3p2 vector x coordinate
  38435. var p3p2y = 0.0; // p3p2 vector y coordinate
  38436. var p3p2z = 0.0; // p3p2 vector z coordinate
  38437. var faceNormalx = 0.0; // facet normal x coordinate
  38438. var faceNormaly = 0.0; // facet normal y coordinate
  38439. var faceNormalz = 0.0; // facet normal z coordinate
  38440. var length = 0.0; // facet normal length before normalization
  38441. var v1x = 0; // vector1 x index in the positions array
  38442. var v1y = 0; // vector1 y index in the positions array
  38443. var v1z = 0; // vector1 z index in the positions array
  38444. var v2x = 0; // vector2 x index in the positions array
  38445. var v2y = 0; // vector2 y index in the positions array
  38446. var v2z = 0; // vector2 z index in the positions array
  38447. var v3x = 0; // vector3 x index in the positions array
  38448. var v3y = 0; // vector3 y index in the positions array
  38449. var v3z = 0; // vector3 z index in the positions array
  38450. var computeFacetNormals = false;
  38451. var computeFacetPositions = false;
  38452. var computeFacetPartitioning = false;
  38453. var computeDepthSort = false;
  38454. var faceNormalSign = 1;
  38455. var ratio = 0;
  38456. var distanceTo = null;
  38457. if (options) {
  38458. computeFacetNormals = (options.facetNormals) ? true : false;
  38459. computeFacetPositions = (options.facetPositions) ? true : false;
  38460. computeFacetPartitioning = (options.facetPartitioning) ? true : false;
  38461. faceNormalSign = (options.useRightHandedSystem === true) ? -1 : 1;
  38462. ratio = options.ratio || 0;
  38463. computeDepthSort = (options.depthSort) ? true : false;
  38464. distanceTo = (options.distanceTo);
  38465. if (computeDepthSort) {
  38466. if (distanceTo === undefined) {
  38467. distanceTo = BABYLON.Vector3.Zero();
  38468. }
  38469. var depthSortedFacets = options.depthSortedFacets;
  38470. }
  38471. }
  38472. // facetPartitioning reinit if needed
  38473. var xSubRatio = 0;
  38474. var ySubRatio = 0;
  38475. var zSubRatio = 0;
  38476. var subSq = 0;
  38477. if (computeFacetPartitioning && options && options.bbSize) {
  38478. var ox = 0; // X partitioning index for facet position
  38479. var oy = 0; // Y partinioning index for facet position
  38480. var oz = 0; // Z partinioning index for facet position
  38481. var b1x = 0; // X partitioning index for facet v1 vertex
  38482. var b1y = 0; // Y partitioning index for facet v1 vertex
  38483. var b1z = 0; // z partitioning index for facet v1 vertex
  38484. var b2x = 0; // X partitioning index for facet v2 vertex
  38485. var b2y = 0; // Y partitioning index for facet v2 vertex
  38486. var b2z = 0; // Z partitioning index for facet v2 vertex
  38487. var b3x = 0; // X partitioning index for facet v3 vertex
  38488. var b3y = 0; // Y partitioning index for facet v3 vertex
  38489. var b3z = 0; // Z partitioning index for facet v3 vertex
  38490. var block_idx_o = 0; // facet barycenter block index
  38491. var block_idx_v1 = 0; // v1 vertex block index
  38492. var block_idx_v2 = 0; // v2 vertex block index
  38493. var block_idx_v3 = 0; // v3 vertex block index
  38494. var bbSizeMax = (options.bbSize.x > options.bbSize.y) ? options.bbSize.x : options.bbSize.y;
  38495. bbSizeMax = (bbSizeMax > options.bbSize.z) ? bbSizeMax : options.bbSize.z;
  38496. xSubRatio = options.subDiv.X * ratio / options.bbSize.x;
  38497. ySubRatio = options.subDiv.Y * ratio / options.bbSize.y;
  38498. zSubRatio = options.subDiv.Z * ratio / options.bbSize.z;
  38499. subSq = options.subDiv.max * options.subDiv.max;
  38500. options.facetPartitioning.length = 0;
  38501. }
  38502. // reset the normals
  38503. for (index = 0; index < positions.length; index++) {
  38504. normals[index] = 0.0;
  38505. }
  38506. // Loop : 1 indice triplet = 1 facet
  38507. var nbFaces = (indices.length / 3) | 0;
  38508. for (index = 0; index < nbFaces; index++) {
  38509. // get the indexes of the coordinates of each vertex of the facet
  38510. v1x = indices[index * 3] * 3;
  38511. v1y = v1x + 1;
  38512. v1z = v1x + 2;
  38513. v2x = indices[index * 3 + 1] * 3;
  38514. v2y = v2x + 1;
  38515. v2z = v2x + 2;
  38516. v3x = indices[index * 3 + 2] * 3;
  38517. v3y = v3x + 1;
  38518. v3z = v3x + 2;
  38519. p1p2x = positions[v1x] - positions[v2x]; // compute two vectors per facet : p1p2 and p3p2
  38520. p1p2y = positions[v1y] - positions[v2y];
  38521. p1p2z = positions[v1z] - positions[v2z];
  38522. p3p2x = positions[v3x] - positions[v2x];
  38523. p3p2y = positions[v3y] - positions[v2y];
  38524. p3p2z = positions[v3z] - positions[v2z];
  38525. // compute the face normal with the cross product
  38526. faceNormalx = faceNormalSign * (p1p2y * p3p2z - p1p2z * p3p2y);
  38527. faceNormaly = faceNormalSign * (p1p2z * p3p2x - p1p2x * p3p2z);
  38528. faceNormalz = faceNormalSign * (p1p2x * p3p2y - p1p2y * p3p2x);
  38529. // normalize this normal and store it in the array facetData
  38530. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  38531. length = (length === 0) ? 1.0 : length;
  38532. faceNormalx /= length;
  38533. faceNormaly /= length;
  38534. faceNormalz /= length;
  38535. if (computeFacetNormals && options) {
  38536. options.facetNormals[index].x = faceNormalx;
  38537. options.facetNormals[index].y = faceNormaly;
  38538. options.facetNormals[index].z = faceNormalz;
  38539. }
  38540. if (computeFacetPositions && options) {
  38541. // compute and the facet barycenter coordinates in the array facetPositions
  38542. options.facetPositions[index].x = (positions[v1x] + positions[v2x] + positions[v3x]) / 3.0;
  38543. options.facetPositions[index].y = (positions[v1y] + positions[v2y] + positions[v3y]) / 3.0;
  38544. options.facetPositions[index].z = (positions[v1z] + positions[v2z] + positions[v3z]) / 3.0;
  38545. }
  38546. if (computeFacetPartitioning && options) {
  38547. // store the facet indexes in arrays in the main facetPartitioning array :
  38548. // compute each facet vertex (+ facet barycenter) index in the partiniong array
  38549. ox = Math.floor((options.facetPositions[index].x - options.bInfo.minimum.x * ratio) * xSubRatio);
  38550. oy = Math.floor((options.facetPositions[index].y - options.bInfo.minimum.y * ratio) * ySubRatio);
  38551. oz = Math.floor((options.facetPositions[index].z - options.bInfo.minimum.z * ratio) * zSubRatio);
  38552. b1x = Math.floor((positions[v1x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  38553. b1y = Math.floor((positions[v1y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  38554. b1z = Math.floor((positions[v1z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  38555. b2x = Math.floor((positions[v2x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  38556. b2y = Math.floor((positions[v2y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  38557. b2z = Math.floor((positions[v2z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  38558. b3x = Math.floor((positions[v3x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  38559. b3y = Math.floor((positions[v3y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  38560. b3z = Math.floor((positions[v3z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  38561. block_idx_v1 = b1x + options.subDiv.max * b1y + subSq * b1z;
  38562. block_idx_v2 = b2x + options.subDiv.max * b2y + subSq * b2z;
  38563. block_idx_v3 = b3x + options.subDiv.max * b3y + subSq * b3z;
  38564. block_idx_o = ox + options.subDiv.max * oy + subSq * oz;
  38565. options.facetPartitioning[block_idx_o] = options.facetPartitioning[block_idx_o] ? options.facetPartitioning[block_idx_o] : new Array();
  38566. options.facetPartitioning[block_idx_v1] = options.facetPartitioning[block_idx_v1] ? options.facetPartitioning[block_idx_v1] : new Array();
  38567. options.facetPartitioning[block_idx_v2] = options.facetPartitioning[block_idx_v2] ? options.facetPartitioning[block_idx_v2] : new Array();
  38568. options.facetPartitioning[block_idx_v3] = options.facetPartitioning[block_idx_v3] ? options.facetPartitioning[block_idx_v3] : new Array();
  38569. // push each facet index in each block containing the vertex
  38570. options.facetPartitioning[block_idx_v1].push(index);
  38571. if (block_idx_v2 != block_idx_v1) {
  38572. options.facetPartitioning[block_idx_v2].push(index);
  38573. }
  38574. if (!(block_idx_v3 == block_idx_v2 || block_idx_v3 == block_idx_v1)) {
  38575. options.facetPartitioning[block_idx_v3].push(index);
  38576. }
  38577. if (!(block_idx_o == block_idx_v1 || block_idx_o == block_idx_v2 || block_idx_o == block_idx_v3)) {
  38578. options.facetPartitioning[block_idx_o].push(index);
  38579. }
  38580. }
  38581. if (computeDepthSort && options && options.facetPositions) {
  38582. var dsf = depthSortedFacets[index];
  38583. dsf.ind = index * 3;
  38584. dsf.sqDistance = BABYLON.Vector3.DistanceSquared(options.facetPositions[index], distanceTo);
  38585. }
  38586. // compute the normals anyway
  38587. normals[v1x] += faceNormalx; // accumulate all the normals per face
  38588. normals[v1y] += faceNormaly;
  38589. normals[v1z] += faceNormalz;
  38590. normals[v2x] += faceNormalx;
  38591. normals[v2y] += faceNormaly;
  38592. normals[v2z] += faceNormalz;
  38593. normals[v3x] += faceNormalx;
  38594. normals[v3y] += faceNormaly;
  38595. normals[v3z] += faceNormalz;
  38596. }
  38597. // last normalization of each normal
  38598. for (index = 0; index < normals.length / 3; index++) {
  38599. faceNormalx = normals[index * 3];
  38600. faceNormaly = normals[index * 3 + 1];
  38601. faceNormalz = normals[index * 3 + 2];
  38602. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  38603. length = (length === 0) ? 1.0 : length;
  38604. faceNormalx /= length;
  38605. faceNormaly /= length;
  38606. faceNormalz /= length;
  38607. normals[index * 3] = faceNormalx;
  38608. normals[index * 3 + 1] = faceNormaly;
  38609. normals[index * 3 + 2] = faceNormalz;
  38610. }
  38611. };
  38612. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs) {
  38613. var li = indices.length;
  38614. var ln = normals.length;
  38615. var i;
  38616. var n;
  38617. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38618. switch (sideOrientation) {
  38619. case BABYLON.Mesh.FRONTSIDE:
  38620. // nothing changed
  38621. break;
  38622. case BABYLON.Mesh.BACKSIDE:
  38623. var tmp;
  38624. // indices
  38625. for (i = 0; i < li; i += 3) {
  38626. tmp = indices[i];
  38627. indices[i] = indices[i + 2];
  38628. indices[i + 2] = tmp;
  38629. }
  38630. // normals
  38631. for (n = 0; n < ln; n++) {
  38632. normals[n] = -normals[n];
  38633. }
  38634. break;
  38635. case BABYLON.Mesh.DOUBLESIDE:
  38636. // positions
  38637. var lp = positions.length;
  38638. var l = lp / 3;
  38639. for (var p = 0; p < lp; p++) {
  38640. positions[lp + p] = positions[p];
  38641. }
  38642. // indices
  38643. for (i = 0; i < li; i += 3) {
  38644. indices[i + li] = indices[i + 2] + l;
  38645. indices[i + 1 + li] = indices[i + 1] + l;
  38646. indices[i + 2 + li] = indices[i] + l;
  38647. }
  38648. // normals
  38649. for (n = 0; n < ln; n++) {
  38650. normals[ln + n] = -normals[n];
  38651. }
  38652. // uvs
  38653. var lu = uvs.length;
  38654. var u = 0;
  38655. for (u = 0; u < lu; u++) {
  38656. uvs[u + lu] = uvs[u];
  38657. }
  38658. frontUVs = frontUVs ? frontUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  38659. backUVs = backUVs ? backUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  38660. u = 0;
  38661. for (i = 0; i < lu / 2; i++) {
  38662. uvs[u] = frontUVs.x + (frontUVs.z - frontUVs.x) * uvs[u];
  38663. uvs[u + 1] = frontUVs.y + (frontUVs.w - frontUVs.y) * uvs[u + 1];
  38664. uvs[u + lu] = backUVs.x + (backUVs.z - backUVs.x) * uvs[u + lu];
  38665. uvs[u + lu + 1] = backUVs.y + (backUVs.w - backUVs.y) * uvs[u + lu + 1];
  38666. u += 2;
  38667. }
  38668. break;
  38669. }
  38670. };
  38671. /**
  38672. * Applies VertexData created from the imported parameters to the geometry
  38673. * @param parsedVertexData the parsed data from an imported file
  38674. * @param geometry the geometry to apply the VertexData to
  38675. */
  38676. VertexData.ImportVertexData = function (parsedVertexData, geometry) {
  38677. var vertexData = new VertexData();
  38678. // positions
  38679. var positions = parsedVertexData.positions;
  38680. if (positions) {
  38681. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  38682. }
  38683. // normals
  38684. var normals = parsedVertexData.normals;
  38685. if (normals) {
  38686. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  38687. }
  38688. // tangents
  38689. var tangents = parsedVertexData.tangents;
  38690. if (tangents) {
  38691. vertexData.set(tangents, BABYLON.VertexBuffer.TangentKind);
  38692. }
  38693. // uvs
  38694. var uvs = parsedVertexData.uvs;
  38695. if (uvs) {
  38696. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  38697. }
  38698. // uv2s
  38699. var uv2s = parsedVertexData.uv2s;
  38700. if (uv2s) {
  38701. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  38702. }
  38703. // uv3s
  38704. var uv3s = parsedVertexData.uv3s;
  38705. if (uv3s) {
  38706. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  38707. }
  38708. // uv4s
  38709. var uv4s = parsedVertexData.uv4s;
  38710. if (uv4s) {
  38711. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  38712. }
  38713. // uv5s
  38714. var uv5s = parsedVertexData.uv5s;
  38715. if (uv5s) {
  38716. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  38717. }
  38718. // uv6s
  38719. var uv6s = parsedVertexData.uv6s;
  38720. if (uv6s) {
  38721. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  38722. }
  38723. // colors
  38724. var colors = parsedVertexData.colors;
  38725. if (colors) {
  38726. vertexData.set(BABYLON.Color4.CheckColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  38727. }
  38728. // matricesIndices
  38729. var matricesIndices = parsedVertexData.matricesIndices;
  38730. if (matricesIndices) {
  38731. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  38732. }
  38733. // matricesWeights
  38734. var matricesWeights = parsedVertexData.matricesWeights;
  38735. if (matricesWeights) {
  38736. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  38737. }
  38738. // indices
  38739. var indices = parsedVertexData.indices;
  38740. if (indices) {
  38741. vertexData.indices = indices;
  38742. }
  38743. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  38744. };
  38745. return VertexData;
  38746. }());
  38747. BABYLON.VertexData = VertexData;
  38748. })(BABYLON || (BABYLON = {}));
  38749. //# sourceMappingURL=babylon.mesh.vertexData.js.map
  38750. var BABYLON;
  38751. (function (BABYLON) {
  38752. /**
  38753. * Class used to store geometry data (vertex buffers + index buffer)
  38754. */
  38755. var Geometry = /** @class */ (function () {
  38756. /**
  38757. * Creates a new geometry
  38758. * @param id defines the unique ID
  38759. * @param scene defines the hosting scene
  38760. * @param vertexData defines the {BABYLON.VertexData} used to get geometry data
  38761. * @param updatable defines if geometry must be updatable (false by default)
  38762. * @param mesh defines the mesh that will be associated with the geometry
  38763. */
  38764. function Geometry(id, scene, vertexData, updatable, mesh) {
  38765. if (updatable === void 0) { updatable = false; }
  38766. if (mesh === void 0) { mesh = null; }
  38767. /**
  38768. * Gets the delay loading state of the geometry (none by default which means not delayed)
  38769. */
  38770. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  38771. this._totalVertices = 0;
  38772. this._isDisposed = false;
  38773. this._indexBufferIsUpdatable = false;
  38774. this.id = id;
  38775. this._engine = scene.getEngine();
  38776. this._meshes = [];
  38777. this._scene = scene;
  38778. //Init vertex buffer cache
  38779. this._vertexBuffers = {};
  38780. this._indices = [];
  38781. this._updatable = updatable;
  38782. // vertexData
  38783. if (vertexData) {
  38784. this.setAllVerticesData(vertexData, updatable);
  38785. }
  38786. else {
  38787. this._totalVertices = 0;
  38788. this._indices = [];
  38789. }
  38790. if (this._engine.getCaps().vertexArrayObject) {
  38791. this._vertexArrayObjects = {};
  38792. }
  38793. // applyToMesh
  38794. if (mesh) {
  38795. if (mesh.getClassName() === "LinesMesh") {
  38796. this.boundingBias = new BABYLON.Vector2(0, mesh.intersectionThreshold);
  38797. this._updateExtend();
  38798. }
  38799. this.applyToMesh(mesh);
  38800. mesh.computeWorldMatrix(true);
  38801. }
  38802. }
  38803. Object.defineProperty(Geometry.prototype, "boundingBias", {
  38804. /**
  38805. * 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
  38806. */
  38807. get: function () {
  38808. return this._boundingBias;
  38809. },
  38810. /**
  38811. * 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
  38812. */
  38813. set: function (value) {
  38814. if (this._boundingBias && this._boundingBias.equals(value)) {
  38815. return;
  38816. }
  38817. this._boundingBias = value.clone();
  38818. this._updateBoundingInfo(true, null);
  38819. },
  38820. enumerable: true,
  38821. configurable: true
  38822. });
  38823. /**
  38824. * Static function used to attach a new empty geometry to a mesh
  38825. * @param mesh defines the mesh to attach the geometry to
  38826. * @returns the new {BABYLON.Geometry}
  38827. */
  38828. Geometry.CreateGeometryForMesh = function (mesh) {
  38829. var geometry = new Geometry(Geometry.RandomId(), mesh.getScene());
  38830. geometry.applyToMesh(mesh);
  38831. return geometry;
  38832. };
  38833. Object.defineProperty(Geometry.prototype, "extend", {
  38834. /**
  38835. * Gets the current extend of the geometry
  38836. */
  38837. get: function () {
  38838. return this._extend;
  38839. },
  38840. enumerable: true,
  38841. configurable: true
  38842. });
  38843. /**
  38844. * Gets the hosting scene
  38845. * @returns the hosting {BABYLON.Scene}
  38846. */
  38847. Geometry.prototype.getScene = function () {
  38848. return this._scene;
  38849. };
  38850. /**
  38851. * Gets the hosting engine
  38852. * @returns the hosting {BABYLON.Engine}
  38853. */
  38854. Geometry.prototype.getEngine = function () {
  38855. return this._engine;
  38856. };
  38857. /**
  38858. * Defines if the geometry is ready to use
  38859. * @returns true if the geometry is ready to be used
  38860. */
  38861. Geometry.prototype.isReady = function () {
  38862. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  38863. };
  38864. Object.defineProperty(Geometry.prototype, "doNotSerialize", {
  38865. /**
  38866. * Gets a value indicating that the geometry should not be serialized
  38867. */
  38868. get: function () {
  38869. for (var index = 0; index < this._meshes.length; index++) {
  38870. if (!this._meshes[index].doNotSerialize) {
  38871. return false;
  38872. }
  38873. }
  38874. return true;
  38875. },
  38876. enumerable: true,
  38877. configurable: true
  38878. });
  38879. /** @hidden */
  38880. Geometry.prototype._rebuild = function () {
  38881. if (this._vertexArrayObjects) {
  38882. this._vertexArrayObjects = {};
  38883. }
  38884. // Index buffer
  38885. if (this._meshes.length !== 0 && this._indices) {
  38886. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  38887. }
  38888. // Vertex buffers
  38889. for (var key in this._vertexBuffers) {
  38890. var vertexBuffer = this._vertexBuffers[key];
  38891. vertexBuffer._rebuild();
  38892. }
  38893. };
  38894. /**
  38895. * Affects all gemetry data in one call
  38896. * @param vertexData defines the geometry data
  38897. * @param updatable defines if the geometry must be flagged as updatable (false as default)
  38898. */
  38899. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  38900. vertexData.applyToGeometry(this, updatable);
  38901. this.notifyUpdate();
  38902. };
  38903. /**
  38904. * Set specific vertex data
  38905. * @param kind defines the data kind (Position, normal, etc...)
  38906. * @param data defines the vertex data to use
  38907. * @param updatable defines if the vertex must be flagged as updatable (false as default)
  38908. * @param stride defines the stride to use (0 by default). This value is deduced from the kind value if not specified
  38909. */
  38910. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  38911. if (updatable === void 0) { updatable = false; }
  38912. var buffer = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  38913. this.setVerticesBuffer(buffer);
  38914. };
  38915. /**
  38916. * Removes a specific vertex data
  38917. * @param kind defines the data kind (Position, normal, etc...)
  38918. */
  38919. Geometry.prototype.removeVerticesData = function (kind) {
  38920. if (this._vertexBuffers[kind]) {
  38921. this._vertexBuffers[kind].dispose();
  38922. delete this._vertexBuffers[kind];
  38923. }
  38924. };
  38925. /**
  38926. * Affect a vertex buffer to the geometry. the vertexBuffer.getKind() function is used to determine where to store the data
  38927. * @param buffer defines the vertex buffer to use
  38928. * @param totalVertices defines the total number of vertices for position kind (could be null)
  38929. */
  38930. Geometry.prototype.setVerticesBuffer = function (buffer, totalVertices) {
  38931. if (totalVertices === void 0) { totalVertices = null; }
  38932. var kind = buffer.getKind();
  38933. if (this._vertexBuffers[kind]) {
  38934. this._vertexBuffers[kind].dispose();
  38935. }
  38936. this._vertexBuffers[kind] = buffer;
  38937. if (kind === BABYLON.VertexBuffer.PositionKind) {
  38938. var data = buffer.getData();
  38939. if (totalVertices != null) {
  38940. this._totalVertices = totalVertices;
  38941. }
  38942. else {
  38943. if (data != null) {
  38944. this._totalVertices = data.length / (buffer.byteStride / 4);
  38945. }
  38946. }
  38947. this._updateExtend(data);
  38948. this._resetPointsArrayCache();
  38949. var meshes = this._meshes;
  38950. var numOfMeshes = meshes.length;
  38951. for (var index = 0; index < numOfMeshes; index++) {
  38952. var mesh = meshes[index];
  38953. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  38954. mesh._createGlobalSubMesh(false);
  38955. mesh.computeWorldMatrix(true);
  38956. }
  38957. }
  38958. this.notifyUpdate(kind);
  38959. if (this._vertexArrayObjects) {
  38960. this._disposeVertexArrayObjects();
  38961. this._vertexArrayObjects = {}; // Will trigger a rebuild of the VAO if supported
  38962. }
  38963. };
  38964. /**
  38965. * Update a specific vertex buffer
  38966. * This function will directly update the underlying WebGLBuffer according to the passed numeric array or Float32Array
  38967. * It will do nothing if the buffer is not updatable
  38968. * @param kind defines the data kind (Position, normal, etc...)
  38969. * @param data defines the data to use
  38970. * @param offset defines the offset in the target buffer where to store the data
  38971. * @param useBytes set to true if the offset is in bytes
  38972. */
  38973. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset, useBytes) {
  38974. if (useBytes === void 0) { useBytes = false; }
  38975. var vertexBuffer = this.getVertexBuffer(kind);
  38976. if (!vertexBuffer) {
  38977. return;
  38978. }
  38979. vertexBuffer.updateDirectly(data, offset, useBytes);
  38980. this.notifyUpdate(kind);
  38981. };
  38982. /**
  38983. * Update a specific vertex buffer
  38984. * This function will create a new buffer if the current one is not updatable
  38985. * @param kind defines the data kind (Position, normal, etc...)
  38986. * @param data defines the data to use
  38987. * @param updateExtends defines if the geometry extends must be recomputed (false by default)
  38988. */
  38989. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  38990. if (updateExtends === void 0) { updateExtends = false; }
  38991. var vertexBuffer = this.getVertexBuffer(kind);
  38992. if (!vertexBuffer) {
  38993. return;
  38994. }
  38995. vertexBuffer.update(data);
  38996. if (kind === BABYLON.VertexBuffer.PositionKind) {
  38997. this._updateBoundingInfo(updateExtends, data);
  38998. }
  38999. this.notifyUpdate(kind);
  39000. };
  39001. Geometry.prototype._updateBoundingInfo = function (updateExtends, data) {
  39002. if (updateExtends) {
  39003. this._updateExtend(data);
  39004. }
  39005. var meshes = this._meshes;
  39006. var numOfMeshes = meshes.length;
  39007. this._resetPointsArrayCache();
  39008. for (var index = 0; index < numOfMeshes; index++) {
  39009. var mesh = meshes[index];
  39010. if (updateExtends) {
  39011. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  39012. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  39013. var subMesh = mesh.subMeshes[subIndex];
  39014. subMesh.refreshBoundingInfo();
  39015. }
  39016. }
  39017. }
  39018. };
  39019. /** @hidden */
  39020. Geometry.prototype._bind = function (effect, indexToBind) {
  39021. if (!effect) {
  39022. return;
  39023. }
  39024. if (indexToBind === undefined) {
  39025. indexToBind = this._indexBuffer;
  39026. }
  39027. var vbs = this.getVertexBuffers();
  39028. if (!vbs) {
  39029. return;
  39030. }
  39031. if (indexToBind != this._indexBuffer || !this._vertexArrayObjects) {
  39032. this._engine.bindBuffers(vbs, indexToBind, effect);
  39033. return;
  39034. }
  39035. // Using VAO
  39036. if (!this._vertexArrayObjects[effect.key]) {
  39037. this._vertexArrayObjects[effect.key] = this._engine.recordVertexArrayObject(vbs, indexToBind, effect);
  39038. }
  39039. this._engine.bindVertexArrayObject(this._vertexArrayObjects[effect.key], indexToBind);
  39040. };
  39041. /**
  39042. * Gets total number of vertices
  39043. * @returns the total number of vertices
  39044. */
  39045. Geometry.prototype.getTotalVertices = function () {
  39046. if (!this.isReady()) {
  39047. return 0;
  39048. }
  39049. return this._totalVertices;
  39050. };
  39051. /**
  39052. * Gets a specific vertex data attached to this geometry. Float data is constructed if the vertex buffer data cannot be returned directly.
  39053. * @param kind defines the data kind (Position, normal, etc...)
  39054. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  39055. * @param forceCopy defines a boolean indicating that the returned array must be cloned upon returning it
  39056. * @returns a float array containing vertex data
  39057. */
  39058. Geometry.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  39059. var vertexBuffer = this.getVertexBuffer(kind);
  39060. if (!vertexBuffer) {
  39061. return null;
  39062. }
  39063. var data = vertexBuffer.getData();
  39064. if (!data) {
  39065. return null;
  39066. }
  39067. var tightlyPackedByteStride = vertexBuffer.getSize() * BABYLON.VertexBuffer.GetTypeByteLength(vertexBuffer.type);
  39068. var count = this._totalVertices * vertexBuffer.getSize();
  39069. if (vertexBuffer.type !== BABYLON.VertexBuffer.FLOAT || vertexBuffer.byteStride !== tightlyPackedByteStride) {
  39070. var copy_1 = new Array(count);
  39071. vertexBuffer.forEach(count, function (value, index) {
  39072. copy_1[index] = value;
  39073. });
  39074. return copy_1;
  39075. }
  39076. if (!((data instanceof Array) || (data instanceof Float32Array)) || vertexBuffer.byteOffset !== 0 || data.length !== count) {
  39077. if (data instanceof Array) {
  39078. var offset = vertexBuffer.byteOffset / 4;
  39079. return BABYLON.Tools.Slice(data, offset, offset + count);
  39080. }
  39081. else if (data instanceof ArrayBuffer) {
  39082. return new Float32Array(data, vertexBuffer.byteOffset, count);
  39083. }
  39084. else {
  39085. return new Float32Array(data.buffer, data.byteOffset + vertexBuffer.byteOffset, count);
  39086. }
  39087. }
  39088. if (forceCopy || (copyWhenShared && this._meshes.length !== 1)) {
  39089. return BABYLON.Tools.Slice(data);
  39090. }
  39091. return data;
  39092. };
  39093. /**
  39094. * Returns a boolean defining if the vertex data for the requested `kind` is updatable
  39095. * @param kind defines the data kind (Position, normal, etc...)
  39096. * @returns true if the vertex buffer with the specified kind is updatable
  39097. */
  39098. Geometry.prototype.isVertexBufferUpdatable = function (kind) {
  39099. var vb = this._vertexBuffers[kind];
  39100. if (!vb) {
  39101. return false;
  39102. }
  39103. return vb.isUpdatable();
  39104. };
  39105. /**
  39106. * Gets a specific vertex buffer
  39107. * @param kind defines the data kind (Position, normal, etc...)
  39108. * @returns a {BABYLON.VertexBuffer}
  39109. */
  39110. Geometry.prototype.getVertexBuffer = function (kind) {
  39111. if (!this.isReady()) {
  39112. return null;
  39113. }
  39114. return this._vertexBuffers[kind];
  39115. };
  39116. /**
  39117. * Returns all vertex buffers
  39118. * @return an object holding all vertex buffers indexed by kind
  39119. */
  39120. Geometry.prototype.getVertexBuffers = function () {
  39121. if (!this.isReady()) {
  39122. return null;
  39123. }
  39124. return this._vertexBuffers;
  39125. };
  39126. /**
  39127. * Gets a boolean indicating if specific vertex buffer is present
  39128. * @param kind defines the data kind (Position, normal, etc...)
  39129. * @returns true if data is present
  39130. */
  39131. Geometry.prototype.isVerticesDataPresent = function (kind) {
  39132. if (!this._vertexBuffers) {
  39133. if (this._delayInfo) {
  39134. return this._delayInfo.indexOf(kind) !== -1;
  39135. }
  39136. return false;
  39137. }
  39138. return this._vertexBuffers[kind] !== undefined;
  39139. };
  39140. /**
  39141. * Gets a list of all attached data kinds (Position, normal, etc...)
  39142. * @returns a list of string containing all kinds
  39143. */
  39144. Geometry.prototype.getVerticesDataKinds = function () {
  39145. var result = [];
  39146. var kind;
  39147. if (!this._vertexBuffers && this._delayInfo) {
  39148. for (kind in this._delayInfo) {
  39149. result.push(kind);
  39150. }
  39151. }
  39152. else {
  39153. for (kind in this._vertexBuffers) {
  39154. result.push(kind);
  39155. }
  39156. }
  39157. return result;
  39158. };
  39159. /**
  39160. * Update index buffer
  39161. * @param indices defines the indices to store in the index buffer
  39162. * @param offset defines the offset in the target buffer where to store the data
  39163. */
  39164. Geometry.prototype.updateIndices = function (indices, offset) {
  39165. if (!this._indexBuffer) {
  39166. return;
  39167. }
  39168. if (!this._indexBufferIsUpdatable) {
  39169. this.setIndices(indices, null, true);
  39170. }
  39171. else {
  39172. this._engine.updateDynamicIndexBuffer(this._indexBuffer, indices, offset);
  39173. }
  39174. };
  39175. /**
  39176. * Creates a new index buffer
  39177. * @param indices defines the indices to store in the index buffer
  39178. * @param totalVertices defines the total number of vertices (could be null)
  39179. * @param updatable defines if the index buffer must be flagged as updatable (false by default)
  39180. */
  39181. Geometry.prototype.setIndices = function (indices, totalVertices, updatable) {
  39182. if (totalVertices === void 0) { totalVertices = null; }
  39183. if (updatable === void 0) { updatable = false; }
  39184. if (this._indexBuffer) {
  39185. this._engine._releaseBuffer(this._indexBuffer);
  39186. }
  39187. this._disposeVertexArrayObjects();
  39188. this._indices = indices;
  39189. this._indexBufferIsUpdatable = updatable;
  39190. if (this._meshes.length !== 0 && this._indices) {
  39191. this._indexBuffer = this._engine.createIndexBuffer(this._indices, updatable);
  39192. }
  39193. if (totalVertices != undefined) { // including null and undefined
  39194. this._totalVertices = totalVertices;
  39195. }
  39196. var meshes = this._meshes;
  39197. var numOfMeshes = meshes.length;
  39198. for (var index = 0; index < numOfMeshes; index++) {
  39199. meshes[index]._createGlobalSubMesh(true);
  39200. }
  39201. this.notifyUpdate();
  39202. };
  39203. /**
  39204. * Return the total number of indices
  39205. * @returns the total number of indices
  39206. */
  39207. Geometry.prototype.getTotalIndices = function () {
  39208. if (!this.isReady()) {
  39209. return 0;
  39210. }
  39211. return this._indices.length;
  39212. };
  39213. /**
  39214. * Gets the index buffer array
  39215. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  39216. * @returns the index buffer array
  39217. */
  39218. Geometry.prototype.getIndices = function (copyWhenShared) {
  39219. if (!this.isReady()) {
  39220. return null;
  39221. }
  39222. var orig = this._indices;
  39223. if (!copyWhenShared || this._meshes.length === 1) {
  39224. return orig;
  39225. }
  39226. else {
  39227. var len = orig.length;
  39228. var copy = [];
  39229. for (var i = 0; i < len; i++) {
  39230. copy.push(orig[i]);
  39231. }
  39232. return copy;
  39233. }
  39234. };
  39235. /**
  39236. * Gets the index buffer
  39237. * @return the index buffer
  39238. */
  39239. Geometry.prototype.getIndexBuffer = function () {
  39240. if (!this.isReady()) {
  39241. return null;
  39242. }
  39243. return this._indexBuffer;
  39244. };
  39245. /** @hidden */
  39246. Geometry.prototype._releaseVertexArrayObject = function (effect) {
  39247. if (effect === void 0) { effect = null; }
  39248. if (!effect || !this._vertexArrayObjects) {
  39249. return;
  39250. }
  39251. if (this._vertexArrayObjects[effect.key]) {
  39252. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[effect.key]);
  39253. delete this._vertexArrayObjects[effect.key];
  39254. }
  39255. };
  39256. /**
  39257. * Release the associated resources for a specific mesh
  39258. * @param mesh defines the source mesh
  39259. * @param shouldDispose defines if the geometry must be disposed if there is no more mesh pointing to it
  39260. */
  39261. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  39262. var meshes = this._meshes;
  39263. var index = meshes.indexOf(mesh);
  39264. if (index === -1) {
  39265. return;
  39266. }
  39267. meshes.splice(index, 1);
  39268. mesh._geometry = null;
  39269. if (meshes.length === 0 && shouldDispose) {
  39270. this.dispose();
  39271. }
  39272. };
  39273. /**
  39274. * Apply current geometry to a given mesh
  39275. * @param mesh defines the mesh to apply geometry to
  39276. */
  39277. Geometry.prototype.applyToMesh = function (mesh) {
  39278. if (mesh._geometry === this) {
  39279. return;
  39280. }
  39281. var previousGeometry = mesh._geometry;
  39282. if (previousGeometry) {
  39283. previousGeometry.releaseForMesh(mesh);
  39284. }
  39285. var meshes = this._meshes;
  39286. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  39287. mesh._geometry = this;
  39288. this._scene.pushGeometry(this);
  39289. meshes.push(mesh);
  39290. if (this.isReady()) {
  39291. this._applyToMesh(mesh);
  39292. }
  39293. else {
  39294. mesh._boundingInfo = this._boundingInfo;
  39295. }
  39296. };
  39297. Geometry.prototype._updateExtend = function (data) {
  39298. if (data === void 0) { data = null; }
  39299. if (!data) {
  39300. data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  39301. }
  39302. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices, this.boundingBias, 3);
  39303. };
  39304. Geometry.prototype._applyToMesh = function (mesh) {
  39305. var numOfMeshes = this._meshes.length;
  39306. // vertexBuffers
  39307. for (var kind in this._vertexBuffers) {
  39308. if (numOfMeshes === 1) {
  39309. this._vertexBuffers[kind].create();
  39310. }
  39311. var buffer = this._vertexBuffers[kind].getBuffer();
  39312. if (buffer)
  39313. buffer.references = numOfMeshes;
  39314. if (kind === BABYLON.VertexBuffer.PositionKind) {
  39315. if (!this._extend) {
  39316. this._updateExtend();
  39317. }
  39318. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  39319. mesh._createGlobalSubMesh(false);
  39320. //bounding info was just created again, world matrix should be applied again.
  39321. mesh._updateBoundingInfo();
  39322. }
  39323. }
  39324. // indexBuffer
  39325. if (numOfMeshes === 1 && this._indices && this._indices.length > 0) {
  39326. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  39327. }
  39328. if (this._indexBuffer) {
  39329. this._indexBuffer.references = numOfMeshes;
  39330. }
  39331. };
  39332. Geometry.prototype.notifyUpdate = function (kind) {
  39333. if (this.onGeometryUpdated) {
  39334. this.onGeometryUpdated(this, kind);
  39335. }
  39336. for (var _i = 0, _a = this._meshes; _i < _a.length; _i++) {
  39337. var mesh = _a[_i];
  39338. mesh._markSubMeshesAsAttributesDirty();
  39339. }
  39340. };
  39341. /**
  39342. * Load the geometry if it was flagged as delay loaded
  39343. * @param scene defines the hosting scene
  39344. * @param onLoaded defines a callback called when the geometry is loaded
  39345. */
  39346. Geometry.prototype.load = function (scene, onLoaded) {
  39347. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  39348. return;
  39349. }
  39350. if (this.isReady()) {
  39351. if (onLoaded) {
  39352. onLoaded();
  39353. }
  39354. return;
  39355. }
  39356. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  39357. this._queueLoad(scene, onLoaded);
  39358. };
  39359. Geometry.prototype._queueLoad = function (scene, onLoaded) {
  39360. var _this = this;
  39361. if (!this.delayLoadingFile) {
  39362. return;
  39363. }
  39364. scene._addPendingData(this);
  39365. scene._loadFile(this.delayLoadingFile, function (data) {
  39366. if (!_this._delayLoadingFunction) {
  39367. return;
  39368. }
  39369. _this._delayLoadingFunction(JSON.parse(data), _this);
  39370. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  39371. _this._delayInfo = [];
  39372. scene._removePendingData(_this);
  39373. var meshes = _this._meshes;
  39374. var numOfMeshes = meshes.length;
  39375. for (var index = 0; index < numOfMeshes; index++) {
  39376. _this._applyToMesh(meshes[index]);
  39377. }
  39378. if (onLoaded) {
  39379. onLoaded();
  39380. }
  39381. }, undefined, true);
  39382. };
  39383. /**
  39384. * Invert the geometry to move from a right handed system to a left handed one.
  39385. */
  39386. Geometry.prototype.toLeftHanded = function () {
  39387. // Flip faces
  39388. var tIndices = this.getIndices(false);
  39389. if (tIndices != null && tIndices.length > 0) {
  39390. for (var i = 0; i < tIndices.length; i += 3) {
  39391. var tTemp = tIndices[i + 0];
  39392. tIndices[i + 0] = tIndices[i + 2];
  39393. tIndices[i + 2] = tTemp;
  39394. }
  39395. this.setIndices(tIndices);
  39396. }
  39397. // Negate position.z
  39398. var tPositions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, false);
  39399. if (tPositions != null && tPositions.length > 0) {
  39400. for (var i = 0; i < tPositions.length; i += 3) {
  39401. tPositions[i + 2] = -tPositions[i + 2];
  39402. }
  39403. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, tPositions, false);
  39404. }
  39405. // Negate normal.z
  39406. var tNormals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind, false);
  39407. if (tNormals != null && tNormals.length > 0) {
  39408. for (var i = 0; i < tNormals.length; i += 3) {
  39409. tNormals[i + 2] = -tNormals[i + 2];
  39410. }
  39411. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, tNormals, false);
  39412. }
  39413. };
  39414. // Cache
  39415. /** @hidden */
  39416. Geometry.prototype._resetPointsArrayCache = function () {
  39417. this._positions = null;
  39418. };
  39419. /** @hidden */
  39420. Geometry.prototype._generatePointsArray = function () {
  39421. if (this._positions)
  39422. return true;
  39423. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  39424. if (!data || data.length === 0) {
  39425. return false;
  39426. }
  39427. this._positions = [];
  39428. for (var index = 0; index < data.length; index += 3) {
  39429. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  39430. }
  39431. return true;
  39432. };
  39433. /**
  39434. * Gets a value indicating if the geometry is disposed
  39435. * @returns true if the geometry was disposed
  39436. */
  39437. Geometry.prototype.isDisposed = function () {
  39438. return this._isDisposed;
  39439. };
  39440. Geometry.prototype._disposeVertexArrayObjects = function () {
  39441. if (this._vertexArrayObjects) {
  39442. for (var kind in this._vertexArrayObjects) {
  39443. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[kind]);
  39444. }
  39445. this._vertexArrayObjects = {};
  39446. }
  39447. };
  39448. /**
  39449. * Free all associated resources
  39450. */
  39451. Geometry.prototype.dispose = function () {
  39452. var meshes = this._meshes;
  39453. var numOfMeshes = meshes.length;
  39454. var index;
  39455. for (index = 0; index < numOfMeshes; index++) {
  39456. this.releaseForMesh(meshes[index]);
  39457. }
  39458. this._meshes = [];
  39459. this._disposeVertexArrayObjects();
  39460. for (var kind in this._vertexBuffers) {
  39461. this._vertexBuffers[kind].dispose();
  39462. }
  39463. this._vertexBuffers = {};
  39464. this._totalVertices = 0;
  39465. if (this._indexBuffer) {
  39466. this._engine._releaseBuffer(this._indexBuffer);
  39467. }
  39468. this._indexBuffer = null;
  39469. this._indices = [];
  39470. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  39471. this.delayLoadingFile = null;
  39472. this._delayLoadingFunction = null;
  39473. this._delayInfo = [];
  39474. this._boundingInfo = null;
  39475. this._scene.removeGeometry(this);
  39476. this._isDisposed = true;
  39477. };
  39478. /**
  39479. * Clone the current geometry into a new geometry
  39480. * @param id defines the unique ID of the new geometry
  39481. * @returns a new geometry object
  39482. */
  39483. Geometry.prototype.copy = function (id) {
  39484. var vertexData = new BABYLON.VertexData();
  39485. vertexData.indices = [];
  39486. var indices = this.getIndices();
  39487. if (indices) {
  39488. for (var index = 0; index < indices.length; index++) {
  39489. vertexData.indices.push(indices[index]);
  39490. }
  39491. }
  39492. var updatable = false;
  39493. var stopChecking = false;
  39494. var kind;
  39495. for (kind in this._vertexBuffers) {
  39496. // using slice() to make a copy of the array and not just reference it
  39497. var data = this.getVerticesData(kind);
  39498. if (data instanceof Float32Array) {
  39499. vertexData.set(new Float32Array(data), kind);
  39500. }
  39501. else {
  39502. vertexData.set(data.slice(0), kind);
  39503. }
  39504. if (!stopChecking) {
  39505. var vb = this.getVertexBuffer(kind);
  39506. if (vb) {
  39507. updatable = vb.isUpdatable();
  39508. stopChecking = !updatable;
  39509. }
  39510. }
  39511. }
  39512. var geometry = new Geometry(id, this._scene, vertexData, updatable);
  39513. geometry.delayLoadState = this.delayLoadState;
  39514. geometry.delayLoadingFile = this.delayLoadingFile;
  39515. geometry._delayLoadingFunction = this._delayLoadingFunction;
  39516. for (kind in this._delayInfo) {
  39517. geometry._delayInfo = geometry._delayInfo || [];
  39518. geometry._delayInfo.push(kind);
  39519. }
  39520. // Bounding info
  39521. geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  39522. return geometry;
  39523. };
  39524. /**
  39525. * Serialize the current geometry info (and not the vertices data) into a JSON object
  39526. * @return a JSON representation of the current geometry data (without the vertices data)
  39527. */
  39528. Geometry.prototype.serialize = function () {
  39529. var serializationObject = {};
  39530. serializationObject.id = this.id;
  39531. serializationObject.updatable = this._updatable;
  39532. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  39533. serializationObject.tags = BABYLON.Tags.GetTags(this);
  39534. }
  39535. return serializationObject;
  39536. };
  39537. Geometry.prototype.toNumberArray = function (origin) {
  39538. if (Array.isArray(origin)) {
  39539. return origin;
  39540. }
  39541. else {
  39542. return Array.prototype.slice.call(origin);
  39543. }
  39544. };
  39545. /**
  39546. * Serialize all vertices data into a JSON oject
  39547. * @returns a JSON representation of the current geometry data
  39548. */
  39549. Geometry.prototype.serializeVerticeData = function () {
  39550. var serializationObject = this.serialize();
  39551. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  39552. serializationObject.positions = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  39553. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  39554. serializationObject.positions._updatable = true;
  39555. }
  39556. }
  39557. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  39558. serializationObject.normals = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  39559. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  39560. serializationObject.normals._updatable = true;
  39561. }
  39562. }
  39563. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  39564. serializationObject.tangets = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  39565. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.TangentKind)) {
  39566. serializationObject.tangets._updatable = true;
  39567. }
  39568. }
  39569. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  39570. serializationObject.uvs = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UVKind));
  39571. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UVKind)) {
  39572. serializationObject.uvs._updatable = true;
  39573. }
  39574. }
  39575. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  39576. serializationObject.uv2s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV2Kind));
  39577. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV2Kind)) {
  39578. serializationObject.uv2s._updatable = true;
  39579. }
  39580. }
  39581. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  39582. serializationObject.uv3s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV3Kind));
  39583. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV3Kind)) {
  39584. serializationObject.uv3s._updatable = true;
  39585. }
  39586. }
  39587. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  39588. serializationObject.uv4s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV4Kind));
  39589. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV4Kind)) {
  39590. serializationObject.uv4s._updatable = true;
  39591. }
  39592. }
  39593. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  39594. serializationObject.uv5s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV5Kind));
  39595. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV5Kind)) {
  39596. serializationObject.uv5s._updatable = true;
  39597. }
  39598. }
  39599. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  39600. serializationObject.uv6s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV6Kind));
  39601. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV6Kind)) {
  39602. serializationObject.uv6s._updatable = true;
  39603. }
  39604. }
  39605. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  39606. serializationObject.colors = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.ColorKind));
  39607. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.ColorKind)) {
  39608. serializationObject.colors._updatable = true;
  39609. }
  39610. }
  39611. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  39612. serializationObject.matricesIndices = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind));
  39613. serializationObject.matricesIndices._isExpanded = true;
  39614. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  39615. serializationObject.matricesIndices._updatable = true;
  39616. }
  39617. }
  39618. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  39619. serializationObject.matricesWeights = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind));
  39620. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  39621. serializationObject.matricesWeights._updatable = true;
  39622. }
  39623. }
  39624. serializationObject.indices = this.toNumberArray(this.getIndices());
  39625. return serializationObject;
  39626. };
  39627. // Statics
  39628. /**
  39629. * Extracts a clone of a mesh geometry
  39630. * @param mesh defines the source mesh
  39631. * @param id defines the unique ID of the new geometry object
  39632. * @returns the new geometry object
  39633. */
  39634. Geometry.ExtractFromMesh = function (mesh, id) {
  39635. var geometry = mesh._geometry;
  39636. if (!geometry) {
  39637. return null;
  39638. }
  39639. return geometry.copy(id);
  39640. };
  39641. /**
  39642. * You should now use Tools.RandomId(), this method is still here for legacy reasons.
  39643. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  39644. * Be aware Math.random() could cause collisions, but:
  39645. * "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"
  39646. * @returns a string containing a new GUID
  39647. */
  39648. Geometry.RandomId = function () {
  39649. return BABYLON.Tools.RandomId();
  39650. };
  39651. /** @hidden */
  39652. Geometry._ImportGeometry = function (parsedGeometry, mesh) {
  39653. var scene = mesh.getScene();
  39654. // Geometry
  39655. var geometryId = parsedGeometry.geometryId;
  39656. if (geometryId) {
  39657. var geometry = scene.getGeometryByID(geometryId);
  39658. if (geometry) {
  39659. geometry.applyToMesh(mesh);
  39660. }
  39661. }
  39662. else if (parsedGeometry instanceof ArrayBuffer) {
  39663. var binaryInfo = mesh._binaryInfo;
  39664. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  39665. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  39666. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  39667. }
  39668. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  39669. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  39670. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  39671. }
  39672. if (binaryInfo.tangetsAttrDesc && binaryInfo.tangetsAttrDesc.count > 0) {
  39673. var tangentsData = new Float32Array(parsedGeometry, binaryInfo.tangetsAttrDesc.offset, binaryInfo.tangetsAttrDesc.count);
  39674. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, tangentsData, false);
  39675. }
  39676. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  39677. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  39678. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  39679. }
  39680. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  39681. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  39682. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  39683. }
  39684. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  39685. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  39686. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  39687. }
  39688. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  39689. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  39690. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  39691. }
  39692. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  39693. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  39694. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  39695. }
  39696. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  39697. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  39698. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  39699. }
  39700. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  39701. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  39702. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  39703. }
  39704. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  39705. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  39706. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  39707. }
  39708. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  39709. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  39710. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  39711. }
  39712. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  39713. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  39714. mesh.setIndices(indicesData, null);
  39715. }
  39716. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  39717. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  39718. mesh.subMeshes = [];
  39719. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  39720. var materialIndex = subMeshesData[(i * 5) + 0];
  39721. var verticesStart = subMeshesData[(i * 5) + 1];
  39722. var verticesCount = subMeshesData[(i * 5) + 2];
  39723. var indexStart = subMeshesData[(i * 5) + 3];
  39724. var indexCount = subMeshesData[(i * 5) + 4];
  39725. BABYLON.SubMesh.AddToMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  39726. }
  39727. }
  39728. }
  39729. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  39730. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, parsedGeometry.positions._updatable);
  39731. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, parsedGeometry.normals._updatable);
  39732. if (parsedGeometry.tangents) {
  39733. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, parsedGeometry.tangents, parsedGeometry.tangents._updatable);
  39734. }
  39735. if (parsedGeometry.uvs) {
  39736. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, parsedGeometry.uvs._updatable);
  39737. }
  39738. if (parsedGeometry.uvs2) {
  39739. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, parsedGeometry.uvs2._updatable);
  39740. }
  39741. if (parsedGeometry.uvs3) {
  39742. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, parsedGeometry.uvs3._updatable);
  39743. }
  39744. if (parsedGeometry.uvs4) {
  39745. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, parsedGeometry.uvs4._updatable);
  39746. }
  39747. if (parsedGeometry.uvs5) {
  39748. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, parsedGeometry.uvs5._updatable);
  39749. }
  39750. if (parsedGeometry.uvs6) {
  39751. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, parsedGeometry.uvs6._updatable);
  39752. }
  39753. if (parsedGeometry.colors) {
  39754. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, BABYLON.Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), parsedGeometry.colors._updatable);
  39755. }
  39756. if (parsedGeometry.matricesIndices) {
  39757. if (!parsedGeometry.matricesIndices._isExpanded) {
  39758. var floatIndices = [];
  39759. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  39760. var matricesIndex = parsedGeometry.matricesIndices[i];
  39761. floatIndices.push(matricesIndex & 0x000000FF);
  39762. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  39763. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  39764. floatIndices.push(matricesIndex >> 24);
  39765. }
  39766. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, parsedGeometry.matricesIndices._updatable);
  39767. }
  39768. else {
  39769. delete parsedGeometry.matricesIndices._isExpanded;
  39770. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, parsedGeometry.matricesIndices._updatable);
  39771. }
  39772. }
  39773. if (parsedGeometry.matricesIndicesExtra) {
  39774. if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
  39775. var floatIndices = [];
  39776. for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
  39777. var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
  39778. floatIndices.push(matricesIndex & 0x000000FF);
  39779. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  39780. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  39781. floatIndices.push(matricesIndex >> 24);
  39782. }
  39783. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, parsedGeometry.matricesIndicesExtra._updatable);
  39784. }
  39785. else {
  39786. delete parsedGeometry.matricesIndices._isExpanded;
  39787. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, parsedGeometry.matricesIndicesExtra._updatable);
  39788. }
  39789. }
  39790. if (parsedGeometry.matricesWeights) {
  39791. Geometry._CleanMatricesWeights(parsedGeometry, mesh);
  39792. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, parsedGeometry.matricesWeights._updatable);
  39793. }
  39794. if (parsedGeometry.matricesWeightsExtra) {
  39795. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, parsedGeometry.matricesWeights._updatable);
  39796. }
  39797. mesh.setIndices(parsedGeometry.indices, null);
  39798. }
  39799. // SubMeshes
  39800. if (parsedGeometry.subMeshes) {
  39801. mesh.subMeshes = [];
  39802. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  39803. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  39804. BABYLON.SubMesh.AddToMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  39805. }
  39806. }
  39807. // Flat shading
  39808. if (mesh._shouldGenerateFlatShading) {
  39809. mesh.convertToFlatShadedMesh();
  39810. delete mesh._shouldGenerateFlatShading;
  39811. }
  39812. // Update
  39813. mesh.computeWorldMatrix(true);
  39814. // Octree
  39815. var sceneOctree = scene.selectionOctree;
  39816. if (sceneOctree !== undefined && sceneOctree !== null) {
  39817. sceneOctree.addMesh(mesh);
  39818. }
  39819. };
  39820. Geometry._CleanMatricesWeights = function (parsedGeometry, mesh) {
  39821. var epsilon = 1e-3;
  39822. if (!BABYLON.SceneLoader.CleanBoneMatrixWeights) {
  39823. return;
  39824. }
  39825. var noInfluenceBoneIndex = 0.0;
  39826. if (parsedGeometry.skeletonId > -1) {
  39827. var skeleton = mesh.getScene().getLastSkeletonByID(parsedGeometry.skeletonId);
  39828. if (!skeleton) {
  39829. return;
  39830. }
  39831. noInfluenceBoneIndex = skeleton.bones.length;
  39832. }
  39833. else {
  39834. return;
  39835. }
  39836. var matricesIndices = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  39837. var matricesIndicesExtra = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  39838. var matricesWeights = parsedGeometry.matricesWeights;
  39839. var matricesWeightsExtra = parsedGeometry.matricesWeightsExtra;
  39840. var influencers = parsedGeometry.numBoneInfluencer;
  39841. var size = matricesWeights.length;
  39842. for (var i = 0; i < size; i += 4) {
  39843. var weight = 0.0;
  39844. var firstZeroWeight = -1;
  39845. for (var j = 0; j < 4; j++) {
  39846. var w = matricesWeights[i + j];
  39847. weight += w;
  39848. if (w < epsilon && firstZeroWeight < 0) {
  39849. firstZeroWeight = j;
  39850. }
  39851. }
  39852. if (matricesWeightsExtra) {
  39853. for (var j = 0; j < 4; j++) {
  39854. var w = matricesWeightsExtra[i + j];
  39855. weight += w;
  39856. if (w < epsilon && firstZeroWeight < 0) {
  39857. firstZeroWeight = j + 4;
  39858. }
  39859. }
  39860. }
  39861. if (firstZeroWeight < 0 || firstZeroWeight > (influencers - 1)) {
  39862. firstZeroWeight = influencers - 1;
  39863. }
  39864. if (weight > epsilon) {
  39865. var mweight = 1.0 / weight;
  39866. for (var j = 0; j < 4; j++) {
  39867. matricesWeights[i + j] *= mweight;
  39868. }
  39869. if (matricesWeightsExtra) {
  39870. for (var j = 0; j < 4; j++) {
  39871. matricesWeightsExtra[i + j] *= mweight;
  39872. }
  39873. }
  39874. }
  39875. else {
  39876. if (firstZeroWeight >= 4) {
  39877. matricesWeightsExtra[i + firstZeroWeight - 4] = 1.0 - weight;
  39878. matricesIndicesExtra[i + firstZeroWeight - 4] = noInfluenceBoneIndex;
  39879. }
  39880. else {
  39881. matricesWeights[i + firstZeroWeight] = 1.0 - weight;
  39882. matricesIndices[i + firstZeroWeight] = noInfluenceBoneIndex;
  39883. }
  39884. }
  39885. }
  39886. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndices);
  39887. if (parsedGeometry.matricesWeightsExtra) {
  39888. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, matricesIndicesExtra);
  39889. }
  39890. };
  39891. /**
  39892. * Create a new geometry from persisted data (Using .babylon file format)
  39893. * @param parsedVertexData defines the persisted data
  39894. * @param scene defines the hosting scene
  39895. * @param rootUrl defines the root url to use to load assets (like delayed data)
  39896. * @returns the new geometry object
  39897. */
  39898. Geometry.Parse = function (parsedVertexData, scene, rootUrl) {
  39899. if (scene.getGeometryByID(parsedVertexData.id)) {
  39900. return null; // null since geometry could be something else than a box...
  39901. }
  39902. var geometry = new Geometry(parsedVertexData.id, scene, undefined, parsedVertexData.updatable);
  39903. if (BABYLON.Tags) {
  39904. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  39905. }
  39906. if (parsedVertexData.delayLoadingFile) {
  39907. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  39908. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  39909. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  39910. geometry._delayInfo = [];
  39911. if (parsedVertexData.hasUVs) {
  39912. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  39913. }
  39914. if (parsedVertexData.hasUVs2) {
  39915. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  39916. }
  39917. if (parsedVertexData.hasUVs3) {
  39918. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  39919. }
  39920. if (parsedVertexData.hasUVs4) {
  39921. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  39922. }
  39923. if (parsedVertexData.hasUVs5) {
  39924. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  39925. }
  39926. if (parsedVertexData.hasUVs6) {
  39927. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  39928. }
  39929. if (parsedVertexData.hasColors) {
  39930. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  39931. }
  39932. if (parsedVertexData.hasMatricesIndices) {
  39933. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  39934. }
  39935. if (parsedVertexData.hasMatricesWeights) {
  39936. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  39937. }
  39938. geometry._delayLoadingFunction = BABYLON.VertexData.ImportVertexData;
  39939. }
  39940. else {
  39941. BABYLON.VertexData.ImportVertexData(parsedVertexData, geometry);
  39942. }
  39943. scene.pushGeometry(geometry, true);
  39944. return geometry;
  39945. };
  39946. return Geometry;
  39947. }());
  39948. BABYLON.Geometry = Geometry;
  39949. // Primitives
  39950. /// Abstract class
  39951. /**
  39952. * Abstract class used to provide common services for all typed geometries
  39953. * @hidden
  39954. */
  39955. var _PrimitiveGeometry = /** @class */ (function (_super) {
  39956. __extends(_PrimitiveGeometry, _super);
  39957. /**
  39958. * Creates a new typed geometry
  39959. * @param id defines the unique ID of the geometry
  39960. * @param scene defines the hosting scene
  39961. * @param _canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  39962. * @param mesh defines the hosting mesh (can be null)
  39963. */
  39964. function _PrimitiveGeometry(id, scene, _canBeRegenerated, mesh) {
  39965. if (_canBeRegenerated === void 0) { _canBeRegenerated = false; }
  39966. if (mesh === void 0) { mesh = null; }
  39967. var _this = _super.call(this, id, scene, undefined, false, mesh) || this;
  39968. _this._canBeRegenerated = _canBeRegenerated;
  39969. _this._beingRegenerated = true;
  39970. _this.regenerate();
  39971. _this._beingRegenerated = false;
  39972. return _this;
  39973. }
  39974. /**
  39975. * Gets a value indicating if the geometry supports being regenerated with new parameters (false by default)
  39976. * @returns true if the geometry can be regenerated
  39977. */
  39978. _PrimitiveGeometry.prototype.canBeRegenerated = function () {
  39979. return this._canBeRegenerated;
  39980. };
  39981. /**
  39982. * If the geometry supports regeneration, the function will recreates the geometry with updated parameter values
  39983. */
  39984. _PrimitiveGeometry.prototype.regenerate = function () {
  39985. if (!this._canBeRegenerated) {
  39986. return;
  39987. }
  39988. this._beingRegenerated = true;
  39989. this.setAllVerticesData(this._regenerateVertexData(), false);
  39990. this._beingRegenerated = false;
  39991. };
  39992. /**
  39993. * Clone the geometry
  39994. * @param id defines the unique ID of the new geometry
  39995. * @returns the new geometry
  39996. */
  39997. _PrimitiveGeometry.prototype.asNewGeometry = function (id) {
  39998. return _super.prototype.copy.call(this, id);
  39999. };
  40000. // overrides
  40001. _PrimitiveGeometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  40002. if (!this._beingRegenerated) {
  40003. return;
  40004. }
  40005. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  40006. };
  40007. _PrimitiveGeometry.prototype.setVerticesData = function (kind, data, updatable) {
  40008. if (!this._beingRegenerated) {
  40009. return;
  40010. }
  40011. _super.prototype.setVerticesData.call(this, kind, data, false);
  40012. };
  40013. // to override
  40014. /** @hidden */
  40015. _PrimitiveGeometry.prototype._regenerateVertexData = function () {
  40016. throw new Error("Abstract method");
  40017. };
  40018. _PrimitiveGeometry.prototype.copy = function (id) {
  40019. throw new Error("Must be overriden in sub-classes.");
  40020. };
  40021. _PrimitiveGeometry.prototype.serialize = function () {
  40022. var serializationObject = _super.prototype.serialize.call(this);
  40023. serializationObject.canBeRegenerated = this.canBeRegenerated();
  40024. return serializationObject;
  40025. };
  40026. return _PrimitiveGeometry;
  40027. }(Geometry));
  40028. BABYLON._PrimitiveGeometry = _PrimitiveGeometry;
  40029. /**
  40030. * Creates a ribbon geometry
  40031. * @description See http://doc.babylonjs.com/how_to/ribbon_tutorial, http://doc.babylonjs.com/resources/maths_make_ribbons
  40032. */
  40033. var RibbonGeometry = /** @class */ (function (_super) {
  40034. __extends(RibbonGeometry, _super);
  40035. /**
  40036. * Creates a ribbon geometry
  40037. * @param id defines the unique ID of the geometry
  40038. * @param scene defines the hosting scene
  40039. * @param pathArray defines the array of paths to use
  40040. * @param closeArray defines if the last path and the first path must be joined
  40041. * @param closePath defines if the last and first points of each path in your pathArray must be joined
  40042. * @param offset defines the offset between points
  40043. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40044. * @param mesh defines the hosting mesh (can be null)
  40045. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40046. */
  40047. function RibbonGeometry(id, scene,
  40048. /**
  40049. * Defines the array of paths to use
  40050. */
  40051. pathArray,
  40052. /**
  40053. * Defines if the last and first points of each path in your pathArray must be joined
  40054. */
  40055. closeArray,
  40056. /**
  40057. * Defines if the last and first points of each path in your pathArray must be joined
  40058. */
  40059. closePath,
  40060. /**
  40061. * Defines the offset between points
  40062. */
  40063. offset, canBeRegenerated, mesh,
  40064. /**
  40065. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40066. */
  40067. side) {
  40068. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40069. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40070. _this.pathArray = pathArray;
  40071. _this.closeArray = closeArray;
  40072. _this.closePath = closePath;
  40073. _this.offset = offset;
  40074. _this.side = side;
  40075. return _this;
  40076. }
  40077. /** @hidden */
  40078. RibbonGeometry.prototype._regenerateVertexData = function () {
  40079. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  40080. };
  40081. RibbonGeometry.prototype.copy = function (id) {
  40082. return new RibbonGeometry(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), undefined, this.side);
  40083. };
  40084. return RibbonGeometry;
  40085. }(_PrimitiveGeometry));
  40086. BABYLON.RibbonGeometry = RibbonGeometry;
  40087. /**
  40088. * Creates a box geometry
  40089. * @description see http://doc.babylonjs.com/how_to/set_shapes#box
  40090. */
  40091. var BoxGeometry = /** @class */ (function (_super) {
  40092. __extends(BoxGeometry, _super);
  40093. /**
  40094. * Creates a box geometry
  40095. * @param id defines the unique ID of the geometry
  40096. * @param scene defines the hosting scene
  40097. * @param size defines the zise of the box (width, height and depth are the same)
  40098. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40099. * @param mesh defines the hosting mesh (can be null)
  40100. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40101. */
  40102. function BoxGeometry(id, scene,
  40103. /**
  40104. * Defines the zise of the box (width, height and depth are the same)
  40105. */
  40106. size, canBeRegenerated, mesh,
  40107. /**
  40108. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40109. */
  40110. side) {
  40111. if (mesh === void 0) { mesh = null; }
  40112. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40113. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40114. _this.size = size;
  40115. _this.side = side;
  40116. return _this;
  40117. }
  40118. BoxGeometry.prototype._regenerateVertexData = function () {
  40119. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  40120. };
  40121. BoxGeometry.prototype.copy = function (id) {
  40122. return new BoxGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), undefined, this.side);
  40123. };
  40124. BoxGeometry.prototype.serialize = function () {
  40125. var serializationObject = _super.prototype.serialize.call(this);
  40126. serializationObject.size = this.size;
  40127. return serializationObject;
  40128. };
  40129. BoxGeometry.Parse = function (parsedBox, scene) {
  40130. if (scene.getGeometryByID(parsedBox.id)) {
  40131. return null; // null since geometry could be something else than a box...
  40132. }
  40133. var box = new BoxGeometry(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  40134. if (BABYLON.Tags) {
  40135. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  40136. }
  40137. scene.pushGeometry(box, true);
  40138. return box;
  40139. };
  40140. return BoxGeometry;
  40141. }(_PrimitiveGeometry));
  40142. BABYLON.BoxGeometry = BoxGeometry;
  40143. /**
  40144. * Creates a sphere geometry
  40145. * @description see http://doc.babylonjs.com/how_to/set_shapes#sphere
  40146. */
  40147. var SphereGeometry = /** @class */ (function (_super) {
  40148. __extends(SphereGeometry, _super);
  40149. /**
  40150. * Create a new sphere geometry
  40151. * @param id defines the unique ID of the geometry
  40152. * @param scene defines the hosting scene
  40153. * @param segments defines the number of segments to use to create the sphere
  40154. * @param diameter defines the diameter of the sphere
  40155. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40156. * @param mesh defines the hosting mesh (can be null)
  40157. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40158. */
  40159. function SphereGeometry(id, scene,
  40160. /**
  40161. * Defines the number of segments to use to create the sphere
  40162. */
  40163. segments,
  40164. /**
  40165. * Defines the diameter of the sphere
  40166. */
  40167. diameter, canBeRegenerated, mesh,
  40168. /**
  40169. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40170. */
  40171. side) {
  40172. if (mesh === void 0) { mesh = null; }
  40173. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40174. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40175. _this.segments = segments;
  40176. _this.diameter = diameter;
  40177. _this.side = side;
  40178. return _this;
  40179. }
  40180. SphereGeometry.prototype._regenerateVertexData = function () {
  40181. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  40182. };
  40183. SphereGeometry.prototype.copy = function (id) {
  40184. return new SphereGeometry(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  40185. };
  40186. SphereGeometry.prototype.serialize = function () {
  40187. var serializationObject = _super.prototype.serialize.call(this);
  40188. serializationObject.segments = this.segments;
  40189. serializationObject.diameter = this.diameter;
  40190. return serializationObject;
  40191. };
  40192. SphereGeometry.Parse = function (parsedSphere, scene) {
  40193. if (scene.getGeometryByID(parsedSphere.id)) {
  40194. return null; // null since geometry could be something else than a sphere...
  40195. }
  40196. var sphere = new SphereGeometry(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  40197. if (BABYLON.Tags) {
  40198. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  40199. }
  40200. scene.pushGeometry(sphere, true);
  40201. return sphere;
  40202. };
  40203. return SphereGeometry;
  40204. }(_PrimitiveGeometry));
  40205. BABYLON.SphereGeometry = SphereGeometry;
  40206. /**
  40207. * Creates a disc geometry
  40208. * @description see http://doc.babylonjs.com/how_to/set_shapes#disc-or-regular-polygon
  40209. */
  40210. var DiscGeometry = /** @class */ (function (_super) {
  40211. __extends(DiscGeometry, _super);
  40212. /**
  40213. * Creates a new disc geometry
  40214. * @param id defines the unique ID of the geometry
  40215. * @param scene defines the hosting scene
  40216. * @param radius defines the radius of the disc
  40217. * @param tessellation defines the tesselation factor to apply to the disc
  40218. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40219. * @param mesh defines the hosting mesh (can be null)
  40220. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40221. */
  40222. function DiscGeometry(id, scene,
  40223. /**
  40224. * Defines the radius of the disc
  40225. */
  40226. radius,
  40227. /**
  40228. * Defines the tesselation factor to apply to the disc
  40229. */
  40230. tessellation, canBeRegenerated, mesh,
  40231. /**
  40232. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40233. */
  40234. side) {
  40235. if (mesh === void 0) { mesh = null; }
  40236. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40237. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40238. _this.radius = radius;
  40239. _this.tessellation = tessellation;
  40240. _this.side = side;
  40241. return _this;
  40242. }
  40243. DiscGeometry.prototype._regenerateVertexData = function () {
  40244. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  40245. };
  40246. DiscGeometry.prototype.copy = function (id) {
  40247. return new DiscGeometry(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  40248. };
  40249. return DiscGeometry;
  40250. }(_PrimitiveGeometry));
  40251. BABYLON.DiscGeometry = DiscGeometry;
  40252. /**
  40253. * Creates a new cylinder geometry
  40254. * @description see http://doc.babylonjs.com/how_to/set_shapes#cylinder-or-cone
  40255. */
  40256. var CylinderGeometry = /** @class */ (function (_super) {
  40257. __extends(CylinderGeometry, _super);
  40258. /**
  40259. * Creates a new cylinder geometry
  40260. * @param id defines the unique ID of the geometry
  40261. * @param scene defines the hosting scene
  40262. * @param height defines the height of the cylinder
  40263. * @param diameterTop defines the diameter of the cylinder's top cap
  40264. * @param diameterBottom defines the diameter of the cylinder's bottom cap
  40265. * @param tessellation defines the tessellation factor to apply to the cylinder (number of radial sides)
  40266. * @param subdivisions defines the number of subdivisions to apply to the cylinder (number of rings) (1 by default)
  40267. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40268. * @param mesh defines the hosting mesh (can be null)
  40269. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40270. */
  40271. function CylinderGeometry(id, scene,
  40272. /**
  40273. * Defines the height of the cylinder
  40274. */
  40275. height,
  40276. /**
  40277. * Defines the diameter of the cylinder's top cap
  40278. */
  40279. diameterTop,
  40280. /**
  40281. * Defines the diameter of the cylinder's bottom cap
  40282. */
  40283. diameterBottom,
  40284. /**
  40285. * Defines the tessellation factor to apply to the cylinder
  40286. */
  40287. tessellation,
  40288. /**
  40289. * Defines the number of subdivisions to apply to the cylinder (1 by default)
  40290. */
  40291. subdivisions, canBeRegenerated, mesh,
  40292. /**
  40293. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40294. */
  40295. side) {
  40296. if (subdivisions === void 0) { subdivisions = 1; }
  40297. if (mesh === void 0) { mesh = null; }
  40298. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40299. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40300. _this.height = height;
  40301. _this.diameterTop = diameterTop;
  40302. _this.diameterBottom = diameterBottom;
  40303. _this.tessellation = tessellation;
  40304. _this.subdivisions = subdivisions;
  40305. _this.side = side;
  40306. return _this;
  40307. }
  40308. CylinderGeometry.prototype._regenerateVertexData = function () {
  40309. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  40310. };
  40311. CylinderGeometry.prototype.copy = function (id) {
  40312. return new CylinderGeometry(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  40313. };
  40314. CylinderGeometry.prototype.serialize = function () {
  40315. var serializationObject = _super.prototype.serialize.call(this);
  40316. serializationObject.height = this.height;
  40317. serializationObject.diameterTop = this.diameterTop;
  40318. serializationObject.diameterBottom = this.diameterBottom;
  40319. serializationObject.tessellation = this.tessellation;
  40320. return serializationObject;
  40321. };
  40322. CylinderGeometry.Parse = function (parsedCylinder, scene) {
  40323. if (scene.getGeometryByID(parsedCylinder.id)) {
  40324. return null; // null since geometry could be something else than a cylinder...
  40325. }
  40326. var cylinder = new CylinderGeometry(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  40327. if (BABYLON.Tags) {
  40328. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  40329. }
  40330. scene.pushGeometry(cylinder, true);
  40331. return cylinder;
  40332. };
  40333. return CylinderGeometry;
  40334. }(_PrimitiveGeometry));
  40335. BABYLON.CylinderGeometry = CylinderGeometry;
  40336. /**
  40337. * Creates a new torus geometry
  40338. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus
  40339. */
  40340. var TorusGeometry = /** @class */ (function (_super) {
  40341. __extends(TorusGeometry, _super);
  40342. /**
  40343. * Creates a new torus geometry
  40344. * @param id defines the unique ID of the geometry
  40345. * @param scene defines the hosting scene
  40346. * @param diameter defines the diameter of the torus
  40347. * @param thickness defines the thickness of the torus (ie. internal diameter)
  40348. * @param tessellation defines the tesselation factor to apply to the torus (number of segments along the circle)
  40349. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40350. * @param mesh defines the hosting mesh (can be null)
  40351. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40352. */
  40353. function TorusGeometry(id, scene,
  40354. /**
  40355. * Defines the diameter of the torus
  40356. */
  40357. diameter,
  40358. /**
  40359. * Defines the thickness of the torus (ie. internal diameter)
  40360. */
  40361. thickness,
  40362. /**
  40363. * Defines the tesselation factor to apply to the torus
  40364. */
  40365. tessellation, canBeRegenerated, mesh,
  40366. /**
  40367. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40368. */
  40369. side) {
  40370. if (mesh === void 0) { mesh = null; }
  40371. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40372. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40373. _this.diameter = diameter;
  40374. _this.thickness = thickness;
  40375. _this.tessellation = tessellation;
  40376. _this.side = side;
  40377. return _this;
  40378. }
  40379. TorusGeometry.prototype._regenerateVertexData = function () {
  40380. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  40381. };
  40382. TorusGeometry.prototype.copy = function (id) {
  40383. return new TorusGeometry(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  40384. };
  40385. TorusGeometry.prototype.serialize = function () {
  40386. var serializationObject = _super.prototype.serialize.call(this);
  40387. serializationObject.diameter = this.diameter;
  40388. serializationObject.thickness = this.thickness;
  40389. serializationObject.tessellation = this.tessellation;
  40390. return serializationObject;
  40391. };
  40392. TorusGeometry.Parse = function (parsedTorus, scene) {
  40393. if (scene.getGeometryByID(parsedTorus.id)) {
  40394. return null; // null since geometry could be something else than a torus...
  40395. }
  40396. var torus = new TorusGeometry(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  40397. if (BABYLON.Tags) {
  40398. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  40399. }
  40400. scene.pushGeometry(torus, true);
  40401. return torus;
  40402. };
  40403. return TorusGeometry;
  40404. }(_PrimitiveGeometry));
  40405. BABYLON.TorusGeometry = TorusGeometry;
  40406. /**
  40407. * Creates a new ground geometry
  40408. * @description see http://doc.babylonjs.com/how_to/set_shapes#ground
  40409. */
  40410. var GroundGeometry = /** @class */ (function (_super) {
  40411. __extends(GroundGeometry, _super);
  40412. /**
  40413. * Creates a new ground geometry
  40414. * @param id defines the unique ID of the geometry
  40415. * @param scene defines the hosting scene
  40416. * @param width defines the width of the ground
  40417. * @param height defines the height of the ground
  40418. * @param subdivisions defines the subdivisions to apply to the ground
  40419. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40420. * @param mesh defines the hosting mesh (can be null)
  40421. */
  40422. function GroundGeometry(id, scene,
  40423. /**
  40424. * Defines the width of the ground
  40425. */
  40426. width,
  40427. /**
  40428. * Defines the height of the ground
  40429. */
  40430. height,
  40431. /**
  40432. * Defines the subdivisions to apply to the ground
  40433. */
  40434. subdivisions, canBeRegenerated, mesh) {
  40435. if (mesh === void 0) { mesh = null; }
  40436. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40437. _this.width = width;
  40438. _this.height = height;
  40439. _this.subdivisions = subdivisions;
  40440. return _this;
  40441. }
  40442. GroundGeometry.prototype._regenerateVertexData = function () {
  40443. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  40444. };
  40445. GroundGeometry.prototype.copy = function (id) {
  40446. return new GroundGeometry(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  40447. };
  40448. GroundGeometry.prototype.serialize = function () {
  40449. var serializationObject = _super.prototype.serialize.call(this);
  40450. serializationObject.width = this.width;
  40451. serializationObject.height = this.height;
  40452. serializationObject.subdivisions = this.subdivisions;
  40453. return serializationObject;
  40454. };
  40455. GroundGeometry.Parse = function (parsedGround, scene) {
  40456. if (scene.getGeometryByID(parsedGround.id)) {
  40457. return null; // null since geometry could be something else than a ground...
  40458. }
  40459. var ground = new GroundGeometry(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  40460. if (BABYLON.Tags) {
  40461. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  40462. }
  40463. scene.pushGeometry(ground, true);
  40464. return ground;
  40465. };
  40466. return GroundGeometry;
  40467. }(_PrimitiveGeometry));
  40468. BABYLON.GroundGeometry = GroundGeometry;
  40469. /**
  40470. * Creates a tiled ground geometry
  40471. * @description see http://doc.babylonjs.com/how_to/set_shapes#tiled-ground
  40472. */
  40473. var TiledGroundGeometry = /** @class */ (function (_super) {
  40474. __extends(TiledGroundGeometry, _super);
  40475. /**
  40476. * Creates a tiled ground geometry
  40477. * @param id defines the unique ID of the geometry
  40478. * @param scene defines the hosting scene
  40479. * @param xmin defines the minimum value on X axis
  40480. * @param zmin defines the minimum value on Z axis
  40481. * @param xmax defines the maximum value on X axis
  40482. * @param zmax defines the maximum value on Z axis
  40483. * @param subdivisions defines the subdivisions to apply to the ground (number of subdivisions (tiles) on the height and the width of the map)
  40484. * @param precision defines the precision to use when computing the tiles
  40485. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40486. * @param mesh defines the hosting mesh (can be null)
  40487. */
  40488. function TiledGroundGeometry(id, scene,
  40489. /**
  40490. * Defines the minimum value on X axis
  40491. */
  40492. xmin,
  40493. /**
  40494. * Defines the minimum value on Z axis
  40495. */
  40496. zmin,
  40497. /**
  40498. * Defines the maximum value on X axis
  40499. */
  40500. xmax,
  40501. /**
  40502. * Defines the maximum value on Z axis
  40503. */
  40504. zmax,
  40505. /**
  40506. * Defines the subdivisions to apply to the ground
  40507. */
  40508. subdivisions,
  40509. /**
  40510. * Defines the precision to use when computing the tiles
  40511. */
  40512. precision, canBeRegenerated, mesh) {
  40513. if (mesh === void 0) { mesh = null; }
  40514. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40515. _this.xmin = xmin;
  40516. _this.zmin = zmin;
  40517. _this.xmax = xmax;
  40518. _this.zmax = zmax;
  40519. _this.subdivisions = subdivisions;
  40520. _this.precision = precision;
  40521. return _this;
  40522. }
  40523. TiledGroundGeometry.prototype._regenerateVertexData = function () {
  40524. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  40525. };
  40526. TiledGroundGeometry.prototype.copy = function (id) {
  40527. return new TiledGroundGeometry(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  40528. };
  40529. return TiledGroundGeometry;
  40530. }(_PrimitiveGeometry));
  40531. BABYLON.TiledGroundGeometry = TiledGroundGeometry;
  40532. /**
  40533. * Creates a plane geometry
  40534. * @description see http://doc.babylonjs.com/how_to/set_shapes#plane
  40535. */
  40536. var PlaneGeometry = /** @class */ (function (_super) {
  40537. __extends(PlaneGeometry, _super);
  40538. /**
  40539. * Creates a plane geometry
  40540. * @param id defines the unique ID of the geometry
  40541. * @param scene defines the hosting scene
  40542. * @param size defines the size of the plane (width === height)
  40543. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40544. * @param mesh defines the hosting mesh (can be null)
  40545. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40546. */
  40547. function PlaneGeometry(id, scene,
  40548. /**
  40549. * Defines the size of the plane (width === height)
  40550. */
  40551. size, canBeRegenerated, mesh,
  40552. /**
  40553. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40554. */
  40555. side) {
  40556. if (mesh === void 0) { mesh = null; }
  40557. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40558. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40559. _this.size = size;
  40560. _this.side = side;
  40561. return _this;
  40562. }
  40563. PlaneGeometry.prototype._regenerateVertexData = function () {
  40564. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  40565. };
  40566. PlaneGeometry.prototype.copy = function (id) {
  40567. return new PlaneGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  40568. };
  40569. PlaneGeometry.prototype.serialize = function () {
  40570. var serializationObject = _super.prototype.serialize.call(this);
  40571. serializationObject.size = this.size;
  40572. return serializationObject;
  40573. };
  40574. PlaneGeometry.Parse = function (parsedPlane, scene) {
  40575. if (scene.getGeometryByID(parsedPlane.id)) {
  40576. return null; // null since geometry could be something else than a ground...
  40577. }
  40578. var plane = new PlaneGeometry(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  40579. if (BABYLON.Tags) {
  40580. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  40581. }
  40582. scene.pushGeometry(plane, true);
  40583. return plane;
  40584. };
  40585. return PlaneGeometry;
  40586. }(_PrimitiveGeometry));
  40587. BABYLON.PlaneGeometry = PlaneGeometry;
  40588. /**
  40589. * Creates a torus knot geometry
  40590. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus-knot
  40591. */
  40592. var TorusKnotGeometry = /** @class */ (function (_super) {
  40593. __extends(TorusKnotGeometry, _super);
  40594. /**
  40595. * Creates a torus knot geometry
  40596. * @param id defines the unique ID of the geometry
  40597. * @param scene defines the hosting scene
  40598. * @param radius defines the radius of the torus knot
  40599. * @param tube defines the thickness of the torus knot tube
  40600. * @param radialSegments defines the number of radial segments
  40601. * @param tubularSegments defines the number of tubular segments
  40602. * @param p defines the first number of windings
  40603. * @param q defines the second number of windings
  40604. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40605. * @param mesh defines the hosting mesh (can be null)
  40606. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40607. */
  40608. function TorusKnotGeometry(id, scene,
  40609. /**
  40610. * Defines the radius of the torus knot
  40611. */
  40612. radius,
  40613. /**
  40614. * Defines the thickness of the torus knot tube
  40615. */
  40616. tube,
  40617. /**
  40618. * Defines the number of radial segments
  40619. */
  40620. radialSegments,
  40621. /**
  40622. * Defines the number of tubular segments
  40623. */
  40624. tubularSegments,
  40625. /**
  40626. * Defines the first number of windings
  40627. */
  40628. p,
  40629. /**
  40630. * Defines the second number of windings
  40631. */
  40632. q, canBeRegenerated, mesh,
  40633. /**
  40634. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40635. */
  40636. side) {
  40637. if (mesh === void 0) { mesh = null; }
  40638. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40639. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40640. _this.radius = radius;
  40641. _this.tube = tube;
  40642. _this.radialSegments = radialSegments;
  40643. _this.tubularSegments = tubularSegments;
  40644. _this.p = p;
  40645. _this.q = q;
  40646. _this.side = side;
  40647. return _this;
  40648. }
  40649. TorusKnotGeometry.prototype._regenerateVertexData = function () {
  40650. 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 });
  40651. };
  40652. TorusKnotGeometry.prototype.copy = function (id) {
  40653. return new TorusKnotGeometry(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  40654. };
  40655. TorusKnotGeometry.prototype.serialize = function () {
  40656. var serializationObject = _super.prototype.serialize.call(this);
  40657. serializationObject.radius = this.radius;
  40658. serializationObject.tube = this.tube;
  40659. serializationObject.radialSegments = this.radialSegments;
  40660. serializationObject.tubularSegments = this.tubularSegments;
  40661. serializationObject.p = this.p;
  40662. serializationObject.q = this.q;
  40663. return serializationObject;
  40664. };
  40665. ;
  40666. TorusKnotGeometry.Parse = function (parsedTorusKnot, scene) {
  40667. if (scene.getGeometryByID(parsedTorusKnot.id)) {
  40668. return null; // null since geometry could be something else than a ground...
  40669. }
  40670. var torusKnot = new TorusKnotGeometry(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
  40671. if (BABYLON.Tags) {
  40672. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  40673. }
  40674. scene.pushGeometry(torusKnot, true);
  40675. return torusKnot;
  40676. };
  40677. return TorusKnotGeometry;
  40678. }(_PrimitiveGeometry));
  40679. BABYLON.TorusKnotGeometry = TorusKnotGeometry;
  40680. //}
  40681. })(BABYLON || (BABYLON = {}));
  40682. //# sourceMappingURL=babylon.geometry.js.map
  40683. var BABYLON;
  40684. (function (BABYLON) {
  40685. /**
  40686. * PostProcessManager is used to manage one or more post processes or post process pipelines
  40687. * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  40688. */
  40689. var PostProcessManager = /** @class */ (function () {
  40690. /**
  40691. * Creates a new instance PostProcess
  40692. * @param scene The scene that the post process is associated with.
  40693. */
  40694. function PostProcessManager(scene) {
  40695. this._vertexBuffers = {};
  40696. this._scene = scene;
  40697. }
  40698. PostProcessManager.prototype._prepareBuffers = function () {
  40699. if (this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]) {
  40700. return;
  40701. }
  40702. // VBO
  40703. var vertices = [];
  40704. vertices.push(1, 1);
  40705. vertices.push(-1, 1);
  40706. vertices.push(-1, -1);
  40707. vertices.push(1, -1);
  40708. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(this._scene.getEngine(), vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  40709. this._buildIndexBuffer();
  40710. };
  40711. PostProcessManager.prototype._buildIndexBuffer = function () {
  40712. // Indices
  40713. var indices = [];
  40714. indices.push(0);
  40715. indices.push(1);
  40716. indices.push(2);
  40717. indices.push(0);
  40718. indices.push(2);
  40719. indices.push(3);
  40720. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  40721. };
  40722. /**
  40723. * Rebuilds the vertex buffers of the manager.
  40724. */
  40725. PostProcessManager.prototype._rebuild = function () {
  40726. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  40727. if (!vb) {
  40728. return;
  40729. }
  40730. vb._rebuild();
  40731. this._buildIndexBuffer();
  40732. };
  40733. // Methods
  40734. /**
  40735. * Prepares a frame to be run through a post process.
  40736. * @param sourceTexture The input texture to the post procesess. (default: null)
  40737. * @param postProcesses An array of post processes to be run. (default: null)
  40738. * @returns True if the post processes were able to be run.
  40739. */
  40740. PostProcessManager.prototype._prepareFrame = function (sourceTexture, postProcesses) {
  40741. if (sourceTexture === void 0) { sourceTexture = null; }
  40742. if (postProcesses === void 0) { postProcesses = null; }
  40743. var camera = this._scene.activeCamera;
  40744. if (!camera) {
  40745. return false;
  40746. }
  40747. var postProcesses = postProcesses || camera._postProcesses.filter(function (pp) { return pp != null; });
  40748. if (!postProcesses || postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  40749. return false;
  40750. }
  40751. postProcesses[0].activate(camera, sourceTexture, postProcesses !== null && postProcesses !== undefined);
  40752. return true;
  40753. };
  40754. /**
  40755. * Manually render a set of post processes to a texture.
  40756. * @param postProcesses An array of post processes to be run.
  40757. * @param targetTexture The target texture to render to.
  40758. * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight
  40759. */
  40760. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture, forceFullscreenViewport) {
  40761. if (targetTexture === void 0) { targetTexture = null; }
  40762. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  40763. var engine = this._scene.getEngine();
  40764. for (var index = 0; index < postProcesses.length; index++) {
  40765. if (index < postProcesses.length - 1) {
  40766. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  40767. }
  40768. else {
  40769. if (targetTexture) {
  40770. engine.bindFramebuffer(targetTexture, 0, undefined, undefined, forceFullscreenViewport);
  40771. }
  40772. else {
  40773. engine.restoreDefaultFramebuffer();
  40774. }
  40775. }
  40776. var pp = postProcesses[index];
  40777. var effect = pp.apply();
  40778. if (effect) {
  40779. pp.onBeforeRenderObservable.notifyObservers(effect);
  40780. // VBOs
  40781. this._prepareBuffers();
  40782. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  40783. // Draw order
  40784. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  40785. pp.onAfterRenderObservable.notifyObservers(effect);
  40786. }
  40787. }
  40788. // Restore depth buffer
  40789. engine.setDepthBuffer(true);
  40790. engine.setDepthWrite(true);
  40791. };
  40792. /**
  40793. * Finalize the result of the output of the postprocesses.
  40794. * @param doNotPresent If true the result will not be displayed to the screen.
  40795. * @param targetTexture The target texture to render to.
  40796. * @param faceIndex The index of the face to bind the target texture to.
  40797. * @param postProcesses The array of post processes to render.
  40798. * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight (default: false)
  40799. */
  40800. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses, forceFullscreenViewport) {
  40801. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  40802. var camera = this._scene.activeCamera;
  40803. if (!camera) {
  40804. return;
  40805. }
  40806. postProcesses = postProcesses || camera._postProcesses.filter(function (pp) { return pp != null; });
  40807. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  40808. return;
  40809. }
  40810. var engine = this._scene.getEngine();
  40811. for (var index = 0, len = postProcesses.length; index < len; index++) {
  40812. var pp = postProcesses[index];
  40813. if (index < len - 1) {
  40814. pp._outputTexture = postProcesses[index + 1].activate(camera, targetTexture);
  40815. }
  40816. else {
  40817. if (targetTexture) {
  40818. engine.bindFramebuffer(targetTexture, faceIndex, undefined, undefined, forceFullscreenViewport);
  40819. pp._outputTexture = targetTexture;
  40820. }
  40821. else {
  40822. engine.restoreDefaultFramebuffer();
  40823. pp._outputTexture = null;
  40824. }
  40825. }
  40826. if (doNotPresent) {
  40827. break;
  40828. }
  40829. var effect = pp.apply();
  40830. if (effect) {
  40831. pp.onBeforeRenderObservable.notifyObservers(effect);
  40832. // VBOs
  40833. this._prepareBuffers();
  40834. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  40835. // Draw order
  40836. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  40837. pp.onAfterRenderObservable.notifyObservers(effect);
  40838. }
  40839. }
  40840. // Restore states
  40841. engine.setDepthBuffer(true);
  40842. engine.setDepthWrite(true);
  40843. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  40844. };
  40845. /**
  40846. * Disposes of the post process manager.
  40847. */
  40848. PostProcessManager.prototype.dispose = function () {
  40849. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  40850. if (buffer) {
  40851. buffer.dispose();
  40852. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  40853. }
  40854. if (this._indexBuffer) {
  40855. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  40856. this._indexBuffer = null;
  40857. }
  40858. };
  40859. return PostProcessManager;
  40860. }());
  40861. BABYLON.PostProcessManager = PostProcessManager;
  40862. })(BABYLON || (BABYLON = {}));
  40863. //# sourceMappingURL=babylon.postProcessManager.js.map
  40864. var BABYLON;
  40865. (function (BABYLON) {
  40866. /**
  40867. * Performance monitor tracks rolling average frame-time and frame-time variance over a user defined sliding-window
  40868. */
  40869. var PerformanceMonitor = /** @class */ (function () {
  40870. /**
  40871. * constructor
  40872. * @param frameSampleSize The number of samples required to saturate the sliding window
  40873. */
  40874. function PerformanceMonitor(frameSampleSize) {
  40875. if (frameSampleSize === void 0) { frameSampleSize = 30; }
  40876. this._enabled = true;
  40877. this._rollingFrameTime = new RollingAverage(frameSampleSize);
  40878. }
  40879. /**
  40880. * Samples current frame
  40881. * @param timeMs A timestamp in milliseconds of the current frame to compare with other frames
  40882. */
  40883. PerformanceMonitor.prototype.sampleFrame = function (timeMs) {
  40884. if (timeMs === void 0) { timeMs = BABYLON.Tools.Now; }
  40885. if (!this._enabled)
  40886. return;
  40887. if (this._lastFrameTimeMs != null) {
  40888. var dt = timeMs - this._lastFrameTimeMs;
  40889. this._rollingFrameTime.add(dt);
  40890. }
  40891. this._lastFrameTimeMs = timeMs;
  40892. };
  40893. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTime", {
  40894. /**
  40895. * Returns the average frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  40896. * @return Average frame time in milliseconds
  40897. */
  40898. get: function () {
  40899. return this._rollingFrameTime.average;
  40900. },
  40901. enumerable: true,
  40902. configurable: true
  40903. });
  40904. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTimeVariance", {
  40905. /**
  40906. * Returns the variance frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  40907. * @return Frame time variance in milliseconds squared
  40908. */
  40909. get: function () {
  40910. return this._rollingFrameTime.variance;
  40911. },
  40912. enumerable: true,
  40913. configurable: true
  40914. });
  40915. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFrameTime", {
  40916. /**
  40917. * Returns the frame time of the most recent frame
  40918. * @return Frame time in milliseconds
  40919. */
  40920. get: function () {
  40921. return this._rollingFrameTime.history(0);
  40922. },
  40923. enumerable: true,
  40924. configurable: true
  40925. });
  40926. Object.defineProperty(PerformanceMonitor.prototype, "averageFPS", {
  40927. /**
  40928. * Returns the average framerate in frames per second over the sliding window (or the subset of frames sampled so far)
  40929. * @return Framerate in frames per second
  40930. */
  40931. get: function () {
  40932. return 1000.0 / this._rollingFrameTime.average;
  40933. },
  40934. enumerable: true,
  40935. configurable: true
  40936. });
  40937. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFPS", {
  40938. /**
  40939. * Returns the average framerate in frames per second using the most recent frame time
  40940. * @return Framerate in frames per second
  40941. */
  40942. get: function () {
  40943. var history = this._rollingFrameTime.history(0);
  40944. if (history === 0) {
  40945. return 0;
  40946. }
  40947. return 1000.0 / history;
  40948. },
  40949. enumerable: true,
  40950. configurable: true
  40951. });
  40952. Object.defineProperty(PerformanceMonitor.prototype, "isSaturated", {
  40953. /**
  40954. * Returns true if enough samples have been taken to completely fill the sliding window
  40955. * @return true if saturated
  40956. */
  40957. get: function () {
  40958. return this._rollingFrameTime.isSaturated();
  40959. },
  40960. enumerable: true,
  40961. configurable: true
  40962. });
  40963. /**
  40964. * Enables contributions to the sliding window sample set
  40965. */
  40966. PerformanceMonitor.prototype.enable = function () {
  40967. this._enabled = true;
  40968. };
  40969. /**
  40970. * Disables contributions to the sliding window sample set
  40971. * Samples will not be interpolated over the disabled period
  40972. */
  40973. PerformanceMonitor.prototype.disable = function () {
  40974. this._enabled = false;
  40975. //clear last sample to avoid interpolating over the disabled period when next enabled
  40976. this._lastFrameTimeMs = null;
  40977. };
  40978. Object.defineProperty(PerformanceMonitor.prototype, "isEnabled", {
  40979. /**
  40980. * Returns true if sampling is enabled
  40981. * @return true if enabled
  40982. */
  40983. get: function () {
  40984. return this._enabled;
  40985. },
  40986. enumerable: true,
  40987. configurable: true
  40988. });
  40989. /**
  40990. * Resets performance monitor
  40991. */
  40992. PerformanceMonitor.prototype.reset = function () {
  40993. //clear last sample to avoid interpolating over the disabled period when next enabled
  40994. this._lastFrameTimeMs = null;
  40995. //wipe record
  40996. this._rollingFrameTime.reset();
  40997. };
  40998. return PerformanceMonitor;
  40999. }());
  41000. BABYLON.PerformanceMonitor = PerformanceMonitor;
  41001. /**
  41002. * RollingAverage
  41003. *
  41004. * Utility to efficiently compute the rolling average and variance over a sliding window of samples
  41005. */
  41006. var RollingAverage = /** @class */ (function () {
  41007. /**
  41008. * constructor
  41009. * @param length The number of samples required to saturate the sliding window
  41010. */
  41011. function RollingAverage(length) {
  41012. this._samples = new Array(length);
  41013. this.reset();
  41014. }
  41015. /**
  41016. * Adds a sample to the sample set
  41017. * @param v The sample value
  41018. */
  41019. RollingAverage.prototype.add = function (v) {
  41020. //http://en.wikipedia.org/wiki/Algorithms_for_calculating_variance
  41021. var delta;
  41022. //we need to check if we've already wrapped round
  41023. if (this.isSaturated()) {
  41024. //remove bottom of stack from mean
  41025. var bottomValue = this._samples[this._pos];
  41026. delta = bottomValue - this.average;
  41027. this.average -= delta / (this._sampleCount - 1);
  41028. this._m2 -= delta * (bottomValue - this.average);
  41029. }
  41030. else {
  41031. this._sampleCount++;
  41032. }
  41033. //add new value to mean
  41034. delta = v - this.average;
  41035. this.average += delta / (this._sampleCount);
  41036. this._m2 += delta * (v - this.average);
  41037. //set the new variance
  41038. this.variance = this._m2 / (this._sampleCount - 1);
  41039. this._samples[this._pos] = v;
  41040. this._pos++;
  41041. this._pos %= this._samples.length; //positive wrap around
  41042. };
  41043. /**
  41044. * Returns previously added values or null if outside of history or outside the sliding window domain
  41045. * @param i Index in history. For example, pass 0 for the most recent value and 1 for the value before that
  41046. * @return Value previously recorded with add() or null if outside of range
  41047. */
  41048. RollingAverage.prototype.history = function (i) {
  41049. if ((i >= this._sampleCount) || (i >= this._samples.length)) {
  41050. return 0;
  41051. }
  41052. var i0 = this._wrapPosition(this._pos - 1.0);
  41053. return this._samples[this._wrapPosition(i0 - i)];
  41054. };
  41055. /**
  41056. * Returns true if enough samples have been taken to completely fill the sliding window
  41057. * @return true if sample-set saturated
  41058. */
  41059. RollingAverage.prototype.isSaturated = function () {
  41060. return this._sampleCount >= this._samples.length;
  41061. };
  41062. /**
  41063. * Resets the rolling average (equivalent to 0 samples taken so far)
  41064. */
  41065. RollingAverage.prototype.reset = function () {
  41066. this.average = 0;
  41067. this.variance = 0;
  41068. this._sampleCount = 0;
  41069. this._pos = 0;
  41070. this._m2 = 0;
  41071. };
  41072. /**
  41073. * Wraps a value around the sample range boundaries
  41074. * @param i Position in sample range, for example if the sample length is 5, and i is -3, then 2 will be returned.
  41075. * @return Wrapped position in sample range
  41076. */
  41077. RollingAverage.prototype._wrapPosition = function (i) {
  41078. var max = this._samples.length;
  41079. return ((i % max) + max) % max;
  41080. };
  41081. return RollingAverage;
  41082. }());
  41083. BABYLON.RollingAverage = RollingAverage;
  41084. })(BABYLON || (BABYLON = {}));
  41085. //# sourceMappingURL=babylon.performanceMonitor.js.map
  41086. var BABYLON;
  41087. (function (BABYLON) {
  41088. /**
  41089. * This groups together the common properties used for image processing either in direct forward pass
  41090. * or through post processing effect depending on the use of the image processing pipeline in your scene
  41091. * or not.
  41092. */
  41093. var ImageProcessingConfiguration = /** @class */ (function () {
  41094. function ImageProcessingConfiguration() {
  41095. /**
  41096. * Color curves setup used in the effect if colorCurvesEnabled is set to true
  41097. */
  41098. this.colorCurves = new BABYLON.ColorCurves();
  41099. this._colorCurvesEnabled = false;
  41100. this._colorGradingEnabled = false;
  41101. this._colorGradingWithGreenDepth = true;
  41102. this._colorGradingBGR = true;
  41103. this._exposure = 1.0;
  41104. this._toneMappingEnabled = false;
  41105. this._contrast = 1.0;
  41106. /**
  41107. * Vignette stretch size.
  41108. */
  41109. this.vignetteStretch = 0;
  41110. /**
  41111. * Vignette centre X Offset.
  41112. */
  41113. this.vignetteCentreX = 0;
  41114. /**
  41115. * Vignette centre Y Offset.
  41116. */
  41117. this.vignetteCentreY = 0;
  41118. /**
  41119. * Vignette weight or intensity of the vignette effect.
  41120. */
  41121. this.vignetteWeight = 1.5;
  41122. /**
  41123. * Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  41124. * if vignetteEnabled is set to true.
  41125. */
  41126. this.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  41127. /**
  41128. * Camera field of view used by the Vignette effect.
  41129. */
  41130. this.vignetteCameraFov = 0.5;
  41131. this._vignetteBlendMode = ImageProcessingConfiguration.VIGNETTEMODE_MULTIPLY;
  41132. this._vignetteEnabled = false;
  41133. this._applyByPostProcess = false;
  41134. this._isEnabled = true;
  41135. /**
  41136. * An event triggered when the configuration changes and requires Shader to Update some parameters.
  41137. */
  41138. this.onUpdateParameters = new BABYLON.Observable();
  41139. }
  41140. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorCurvesEnabled", {
  41141. /**
  41142. * Gets wether the color curves effect is enabled.
  41143. */
  41144. get: function () {
  41145. return this._colorCurvesEnabled;
  41146. },
  41147. /**
  41148. * Sets wether the color curves effect is enabled.
  41149. */
  41150. set: function (value) {
  41151. if (this._colorCurvesEnabled === value) {
  41152. return;
  41153. }
  41154. this._colorCurvesEnabled = value;
  41155. this._updateParameters();
  41156. },
  41157. enumerable: true,
  41158. configurable: true
  41159. });
  41160. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingEnabled", {
  41161. /**
  41162. * Gets wether the color grading effect is enabled.
  41163. */
  41164. get: function () {
  41165. return this._colorGradingEnabled;
  41166. },
  41167. /**
  41168. * Sets wether the color grading effect is enabled.
  41169. */
  41170. set: function (value) {
  41171. if (this._colorGradingEnabled === value) {
  41172. return;
  41173. }
  41174. this._colorGradingEnabled = value;
  41175. this._updateParameters();
  41176. },
  41177. enumerable: true,
  41178. configurable: true
  41179. });
  41180. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingWithGreenDepth", {
  41181. /**
  41182. * Gets wether the color grading effect is using a green depth for the 3d Texture.
  41183. */
  41184. get: function () {
  41185. return this._colorGradingWithGreenDepth;
  41186. },
  41187. /**
  41188. * Sets wether the color grading effect is using a green depth for the 3d Texture.
  41189. */
  41190. set: function (value) {
  41191. if (this._colorGradingWithGreenDepth === value) {
  41192. return;
  41193. }
  41194. this._colorGradingWithGreenDepth = value;
  41195. this._updateParameters();
  41196. },
  41197. enumerable: true,
  41198. configurable: true
  41199. });
  41200. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingBGR", {
  41201. /**
  41202. * Gets wether the color grading texture contains BGR values.
  41203. */
  41204. get: function () {
  41205. return this._colorGradingBGR;
  41206. },
  41207. /**
  41208. * Sets wether the color grading texture contains BGR values.
  41209. */
  41210. set: function (value) {
  41211. if (this._colorGradingBGR === value) {
  41212. return;
  41213. }
  41214. this._colorGradingBGR = value;
  41215. this._updateParameters();
  41216. },
  41217. enumerable: true,
  41218. configurable: true
  41219. });
  41220. Object.defineProperty(ImageProcessingConfiguration.prototype, "exposure", {
  41221. /**
  41222. * Gets the Exposure used in the effect.
  41223. */
  41224. get: function () {
  41225. return this._exposure;
  41226. },
  41227. /**
  41228. * Sets the Exposure used in the effect.
  41229. */
  41230. set: function (value) {
  41231. if (this._exposure === value) {
  41232. return;
  41233. }
  41234. this._exposure = value;
  41235. this._updateParameters();
  41236. },
  41237. enumerable: true,
  41238. configurable: true
  41239. });
  41240. Object.defineProperty(ImageProcessingConfiguration.prototype, "toneMappingEnabled", {
  41241. /**
  41242. * Gets wether the tone mapping effect is enabled.
  41243. */
  41244. get: function () {
  41245. return this._toneMappingEnabled;
  41246. },
  41247. /**
  41248. * Sets wether the tone mapping effect is enabled.
  41249. */
  41250. set: function (value) {
  41251. if (this._toneMappingEnabled === value) {
  41252. return;
  41253. }
  41254. this._toneMappingEnabled = value;
  41255. this._updateParameters();
  41256. },
  41257. enumerable: true,
  41258. configurable: true
  41259. });
  41260. Object.defineProperty(ImageProcessingConfiguration.prototype, "contrast", {
  41261. /**
  41262. * Gets the contrast used in the effect.
  41263. */
  41264. get: function () {
  41265. return this._contrast;
  41266. },
  41267. /**
  41268. * Sets the contrast used in the effect.
  41269. */
  41270. set: function (value) {
  41271. if (this._contrast === value) {
  41272. return;
  41273. }
  41274. this._contrast = value;
  41275. this._updateParameters();
  41276. },
  41277. enumerable: true,
  41278. configurable: true
  41279. });
  41280. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteBlendMode", {
  41281. /**
  41282. * Gets the vignette blend mode allowing different kind of effect.
  41283. */
  41284. get: function () {
  41285. return this._vignetteBlendMode;
  41286. },
  41287. /**
  41288. * Sets the vignette blend mode allowing different kind of effect.
  41289. */
  41290. set: function (value) {
  41291. if (this._vignetteBlendMode === value) {
  41292. return;
  41293. }
  41294. this._vignetteBlendMode = value;
  41295. this._updateParameters();
  41296. },
  41297. enumerable: true,
  41298. configurable: true
  41299. });
  41300. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteEnabled", {
  41301. /**
  41302. * Gets wether the vignette effect is enabled.
  41303. */
  41304. get: function () {
  41305. return this._vignetteEnabled;
  41306. },
  41307. /**
  41308. * Sets wether the vignette effect is enabled.
  41309. */
  41310. set: function (value) {
  41311. if (this._vignetteEnabled === value) {
  41312. return;
  41313. }
  41314. this._vignetteEnabled = value;
  41315. this._updateParameters();
  41316. },
  41317. enumerable: true,
  41318. configurable: true
  41319. });
  41320. Object.defineProperty(ImageProcessingConfiguration.prototype, "applyByPostProcess", {
  41321. /**
  41322. * Gets wether the image processing is applied through a post process or not.
  41323. */
  41324. get: function () {
  41325. return this._applyByPostProcess;
  41326. },
  41327. /**
  41328. * Sets wether the image processing is applied through a post process or not.
  41329. */
  41330. set: function (value) {
  41331. if (this._applyByPostProcess === value) {
  41332. return;
  41333. }
  41334. this._applyByPostProcess = value;
  41335. this._updateParameters();
  41336. },
  41337. enumerable: true,
  41338. configurable: true
  41339. });
  41340. Object.defineProperty(ImageProcessingConfiguration.prototype, "isEnabled", {
  41341. /**
  41342. * Gets wether the image processing is enabled or not.
  41343. */
  41344. get: function () {
  41345. return this._isEnabled;
  41346. },
  41347. /**
  41348. * Sets wether the image processing is enabled or not.
  41349. */
  41350. set: function (value) {
  41351. if (this._isEnabled === value) {
  41352. return;
  41353. }
  41354. this._isEnabled = value;
  41355. this._updateParameters();
  41356. },
  41357. enumerable: true,
  41358. configurable: true
  41359. });
  41360. /**
  41361. * Method called each time the image processing information changes requires to recompile the effect.
  41362. */
  41363. ImageProcessingConfiguration.prototype._updateParameters = function () {
  41364. this.onUpdateParameters.notifyObservers(this);
  41365. };
  41366. ImageProcessingConfiguration.prototype.getClassName = function () {
  41367. return "ImageProcessingConfiguration";
  41368. };
  41369. /**
  41370. * Prepare the list of uniforms associated with the Image Processing effects.
  41371. * @param uniformsList The list of uniforms used in the effect
  41372. * @param defines the list of defines currently in use
  41373. */
  41374. ImageProcessingConfiguration.PrepareUniforms = function (uniforms, defines) {
  41375. if (defines.EXPOSURE) {
  41376. uniforms.push("exposureLinear");
  41377. }
  41378. if (defines.CONTRAST) {
  41379. uniforms.push("contrast");
  41380. }
  41381. if (defines.COLORGRADING) {
  41382. uniforms.push("colorTransformSettings");
  41383. }
  41384. if (defines.VIGNETTE) {
  41385. uniforms.push("vInverseScreenSize");
  41386. uniforms.push("vignetteSettings1");
  41387. uniforms.push("vignetteSettings2");
  41388. }
  41389. if (defines.COLORCURVES) {
  41390. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  41391. }
  41392. };
  41393. /**
  41394. * Prepare the list of samplers associated with the Image Processing effects.
  41395. * @param uniformsList The list of uniforms used in the effect
  41396. * @param defines the list of defines currently in use
  41397. */
  41398. ImageProcessingConfiguration.PrepareSamplers = function (samplersList, defines) {
  41399. if (defines.COLORGRADING) {
  41400. samplersList.push("txColorTransform");
  41401. }
  41402. };
  41403. /**
  41404. * Prepare the list of defines associated to the shader.
  41405. * @param defines the list of defines to complete
  41406. */
  41407. ImageProcessingConfiguration.prototype.prepareDefines = function (defines, forPostProcess) {
  41408. if (forPostProcess === void 0) { forPostProcess = false; }
  41409. if (forPostProcess !== this.applyByPostProcess || !this._isEnabled) {
  41410. defines.VIGNETTE = false;
  41411. defines.TONEMAPPING = false;
  41412. defines.CONTRAST = false;
  41413. defines.EXPOSURE = false;
  41414. defines.COLORCURVES = false;
  41415. defines.COLORGRADING = false;
  41416. defines.COLORGRADING3D = false;
  41417. defines.IMAGEPROCESSING = false;
  41418. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess && this._isEnabled;
  41419. return;
  41420. }
  41421. defines.VIGNETTE = this.vignetteEnabled;
  41422. defines.VIGNETTEBLENDMODEMULTIPLY = (this.vignetteBlendMode === ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY);
  41423. defines.VIGNETTEBLENDMODEOPAQUE = !defines.VIGNETTEBLENDMODEMULTIPLY;
  41424. defines.TONEMAPPING = this.toneMappingEnabled;
  41425. defines.CONTRAST = (this.contrast !== 1.0);
  41426. defines.EXPOSURE = (this.exposure !== 1.0);
  41427. defines.COLORCURVES = (this.colorCurvesEnabled && !!this.colorCurves);
  41428. defines.COLORGRADING = (this.colorGradingEnabled && !!this.colorGradingTexture);
  41429. if (defines.COLORGRADING) {
  41430. defines.COLORGRADING3D = this.colorGradingTexture.is3D;
  41431. }
  41432. else {
  41433. defines.COLORGRADING3D = false;
  41434. }
  41435. defines.SAMPLER3DGREENDEPTH = this.colorGradingWithGreenDepth;
  41436. defines.SAMPLER3DBGRMAP = this.colorGradingBGR;
  41437. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess;
  41438. defines.IMAGEPROCESSING = defines.VIGNETTE || defines.TONEMAPPING || defines.CONTRAST || defines.EXPOSURE || defines.COLORCURVES || defines.COLORGRADING;
  41439. };
  41440. /**
  41441. * Returns true if all the image processing information are ready.
  41442. */
  41443. ImageProcessingConfiguration.prototype.isReady = function () {
  41444. // Color Grading texure can not be none blocking.
  41445. return !this.colorGradingEnabled || !this.colorGradingTexture || this.colorGradingTexture.isReady();
  41446. };
  41447. /**
  41448. * Binds the image processing to the shader.
  41449. * @param effect The effect to bind to
  41450. */
  41451. ImageProcessingConfiguration.prototype.bind = function (effect, aspectRatio) {
  41452. if (aspectRatio === void 0) { aspectRatio = 1; }
  41453. // Color Curves
  41454. if (this._colorCurvesEnabled && this.colorCurves) {
  41455. BABYLON.ColorCurves.Bind(this.colorCurves, effect);
  41456. }
  41457. // Vignette
  41458. if (this._vignetteEnabled) {
  41459. var inverseWidth = 1 / effect.getEngine().getRenderWidth();
  41460. var inverseHeight = 1 / effect.getEngine().getRenderHeight();
  41461. effect.setFloat2("vInverseScreenSize", inverseWidth, inverseHeight);
  41462. var vignetteScaleY = Math.tan(this.vignetteCameraFov * 0.5);
  41463. var vignetteScaleX = vignetteScaleY * aspectRatio;
  41464. var vignetteScaleGeometricMean = Math.sqrt(vignetteScaleX * vignetteScaleY);
  41465. vignetteScaleX = BABYLON.Tools.Mix(vignetteScaleX, vignetteScaleGeometricMean, this.vignetteStretch);
  41466. vignetteScaleY = BABYLON.Tools.Mix(vignetteScaleY, vignetteScaleGeometricMean, this.vignetteStretch);
  41467. effect.setFloat4("vignetteSettings1", vignetteScaleX, vignetteScaleY, -vignetteScaleX * this.vignetteCentreX, -vignetteScaleY * this.vignetteCentreY);
  41468. var vignettePower = -2.0 * this.vignetteWeight;
  41469. effect.setFloat4("vignetteSettings2", this.vignetteColor.r, this.vignetteColor.g, this.vignetteColor.b, vignettePower);
  41470. }
  41471. // Exposure
  41472. effect.setFloat("exposureLinear", this.exposure);
  41473. // Contrast
  41474. effect.setFloat("contrast", this.contrast);
  41475. // Color transform settings
  41476. if (this.colorGradingTexture) {
  41477. effect.setTexture("txColorTransform", this.colorGradingTexture);
  41478. var textureSize = this.colorGradingTexture.getSize().height;
  41479. effect.setFloat4("colorTransformSettings", (textureSize - 1) / textureSize, // textureScale
  41480. 0.5 / textureSize, // textureOffset
  41481. textureSize, // textureSize
  41482. this.colorGradingTexture.level // weight
  41483. );
  41484. }
  41485. };
  41486. /**
  41487. * Clones the current image processing instance.
  41488. * @return The cloned image processing
  41489. */
  41490. ImageProcessingConfiguration.prototype.clone = function () {
  41491. return BABYLON.SerializationHelper.Clone(function () { return new ImageProcessingConfiguration(); }, this);
  41492. };
  41493. /**
  41494. * Serializes the current image processing instance to a json representation.
  41495. * @return a JSON representation
  41496. */
  41497. ImageProcessingConfiguration.prototype.serialize = function () {
  41498. return BABYLON.SerializationHelper.Serialize(this);
  41499. };
  41500. /**
  41501. * Parses the image processing from a json representation.
  41502. * @param source the JSON source to parse
  41503. * @return The parsed image processing
  41504. */
  41505. ImageProcessingConfiguration.Parse = function (source) {
  41506. return BABYLON.SerializationHelper.Parse(function () { return new ImageProcessingConfiguration(); }, source, null, null);
  41507. };
  41508. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_MULTIPLY", {
  41509. /**
  41510. * Used to apply the vignette as a mix with the pixel color.
  41511. */
  41512. get: function () {
  41513. return this._VIGNETTEMODE_MULTIPLY;
  41514. },
  41515. enumerable: true,
  41516. configurable: true
  41517. });
  41518. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_OPAQUE", {
  41519. /**
  41520. * Used to apply the vignette as a replacement of the pixel color.
  41521. */
  41522. get: function () {
  41523. return this._VIGNETTEMODE_OPAQUE;
  41524. },
  41525. enumerable: true,
  41526. configurable: true
  41527. });
  41528. // Static constants associated to the image processing.
  41529. ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY = 0;
  41530. ImageProcessingConfiguration._VIGNETTEMODE_OPAQUE = 1;
  41531. __decorate([
  41532. BABYLON.serializeAsColorCurves()
  41533. ], ImageProcessingConfiguration.prototype, "colorCurves", void 0);
  41534. __decorate([
  41535. BABYLON.serialize()
  41536. ], ImageProcessingConfiguration.prototype, "_colorCurvesEnabled", void 0);
  41537. __decorate([
  41538. BABYLON.serializeAsTexture()
  41539. ], ImageProcessingConfiguration.prototype, "colorGradingTexture", void 0);
  41540. __decorate([
  41541. BABYLON.serialize()
  41542. ], ImageProcessingConfiguration.prototype, "_colorGradingEnabled", void 0);
  41543. __decorate([
  41544. BABYLON.serialize()
  41545. ], ImageProcessingConfiguration.prototype, "_colorGradingWithGreenDepth", void 0);
  41546. __decorate([
  41547. BABYLON.serialize()
  41548. ], ImageProcessingConfiguration.prototype, "_colorGradingBGR", void 0);
  41549. __decorate([
  41550. BABYLON.serialize()
  41551. ], ImageProcessingConfiguration.prototype, "_exposure", void 0);
  41552. __decorate([
  41553. BABYLON.serialize()
  41554. ], ImageProcessingConfiguration.prototype, "_toneMappingEnabled", void 0);
  41555. __decorate([
  41556. BABYLON.serialize()
  41557. ], ImageProcessingConfiguration.prototype, "_contrast", void 0);
  41558. __decorate([
  41559. BABYLON.serialize()
  41560. ], ImageProcessingConfiguration.prototype, "vignetteStretch", void 0);
  41561. __decorate([
  41562. BABYLON.serialize()
  41563. ], ImageProcessingConfiguration.prototype, "vignetteCentreX", void 0);
  41564. __decorate([
  41565. BABYLON.serialize()
  41566. ], ImageProcessingConfiguration.prototype, "vignetteCentreY", void 0);
  41567. __decorate([
  41568. BABYLON.serialize()
  41569. ], ImageProcessingConfiguration.prototype, "vignetteWeight", void 0);
  41570. __decorate([
  41571. BABYLON.serializeAsColor4()
  41572. ], ImageProcessingConfiguration.prototype, "vignetteColor", void 0);
  41573. __decorate([
  41574. BABYLON.serialize()
  41575. ], ImageProcessingConfiguration.prototype, "vignetteCameraFov", void 0);
  41576. __decorate([
  41577. BABYLON.serialize()
  41578. ], ImageProcessingConfiguration.prototype, "_vignetteBlendMode", void 0);
  41579. __decorate([
  41580. BABYLON.serialize()
  41581. ], ImageProcessingConfiguration.prototype, "_vignetteEnabled", void 0);
  41582. __decorate([
  41583. BABYLON.serialize()
  41584. ], ImageProcessingConfiguration.prototype, "_applyByPostProcess", void 0);
  41585. __decorate([
  41586. BABYLON.serialize()
  41587. ], ImageProcessingConfiguration.prototype, "_isEnabled", void 0);
  41588. return ImageProcessingConfiguration;
  41589. }());
  41590. BABYLON.ImageProcessingConfiguration = ImageProcessingConfiguration;
  41591. })(BABYLON || (BABYLON = {}));
  41592. //# sourceMappingURL=babylon.imageProcessingConfiguration.js.map
  41593. var BABYLON;
  41594. (function (BABYLON) {
  41595. /**
  41596. * This represents a color grading texture. This acts as a lookup table LUT, useful during post process
  41597. * It can help converting any input color in a desired output one. This can then be used to create effects
  41598. * from sepia, black and white to sixties or futuristic rendering...
  41599. *
  41600. * The only supported format is currently 3dl.
  41601. * More information on LUT: https://en.wikipedia.org/wiki/3D_lookup_table/
  41602. */
  41603. var ColorGradingTexture = /** @class */ (function (_super) {
  41604. __extends(ColorGradingTexture, _super);
  41605. /**
  41606. * Instantiates a ColorGradingTexture from the following parameters.
  41607. *
  41608. * @param url The location of the color gradind data (currently only supporting 3dl)
  41609. * @param scene The scene the texture will be used in
  41610. */
  41611. function ColorGradingTexture(url, scene) {
  41612. var _this = _super.call(this, scene) || this;
  41613. if (!url) {
  41614. return _this;
  41615. }
  41616. _this._engine = scene.getEngine();
  41617. _this._textureMatrix = BABYLON.Matrix.Identity();
  41618. _this.name = url;
  41619. _this.url = url;
  41620. _this.hasAlpha = false;
  41621. _this.isCube = false;
  41622. _this.is3D = _this._engine.webGLVersion > 1;
  41623. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  41624. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  41625. _this.wrapR = BABYLON.Texture.CLAMP_ADDRESSMODE;
  41626. _this.anisotropicFilteringLevel = 1;
  41627. _this._texture = _this._getFromCache(url, true);
  41628. if (!_this._texture) {
  41629. if (!scene.useDelayedTextureLoading) {
  41630. _this.loadTexture();
  41631. }
  41632. else {
  41633. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  41634. }
  41635. }
  41636. return _this;
  41637. }
  41638. /**
  41639. * Returns the texture matrix used in most of the material.
  41640. * This is not used in color grading but keep for troubleshooting purpose (easily swap diffuse by colorgrading to look in).
  41641. */
  41642. ColorGradingTexture.prototype.getTextureMatrix = function () {
  41643. return this._textureMatrix;
  41644. };
  41645. /**
  41646. * Occurs when the file being loaded is a .3dl LUT file.
  41647. */
  41648. ColorGradingTexture.prototype.load3dlTexture = function () {
  41649. var engine = this._engine;
  41650. var texture;
  41651. if (engine.webGLVersion === 1) {
  41652. texture = engine.createRawTexture(null, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  41653. }
  41654. else {
  41655. texture = engine.createRawTexture3D(null, 1, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  41656. }
  41657. this._texture = texture;
  41658. var callback = function (text) {
  41659. if (typeof text !== "string") {
  41660. return;
  41661. }
  41662. var data = null;
  41663. var tempData = null;
  41664. var line;
  41665. var lines = text.split('\n');
  41666. var size = 0, pixelIndexW = 0, pixelIndexH = 0, pixelIndexSlice = 0;
  41667. var maxColor = 0;
  41668. for (var i = 0; i < lines.length; i++) {
  41669. line = lines[i];
  41670. if (!ColorGradingTexture._noneEmptyLineRegex.test(line))
  41671. continue;
  41672. if (line.indexOf('#') === 0)
  41673. continue;
  41674. var words = line.split(" ");
  41675. if (size === 0) {
  41676. // Number of space + one
  41677. size = words.length;
  41678. data = new Uint8Array(size * size * size * 4); // volume texture of side size and rgb 8
  41679. tempData = new Float32Array(size * size * size * 4);
  41680. continue;
  41681. }
  41682. if (size != 0) {
  41683. var r = Math.max(parseInt(words[0]), 0);
  41684. var g = Math.max(parseInt(words[1]), 0);
  41685. var b = Math.max(parseInt(words[2]), 0);
  41686. maxColor = Math.max(r, maxColor);
  41687. maxColor = Math.max(g, maxColor);
  41688. maxColor = Math.max(b, maxColor);
  41689. var pixelStorageIndex = (pixelIndexW + pixelIndexSlice * size + pixelIndexH * size * size) * 4;
  41690. if (tempData) {
  41691. tempData[pixelStorageIndex + 0] = r;
  41692. tempData[pixelStorageIndex + 1] = g;
  41693. tempData[pixelStorageIndex + 2] = b;
  41694. }
  41695. pixelIndexSlice++;
  41696. if (pixelIndexSlice % size == 0) {
  41697. pixelIndexH++;
  41698. pixelIndexSlice = 0;
  41699. if (pixelIndexH % size == 0) {
  41700. pixelIndexW++;
  41701. pixelIndexH = 0;
  41702. }
  41703. }
  41704. }
  41705. }
  41706. if (tempData && data) {
  41707. for (var i = 0; i < tempData.length; i++) {
  41708. if (i > 0 && (i + 1) % 4 === 0) {
  41709. data[i] = 255;
  41710. }
  41711. else {
  41712. var value = tempData[i];
  41713. data[i] = (value / maxColor * 255);
  41714. }
  41715. }
  41716. }
  41717. if (texture.is3D) {
  41718. texture.updateSize(size, size, size);
  41719. engine.updateRawTexture3D(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  41720. }
  41721. else {
  41722. texture.updateSize(size * size, size);
  41723. engine.updateRawTexture(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  41724. }
  41725. };
  41726. var scene = this.getScene();
  41727. if (scene) {
  41728. scene._loadFile(this.url, callback);
  41729. }
  41730. else {
  41731. this._engine._loadFile(this.url, callback);
  41732. }
  41733. return this._texture;
  41734. };
  41735. /**
  41736. * Starts the loading process of the texture.
  41737. */
  41738. ColorGradingTexture.prototype.loadTexture = function () {
  41739. if (this.url && this.url.toLocaleLowerCase().indexOf(".3dl") == (this.url.length - 4)) {
  41740. this.load3dlTexture();
  41741. }
  41742. };
  41743. /**
  41744. * Clones the color gradind texture.
  41745. */
  41746. ColorGradingTexture.prototype.clone = function () {
  41747. var newTexture = new ColorGradingTexture(this.url, this.getScene());
  41748. // Base texture
  41749. newTexture.level = this.level;
  41750. return newTexture;
  41751. };
  41752. /**
  41753. * Called during delayed load for textures.
  41754. */
  41755. ColorGradingTexture.prototype.delayLoad = function () {
  41756. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  41757. return;
  41758. }
  41759. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  41760. this._texture = this._getFromCache(this.url, true);
  41761. if (!this._texture) {
  41762. this.loadTexture();
  41763. }
  41764. };
  41765. /**
  41766. * Parses a color grading texture serialized by Babylon.
  41767. * @param parsedTexture The texture information being parsedTexture
  41768. * @param scene The scene to load the texture in
  41769. * @param rootUrl The root url of the data assets to load
  41770. * @return A color gradind texture
  41771. */
  41772. ColorGradingTexture.Parse = function (parsedTexture, scene, rootUrl) {
  41773. var texture = null;
  41774. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  41775. texture = new ColorGradingTexture(parsedTexture.name, scene);
  41776. texture.name = parsedTexture.name;
  41777. texture.level = parsedTexture.level;
  41778. }
  41779. return texture;
  41780. };
  41781. /**
  41782. * Serializes the LUT texture to json format.
  41783. */
  41784. ColorGradingTexture.prototype.serialize = function () {
  41785. if (!this.name) {
  41786. return null;
  41787. }
  41788. var serializationObject = {};
  41789. serializationObject.name = this.name;
  41790. serializationObject.level = this.level;
  41791. serializationObject.customType = "BABYLON.ColorGradingTexture";
  41792. return serializationObject;
  41793. };
  41794. /**
  41795. * Empty line regex stored for GC.
  41796. */
  41797. ColorGradingTexture._noneEmptyLineRegex = /\S+/;
  41798. return ColorGradingTexture;
  41799. }(BABYLON.BaseTexture));
  41800. BABYLON.ColorGradingTexture = ColorGradingTexture;
  41801. })(BABYLON || (BABYLON = {}));
  41802. //# sourceMappingURL=babylon.colorGradingTexture.js.map
  41803. var BABYLON;
  41804. (function (BABYLON) {
  41805. /**
  41806. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  41807. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  41808. * 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;
  41809. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  41810. */
  41811. var ColorCurves = /** @class */ (function () {
  41812. function ColorCurves() {
  41813. this._dirty = true;
  41814. this._tempColor = new BABYLON.Color4(0, 0, 0, 0);
  41815. this._globalCurve = new BABYLON.Color4(0, 0, 0, 0);
  41816. this._highlightsCurve = new BABYLON.Color4(0, 0, 0, 0);
  41817. this._midtonesCurve = new BABYLON.Color4(0, 0, 0, 0);
  41818. this._shadowsCurve = new BABYLON.Color4(0, 0, 0, 0);
  41819. this._positiveCurve = new BABYLON.Color4(0, 0, 0, 0);
  41820. this._negativeCurve = new BABYLON.Color4(0, 0, 0, 0);
  41821. this._globalHue = 30;
  41822. this._globalDensity = 0;
  41823. this._globalSaturation = 0;
  41824. this._globalExposure = 0;
  41825. this._highlightsHue = 30;
  41826. this._highlightsDensity = 0;
  41827. this._highlightsSaturation = 0;
  41828. this._highlightsExposure = 0;
  41829. this._midtonesHue = 30;
  41830. this._midtonesDensity = 0;
  41831. this._midtonesSaturation = 0;
  41832. this._midtonesExposure = 0;
  41833. this._shadowsHue = 30;
  41834. this._shadowsDensity = 0;
  41835. this._shadowsSaturation = 0;
  41836. this._shadowsExposure = 0;
  41837. }
  41838. Object.defineProperty(ColorCurves.prototype, "globalHue", {
  41839. /**
  41840. * Gets the global Hue value.
  41841. * 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).
  41842. */
  41843. get: function () {
  41844. return this._globalHue;
  41845. },
  41846. /**
  41847. * Sets the global Hue value.
  41848. * 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).
  41849. */
  41850. set: function (value) {
  41851. this._globalHue = value;
  41852. this._dirty = true;
  41853. },
  41854. enumerable: true,
  41855. configurable: true
  41856. });
  41857. Object.defineProperty(ColorCurves.prototype, "globalDensity", {
  41858. /**
  41859. * Gets the global Density value.
  41860. * 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.
  41861. * Values less than zero provide a filter of opposite hue.
  41862. */
  41863. get: function () {
  41864. return this._globalDensity;
  41865. },
  41866. /**
  41867. * Sets the global Density value.
  41868. * 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.
  41869. * Values less than zero provide a filter of opposite hue.
  41870. */
  41871. set: function (value) {
  41872. this._globalDensity = value;
  41873. this._dirty = true;
  41874. },
  41875. enumerable: true,
  41876. configurable: true
  41877. });
  41878. Object.defineProperty(ColorCurves.prototype, "globalSaturation", {
  41879. /**
  41880. * Gets the global Saturation value.
  41881. * 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.
  41882. */
  41883. get: function () {
  41884. return this._globalSaturation;
  41885. },
  41886. /**
  41887. * Sets the global Saturation value.
  41888. * 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.
  41889. */
  41890. set: function (value) {
  41891. this._globalSaturation = value;
  41892. this._dirty = true;
  41893. },
  41894. enumerable: true,
  41895. configurable: true
  41896. });
  41897. Object.defineProperty(ColorCurves.prototype, "globalExposure", {
  41898. /**
  41899. * Gets the global Exposure value.
  41900. * 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.
  41901. */
  41902. get: function () {
  41903. return this._globalExposure;
  41904. },
  41905. /**
  41906. * Sets the global Exposure value.
  41907. * 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.
  41908. */
  41909. set: function (value) {
  41910. this._globalExposure = value;
  41911. this._dirty = true;
  41912. },
  41913. enumerable: true,
  41914. configurable: true
  41915. });
  41916. Object.defineProperty(ColorCurves.prototype, "highlightsHue", {
  41917. /**
  41918. * Gets the highlights Hue value.
  41919. * 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).
  41920. */
  41921. get: function () {
  41922. return this._highlightsHue;
  41923. },
  41924. /**
  41925. * Sets the highlights Hue value.
  41926. * 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).
  41927. */
  41928. set: function (value) {
  41929. this._highlightsHue = value;
  41930. this._dirty = true;
  41931. },
  41932. enumerable: true,
  41933. configurable: true
  41934. });
  41935. Object.defineProperty(ColorCurves.prototype, "highlightsDensity", {
  41936. /**
  41937. * Gets the highlights Density value.
  41938. * 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.
  41939. * Values less than zero provide a filter of opposite hue.
  41940. */
  41941. get: function () {
  41942. return this._highlightsDensity;
  41943. },
  41944. /**
  41945. * Sets the highlights Density value.
  41946. * 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.
  41947. * Values less than zero provide a filter of opposite hue.
  41948. */
  41949. set: function (value) {
  41950. this._highlightsDensity = value;
  41951. this._dirty = true;
  41952. },
  41953. enumerable: true,
  41954. configurable: true
  41955. });
  41956. Object.defineProperty(ColorCurves.prototype, "highlightsSaturation", {
  41957. /**
  41958. * Gets the highlights Saturation value.
  41959. * 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.
  41960. */
  41961. get: function () {
  41962. return this._highlightsSaturation;
  41963. },
  41964. /**
  41965. * Sets the highlights Saturation value.
  41966. * 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.
  41967. */
  41968. set: function (value) {
  41969. this._highlightsSaturation = value;
  41970. this._dirty = true;
  41971. },
  41972. enumerable: true,
  41973. configurable: true
  41974. });
  41975. Object.defineProperty(ColorCurves.prototype, "highlightsExposure", {
  41976. /**
  41977. * Gets the highlights Exposure value.
  41978. * 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.
  41979. */
  41980. get: function () {
  41981. return this._highlightsExposure;
  41982. },
  41983. /**
  41984. * Sets the highlights Exposure value.
  41985. * 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.
  41986. */
  41987. set: function (value) {
  41988. this._highlightsExposure = value;
  41989. this._dirty = true;
  41990. },
  41991. enumerable: true,
  41992. configurable: true
  41993. });
  41994. Object.defineProperty(ColorCurves.prototype, "midtonesHue", {
  41995. /**
  41996. * Gets the midtones Hue value.
  41997. * 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).
  41998. */
  41999. get: function () {
  42000. return this._midtonesHue;
  42001. },
  42002. /**
  42003. * Sets the midtones Hue value.
  42004. * 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).
  42005. */
  42006. set: function (value) {
  42007. this._midtonesHue = value;
  42008. this._dirty = true;
  42009. },
  42010. enumerable: true,
  42011. configurable: true
  42012. });
  42013. Object.defineProperty(ColorCurves.prototype, "midtonesDensity", {
  42014. /**
  42015. * Gets the midtones Density value.
  42016. * 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.
  42017. * Values less than zero provide a filter of opposite hue.
  42018. */
  42019. get: function () {
  42020. return this._midtonesDensity;
  42021. },
  42022. /**
  42023. * Sets the midtones Density value.
  42024. * 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.
  42025. * Values less than zero provide a filter of opposite hue.
  42026. */
  42027. set: function (value) {
  42028. this._midtonesDensity = value;
  42029. this._dirty = true;
  42030. },
  42031. enumerable: true,
  42032. configurable: true
  42033. });
  42034. Object.defineProperty(ColorCurves.prototype, "midtonesSaturation", {
  42035. /**
  42036. * Gets the midtones Saturation value.
  42037. * 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.
  42038. */
  42039. get: function () {
  42040. return this._midtonesSaturation;
  42041. },
  42042. /**
  42043. * Sets the midtones Saturation value.
  42044. * 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.
  42045. */
  42046. set: function (value) {
  42047. this._midtonesSaturation = value;
  42048. this._dirty = true;
  42049. },
  42050. enumerable: true,
  42051. configurable: true
  42052. });
  42053. Object.defineProperty(ColorCurves.prototype, "midtonesExposure", {
  42054. /**
  42055. * Gets the midtones Exposure value.
  42056. * 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.
  42057. */
  42058. get: function () {
  42059. return this._midtonesExposure;
  42060. },
  42061. /**
  42062. * Sets the midtones Exposure value.
  42063. * 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.
  42064. */
  42065. set: function (value) {
  42066. this._midtonesExposure = value;
  42067. this._dirty = true;
  42068. },
  42069. enumerable: true,
  42070. configurable: true
  42071. });
  42072. Object.defineProperty(ColorCurves.prototype, "shadowsHue", {
  42073. /**
  42074. * Gets the shadows Hue value.
  42075. * 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).
  42076. */
  42077. get: function () {
  42078. return this._shadowsHue;
  42079. },
  42080. /**
  42081. * Sets the shadows Hue value.
  42082. * 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).
  42083. */
  42084. set: function (value) {
  42085. this._shadowsHue = value;
  42086. this._dirty = true;
  42087. },
  42088. enumerable: true,
  42089. configurable: true
  42090. });
  42091. Object.defineProperty(ColorCurves.prototype, "shadowsDensity", {
  42092. /**
  42093. * Gets the shadows Density value.
  42094. * 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.
  42095. * Values less than zero provide a filter of opposite hue.
  42096. */
  42097. get: function () {
  42098. return this._shadowsDensity;
  42099. },
  42100. /**
  42101. * Sets the shadows Density value.
  42102. * 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.
  42103. * Values less than zero provide a filter of opposite hue.
  42104. */
  42105. set: function (value) {
  42106. this._shadowsDensity = value;
  42107. this._dirty = true;
  42108. },
  42109. enumerable: true,
  42110. configurable: true
  42111. });
  42112. Object.defineProperty(ColorCurves.prototype, "shadowsSaturation", {
  42113. /**
  42114. * Gets the shadows Saturation value.
  42115. * 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.
  42116. */
  42117. get: function () {
  42118. return this._shadowsSaturation;
  42119. },
  42120. /**
  42121. * Sets the shadows Saturation value.
  42122. * 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.
  42123. */
  42124. set: function (value) {
  42125. this._shadowsSaturation = value;
  42126. this._dirty = true;
  42127. },
  42128. enumerable: true,
  42129. configurable: true
  42130. });
  42131. Object.defineProperty(ColorCurves.prototype, "shadowsExposure", {
  42132. /**
  42133. * Gets the shadows Exposure value.
  42134. * 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.
  42135. */
  42136. get: function () {
  42137. return this._shadowsExposure;
  42138. },
  42139. /**
  42140. * Sets the shadows Exposure value.
  42141. * 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.
  42142. */
  42143. set: function (value) {
  42144. this._shadowsExposure = value;
  42145. this._dirty = true;
  42146. },
  42147. enumerable: true,
  42148. configurable: true
  42149. });
  42150. ColorCurves.prototype.getClassName = function () {
  42151. return "ColorCurves";
  42152. };
  42153. /**
  42154. * Binds the color curves to the shader.
  42155. * @param colorCurves The color curve to bind
  42156. * @param effect The effect to bind to
  42157. */
  42158. ColorCurves.Bind = function (colorCurves, effect, positiveUniform, neutralUniform, negativeUniform) {
  42159. if (positiveUniform === void 0) { positiveUniform = "vCameraColorCurvePositive"; }
  42160. if (neutralUniform === void 0) { neutralUniform = "vCameraColorCurveNeutral"; }
  42161. if (negativeUniform === void 0) { negativeUniform = "vCameraColorCurveNegative"; }
  42162. if (colorCurves._dirty) {
  42163. colorCurves._dirty = false;
  42164. // Fill in global info.
  42165. colorCurves.getColorGradingDataToRef(colorCurves._globalHue, colorCurves._globalDensity, colorCurves._globalSaturation, colorCurves._globalExposure, colorCurves._globalCurve);
  42166. // Compute highlights info.
  42167. colorCurves.getColorGradingDataToRef(colorCurves._highlightsHue, colorCurves._highlightsDensity, colorCurves._highlightsSaturation, colorCurves._highlightsExposure, colorCurves._tempColor);
  42168. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._highlightsCurve);
  42169. // Compute midtones info.
  42170. colorCurves.getColorGradingDataToRef(colorCurves._midtonesHue, colorCurves._midtonesDensity, colorCurves._midtonesSaturation, colorCurves._midtonesExposure, colorCurves._tempColor);
  42171. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._midtonesCurve);
  42172. // Compute shadows info.
  42173. colorCurves.getColorGradingDataToRef(colorCurves._shadowsHue, colorCurves._shadowsDensity, colorCurves._shadowsSaturation, colorCurves._shadowsExposure, colorCurves._tempColor);
  42174. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._shadowsCurve);
  42175. // Compute deltas (neutral is midtones).
  42176. colorCurves._highlightsCurve.subtractToRef(colorCurves._midtonesCurve, colorCurves._positiveCurve);
  42177. colorCurves._midtonesCurve.subtractToRef(colorCurves._shadowsCurve, colorCurves._negativeCurve);
  42178. }
  42179. if (effect) {
  42180. effect.setFloat4(positiveUniform, colorCurves._positiveCurve.r, colorCurves._positiveCurve.g, colorCurves._positiveCurve.b, colorCurves._positiveCurve.a);
  42181. effect.setFloat4(neutralUniform, colorCurves._midtonesCurve.r, colorCurves._midtonesCurve.g, colorCurves._midtonesCurve.b, colorCurves._midtonesCurve.a);
  42182. effect.setFloat4(negativeUniform, colorCurves._negativeCurve.r, colorCurves._negativeCurve.g, colorCurves._negativeCurve.b, colorCurves._negativeCurve.a);
  42183. }
  42184. };
  42185. /**
  42186. * Prepare the list of uniforms associated with the ColorCurves effects.
  42187. * @param uniformsList The list of uniforms used in the effect
  42188. */
  42189. ColorCurves.PrepareUniforms = function (uniformsList) {
  42190. uniformsList.push("vCameraColorCurveNeutral", "vCameraColorCurvePositive", "vCameraColorCurveNegative");
  42191. };
  42192. /**
  42193. * Returns color grading data based on a hue, density, saturation and exposure value.
  42194. * @param filterHue The hue of the color filter.
  42195. * @param filterDensity The density of the color filter.
  42196. * @param saturation The saturation.
  42197. * @param exposure The exposure.
  42198. * @param result The result data container.
  42199. */
  42200. ColorCurves.prototype.getColorGradingDataToRef = function (hue, density, saturation, exposure, result) {
  42201. if (hue == null) {
  42202. return;
  42203. }
  42204. hue = ColorCurves.clamp(hue, 0, 360);
  42205. density = ColorCurves.clamp(density, -100, 100);
  42206. saturation = ColorCurves.clamp(saturation, -100, 100);
  42207. exposure = ColorCurves.clamp(exposure, -100, 100);
  42208. // Remap the slider/config filter density with non-linear mapping and also scale by half
  42209. // so that the maximum filter density is only 50% control. This provides fine control
  42210. // for small values and reasonable range.
  42211. density = ColorCurves.applyColorGradingSliderNonlinear(density);
  42212. density *= 0.5;
  42213. exposure = ColorCurves.applyColorGradingSliderNonlinear(exposure);
  42214. if (density < 0) {
  42215. density *= -1;
  42216. hue = (hue + 180) % 360;
  42217. }
  42218. ColorCurves.fromHSBToRef(hue, density, 50 + 0.25 * exposure, result);
  42219. result.scaleToRef(2, result);
  42220. result.a = 1 + 0.01 * saturation;
  42221. };
  42222. /**
  42223. * Takes an input slider value and returns an adjusted value that provides extra control near the centre.
  42224. * @param value The input slider value in range [-100,100].
  42225. * @returns Adjusted value.
  42226. */
  42227. ColorCurves.applyColorGradingSliderNonlinear = function (value) {
  42228. value /= 100;
  42229. var x = Math.abs(value);
  42230. x = Math.pow(x, 2);
  42231. if (value < 0) {
  42232. x *= -1;
  42233. }
  42234. x *= 100;
  42235. return x;
  42236. };
  42237. /**
  42238. * Returns an RGBA Color4 based on Hue, Saturation and Brightness (also referred to as value, HSV).
  42239. * @param hue The hue (H) input.
  42240. * @param saturation The saturation (S) input.
  42241. * @param brightness The brightness (B) input.
  42242. * @result An RGBA color represented as Vector4.
  42243. */
  42244. ColorCurves.fromHSBToRef = function (hue, saturation, brightness, result) {
  42245. var h = ColorCurves.clamp(hue, 0, 360);
  42246. var s = ColorCurves.clamp(saturation / 100, 0, 1);
  42247. var v = ColorCurves.clamp(brightness / 100, 0, 1);
  42248. if (s === 0) {
  42249. result.r = v;
  42250. result.g = v;
  42251. result.b = v;
  42252. }
  42253. else {
  42254. // sector 0 to 5
  42255. h /= 60;
  42256. var i = Math.floor(h);
  42257. // fractional part of h
  42258. var f = h - i;
  42259. var p = v * (1 - s);
  42260. var q = v * (1 - s * f);
  42261. var t = v * (1 - s * (1 - f));
  42262. switch (i) {
  42263. case 0:
  42264. result.r = v;
  42265. result.g = t;
  42266. result.b = p;
  42267. break;
  42268. case 1:
  42269. result.r = q;
  42270. result.g = v;
  42271. result.b = p;
  42272. break;
  42273. case 2:
  42274. result.r = p;
  42275. result.g = v;
  42276. result.b = t;
  42277. break;
  42278. case 3:
  42279. result.r = p;
  42280. result.g = q;
  42281. result.b = v;
  42282. break;
  42283. case 4:
  42284. result.r = t;
  42285. result.g = p;
  42286. result.b = v;
  42287. break;
  42288. default: // case 5:
  42289. result.r = v;
  42290. result.g = p;
  42291. result.b = q;
  42292. break;
  42293. }
  42294. }
  42295. result.a = 1;
  42296. };
  42297. /**
  42298. * Returns a value clamped between min and max
  42299. * @param value The value to clamp
  42300. * @param min The minimum of value
  42301. * @param max The maximum of value
  42302. * @returns The clamped value.
  42303. */
  42304. ColorCurves.clamp = function (value, min, max) {
  42305. return Math.min(Math.max(value, min), max);
  42306. };
  42307. /**
  42308. * Clones the current color curve instance.
  42309. * @return The cloned curves
  42310. */
  42311. ColorCurves.prototype.clone = function () {
  42312. return BABYLON.SerializationHelper.Clone(function () { return new ColorCurves(); }, this);
  42313. };
  42314. /**
  42315. * Serializes the current color curve instance to a json representation.
  42316. * @return a JSON representation
  42317. */
  42318. ColorCurves.prototype.serialize = function () {
  42319. return BABYLON.SerializationHelper.Serialize(this);
  42320. };
  42321. /**
  42322. * Parses the color curve from a json representation.
  42323. * @param source the JSON source to parse
  42324. * @return The parsed curves
  42325. */
  42326. ColorCurves.Parse = function (source) {
  42327. return BABYLON.SerializationHelper.Parse(function () { return new ColorCurves(); }, source, null, null);
  42328. };
  42329. __decorate([
  42330. BABYLON.serialize()
  42331. ], ColorCurves.prototype, "_globalHue", void 0);
  42332. __decorate([
  42333. BABYLON.serialize()
  42334. ], ColorCurves.prototype, "_globalDensity", void 0);
  42335. __decorate([
  42336. BABYLON.serialize()
  42337. ], ColorCurves.prototype, "_globalSaturation", void 0);
  42338. __decorate([
  42339. BABYLON.serialize()
  42340. ], ColorCurves.prototype, "_globalExposure", void 0);
  42341. __decorate([
  42342. BABYLON.serialize()
  42343. ], ColorCurves.prototype, "_highlightsHue", void 0);
  42344. __decorate([
  42345. BABYLON.serialize()
  42346. ], ColorCurves.prototype, "_highlightsDensity", void 0);
  42347. __decorate([
  42348. BABYLON.serialize()
  42349. ], ColorCurves.prototype, "_highlightsSaturation", void 0);
  42350. __decorate([
  42351. BABYLON.serialize()
  42352. ], ColorCurves.prototype, "_highlightsExposure", void 0);
  42353. __decorate([
  42354. BABYLON.serialize()
  42355. ], ColorCurves.prototype, "_midtonesHue", void 0);
  42356. __decorate([
  42357. BABYLON.serialize()
  42358. ], ColorCurves.prototype, "_midtonesDensity", void 0);
  42359. __decorate([
  42360. BABYLON.serialize()
  42361. ], ColorCurves.prototype, "_midtonesSaturation", void 0);
  42362. __decorate([
  42363. BABYLON.serialize()
  42364. ], ColorCurves.prototype, "_midtonesExposure", void 0);
  42365. return ColorCurves;
  42366. }());
  42367. BABYLON.ColorCurves = ColorCurves;
  42368. })(BABYLON || (BABYLON = {}));
  42369. //# sourceMappingURL=babylon.colorCurves.js.map
  42370. //# sourceMappingURL=babylon.behavior.js.map
  42371. var BABYLON;
  42372. (function (BABYLON) {
  42373. /**
  42374. * "Static Class" containing the most commonly used helper while dealing with material for
  42375. * rendering purpose.
  42376. *
  42377. * It contains the basic tools to help defining defines, binding uniform for the common part of the materials.
  42378. *
  42379. * This works by convention in BabylonJS but is meant to be use only with shader following the in place naming rules and conventions.
  42380. */
  42381. var MaterialHelper = /** @class */ (function () {
  42382. function MaterialHelper() {
  42383. }
  42384. /**
  42385. * Bind the current view position to an effect.
  42386. * @param effect The effect to be bound
  42387. * @param scene The scene the eyes position is used from
  42388. */
  42389. MaterialHelper.BindEyePosition = function (effect, scene) {
  42390. if (scene._forcedViewPosition) {
  42391. effect.setVector3("vEyePosition", scene._forcedViewPosition);
  42392. return;
  42393. }
  42394. effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  42395. };
  42396. /**
  42397. * Helps preparing the defines values about the UVs in used in the effect.
  42398. * UVs are shared as much as we can accross chanels in the shaders.
  42399. * @param texture The texture we are preparing the UVs for
  42400. * @param defines The defines to update
  42401. * @param key The chanel key "diffuse", "specular"... used in the shader
  42402. */
  42403. MaterialHelper.PrepareDefinesForMergedUV = function (texture, defines, key) {
  42404. defines._needUVs = true;
  42405. defines[key] = true;
  42406. if (texture.getTextureMatrix().isIdentity(true)) {
  42407. defines[key + "DIRECTUV"] = texture.coordinatesIndex + 1;
  42408. if (texture.coordinatesIndex === 0) {
  42409. defines["MAINUV1"] = true;
  42410. }
  42411. else {
  42412. defines["MAINUV2"] = true;
  42413. }
  42414. }
  42415. else {
  42416. defines[key + "DIRECTUV"] = 0;
  42417. }
  42418. };
  42419. /**
  42420. * Binds a texture matrix value to its corrsponding uniform
  42421. * @param texture The texture to bind the matrix for
  42422. * @param uniformBuffer The uniform buffer receivin the data
  42423. * @param key The chanel key "diffuse", "specular"... used in the shader
  42424. */
  42425. MaterialHelper.BindTextureMatrix = function (texture, uniformBuffer, key) {
  42426. var matrix = texture.getTextureMatrix();
  42427. if (!matrix.isIdentity(true)) {
  42428. uniformBuffer.updateMatrix(key + "Matrix", matrix);
  42429. }
  42430. };
  42431. /**
  42432. * Helper used to prepare the list of defines associated with misc. values for shader compilation
  42433. * @param mesh defines the current mesh
  42434. * @param scene defines the current scene
  42435. * @param useLogarithmicDepth defines if logarithmic depth has to be turned on
  42436. * @param pointsCloud defines if point cloud rendering has to be turned on
  42437. * @param fogEnabled defines if fog has to be turned on
  42438. * @param alphaTest defines if alpha testing has to be turned on
  42439. * @param defines defines the current list of defines
  42440. */
  42441. MaterialHelper.PrepareDefinesForMisc = function (mesh, scene, useLogarithmicDepth, pointsCloud, fogEnabled, alphaTest, defines) {
  42442. if (defines._areMiscDirty) {
  42443. defines["LOGARITHMICDEPTH"] = useLogarithmicDepth;
  42444. defines["POINTSIZE"] = pointsCloud;
  42445. defines["FOG"] = (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && fogEnabled);
  42446. defines["NONUNIFORMSCALING"] = mesh.nonUniformScaling;
  42447. defines["ALPHATEST"] = alphaTest;
  42448. }
  42449. };
  42450. /**
  42451. * Helper used to prepare the list of defines associated with frame values for shader compilation
  42452. * @param scene defines the current scene
  42453. * @param engine defines the current engine
  42454. * @param defines specifies the list of active defines
  42455. * @param useInstances defines if instances have to be turned on
  42456. * @param useClipPlane defines if clip plane have to be turned on
  42457. */
  42458. MaterialHelper.PrepareDefinesForFrameBoundValues = function (scene, engine, defines, useInstances, useClipPlane) {
  42459. if (useClipPlane === void 0) { useClipPlane = null; }
  42460. var changed = false;
  42461. if (useClipPlane == null) {
  42462. useClipPlane = (scene.clipPlane !== undefined && scene.clipPlane !== null);
  42463. }
  42464. if (defines["CLIPPLANE"] !== useClipPlane) {
  42465. defines["CLIPPLANE"] = useClipPlane;
  42466. changed = true;
  42467. }
  42468. if (defines["DEPTHPREPASS"] !== !engine.getColorWrite()) {
  42469. defines["DEPTHPREPASS"] = !defines["DEPTHPREPASS"];
  42470. changed = true;
  42471. }
  42472. if (defines["INSTANCES"] !== useInstances) {
  42473. defines["INSTANCES"] = useInstances;
  42474. changed = true;
  42475. }
  42476. if (changed) {
  42477. defines.markAsUnprocessed();
  42478. }
  42479. };
  42480. /**
  42481. * Prepares the defines used in the shader depending on the attributes data available in the mesh
  42482. * @param mesh The mesh containing the geometry data we will draw
  42483. * @param defines The defines to update
  42484. * @param useVertexColor Precise whether vertex colors should be used or not (override mesh info)
  42485. * @param useBones Precise whether bones should be used or not (override mesh info)
  42486. * @param useMorphTargets Precise whether morph targets should be used or not (override mesh info)
  42487. * @param useVertexAlpha Precise whether vertex alpha should be used or not (override mesh info)
  42488. * @returns false if defines are considered not dirty and have not been checked
  42489. */
  42490. MaterialHelper.PrepareDefinesForAttributes = function (mesh, defines, useVertexColor, useBones, useMorphTargets, useVertexAlpha) {
  42491. if (useMorphTargets === void 0) { useMorphTargets = false; }
  42492. if (useVertexAlpha === void 0) { useVertexAlpha = true; }
  42493. if (!defines._areAttributesDirty && defines._needNormals === defines._normals && defines._needUVs === defines._uvs) {
  42494. return false;
  42495. }
  42496. defines._normals = defines._needNormals;
  42497. defines._uvs = defines._needUVs;
  42498. defines["NORMAL"] = (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  42499. if (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  42500. defines["TANGENT"] = true;
  42501. }
  42502. if (defines._needUVs) {
  42503. defines["UV1"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind);
  42504. defines["UV2"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind);
  42505. }
  42506. else {
  42507. defines["UV1"] = false;
  42508. defines["UV2"] = false;
  42509. }
  42510. if (useVertexColor) {
  42511. var hasVertexColors = mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind);
  42512. defines["VERTEXCOLOR"] = hasVertexColors;
  42513. defines["VERTEXALPHA"] = mesh.hasVertexAlpha && hasVertexColors && useVertexAlpha;
  42514. }
  42515. if (useBones) {
  42516. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  42517. defines["NUM_BONE_INFLUENCERS"] = mesh.numBoneInfluencers;
  42518. defines["BonesPerMesh"] = (mesh.skeleton.bones.length + 1);
  42519. }
  42520. else {
  42521. defines["NUM_BONE_INFLUENCERS"] = 0;
  42522. defines["BonesPerMesh"] = 0;
  42523. }
  42524. }
  42525. if (useMorphTargets) {
  42526. var manager = mesh.morphTargetManager;
  42527. if (manager) {
  42528. defines["MORPHTARGETS_TANGENT"] = manager.supportsTangents && defines["TANGENT"];
  42529. defines["MORPHTARGETS_NORMAL"] = manager.supportsNormals && defines["NORMAL"];
  42530. defines["MORPHTARGETS"] = (manager.numInfluencers > 0);
  42531. defines["NUM_MORPH_INFLUENCERS"] = manager.numInfluencers;
  42532. }
  42533. else {
  42534. defines["MORPHTARGETS_TANGENT"] = false;
  42535. defines["MORPHTARGETS_NORMAL"] = false;
  42536. defines["MORPHTARGETS"] = false;
  42537. defines["NUM_MORPH_INFLUENCERS"] = 0;
  42538. }
  42539. }
  42540. return true;
  42541. };
  42542. /**
  42543. * Prepares the defines related to the light information passed in parameter
  42544. * @param scene The scene we are intending to draw
  42545. * @param mesh The mesh the effect is compiling for
  42546. * @param defines The defines to update
  42547. * @param specularSupported Specifies whether specular is supported or not (override lights data)
  42548. * @param maxSimultaneousLights Specfies how manuy lights can be added to the effect at max
  42549. * @param disableLighting Specifies whether the lighting is disabled (override scene and light)
  42550. * @returns true if normals will be required for the rest of the effect
  42551. */
  42552. MaterialHelper.PrepareDefinesForLights = function (scene, mesh, defines, specularSupported, maxSimultaneousLights, disableLighting) {
  42553. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  42554. if (disableLighting === void 0) { disableLighting = false; }
  42555. if (!defines._areLightsDirty) {
  42556. return defines._needNormals;
  42557. }
  42558. var lightIndex = 0;
  42559. var needNormals = false;
  42560. var needRebuild = false;
  42561. var lightmapMode = false;
  42562. var shadowEnabled = false;
  42563. var specularEnabled = false;
  42564. if (scene.lightsEnabled && !disableLighting) {
  42565. for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) {
  42566. var light = _a[_i];
  42567. needNormals = true;
  42568. if (defines["LIGHT" + lightIndex] === undefined) {
  42569. needRebuild = true;
  42570. }
  42571. defines["LIGHT" + lightIndex] = true;
  42572. defines["SPOTLIGHT" + lightIndex] = false;
  42573. defines["HEMILIGHT" + lightIndex] = false;
  42574. defines["POINTLIGHT" + lightIndex] = false;
  42575. defines["DIRLIGHT" + lightIndex] = false;
  42576. var type;
  42577. if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_SPOTLIGHT) {
  42578. type = "SPOTLIGHT" + lightIndex;
  42579. var spotLight = light;
  42580. defines["PROJECTEDLIGHTTEXTURE" + lightIndex] = spotLight.projectionTexture ? true : false;
  42581. }
  42582. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT) {
  42583. type = "HEMILIGHT" + lightIndex;
  42584. }
  42585. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_POINTLIGHT) {
  42586. type = "POINTLIGHT" + lightIndex;
  42587. }
  42588. else {
  42589. type = "DIRLIGHT" + lightIndex;
  42590. }
  42591. defines[type] = true;
  42592. // Specular
  42593. if (specularSupported && !light.specular.equalsFloats(0, 0, 0)) {
  42594. specularEnabled = true;
  42595. }
  42596. // Shadows
  42597. defines["SHADOW" + lightIndex] = false;
  42598. defines["SHADOWPCF" + lightIndex] = false;
  42599. defines["SHADOWPCSS" + lightIndex] = false;
  42600. defines["SHADOWPOISSON" + lightIndex] = false;
  42601. defines["SHADOWESM" + lightIndex] = false;
  42602. defines["SHADOWCUBE" + lightIndex] = false;
  42603. defines["SHADOWLOWQUALITY" + lightIndex] = false;
  42604. defines["SHADOWMEDIUMQUALITY" + lightIndex] = false;
  42605. if (mesh && mesh.receiveShadows && scene.shadowsEnabled && light.shadowEnabled) {
  42606. var shadowGenerator = light.getShadowGenerator();
  42607. if (shadowGenerator) {
  42608. shadowEnabled = true;
  42609. shadowGenerator.prepareDefines(defines, lightIndex);
  42610. }
  42611. }
  42612. if (light.lightmapMode != BABYLON.Light.LIGHTMAP_DEFAULT) {
  42613. lightmapMode = true;
  42614. defines["LIGHTMAPEXCLUDED" + lightIndex] = true;
  42615. defines["LIGHTMAPNOSPECULAR" + lightIndex] = (light.lightmapMode == BABYLON.Light.LIGHTMAP_SHADOWSONLY);
  42616. }
  42617. else {
  42618. defines["LIGHTMAPEXCLUDED" + lightIndex] = false;
  42619. defines["LIGHTMAPNOSPECULAR" + lightIndex] = false;
  42620. }
  42621. lightIndex++;
  42622. if (lightIndex === maxSimultaneousLights)
  42623. break;
  42624. }
  42625. }
  42626. defines["SPECULARTERM"] = specularEnabled;
  42627. defines["SHADOWS"] = shadowEnabled;
  42628. // Resetting all other lights if any
  42629. for (var index = lightIndex; index < maxSimultaneousLights; index++) {
  42630. if (defines["LIGHT" + index] !== undefined) {
  42631. defines["LIGHT" + index] = false;
  42632. defines["HEMILIGHT" + lightIndex] = false;
  42633. defines["POINTLIGHT" + lightIndex] = false;
  42634. defines["DIRLIGHT" + lightIndex] = false;
  42635. defines["SPOTLIGHT" + lightIndex] = false;
  42636. defines["SHADOW" + lightIndex] = false;
  42637. }
  42638. }
  42639. var caps = scene.getEngine().getCaps();
  42640. if (defines["SHADOWFLOAT"] === undefined) {
  42641. needRebuild = true;
  42642. }
  42643. defines["SHADOWFLOAT"] = shadowEnabled &&
  42644. ((caps.textureFloatRender && caps.textureFloatLinearFiltering) ||
  42645. (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering));
  42646. defines["LIGHTMAPEXCLUDED"] = lightmapMode;
  42647. if (needRebuild) {
  42648. defines.rebuild();
  42649. }
  42650. return needNormals;
  42651. };
  42652. /**
  42653. * Prepares the uniforms and samplers list to be used in the effect. This can automatically remove from the list uniforms
  42654. * that won t be acctive due to defines being turned off.
  42655. * @param uniformsListOrOptions The uniform names to prepare or an EffectCreationOptions containing the liist and extra information
  42656. * @param samplersList The samplers list
  42657. * @param defines The defines helping in the list generation
  42658. * @param maxSimultaneousLights The maximum number of simultanous light allowed in the effect
  42659. */
  42660. MaterialHelper.PrepareUniformsAndSamplersList = function (uniformsListOrOptions, samplersList, defines, maxSimultaneousLights) {
  42661. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  42662. var uniformsList;
  42663. var uniformBuffersList = null;
  42664. if (uniformsListOrOptions.uniformsNames) {
  42665. var options = uniformsListOrOptions;
  42666. uniformsList = options.uniformsNames;
  42667. uniformBuffersList = options.uniformBuffersNames;
  42668. samplersList = options.samplers;
  42669. defines = options.defines;
  42670. maxSimultaneousLights = options.maxSimultaneousLights;
  42671. }
  42672. else {
  42673. uniformsList = uniformsListOrOptions;
  42674. if (!samplersList) {
  42675. samplersList = [];
  42676. }
  42677. }
  42678. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  42679. if (!defines["LIGHT" + lightIndex]) {
  42680. break;
  42681. }
  42682. uniformsList.push("vLightData" + lightIndex, "vLightDiffuse" + lightIndex, "vLightSpecular" + lightIndex, "vLightDirection" + lightIndex, "vLightGround" + lightIndex, "lightMatrix" + lightIndex, "shadowsInfo" + lightIndex, "depthValues" + lightIndex);
  42683. if (uniformBuffersList) {
  42684. uniformBuffersList.push("Light" + lightIndex);
  42685. }
  42686. samplersList.push("shadowSampler" + lightIndex);
  42687. samplersList.push("depthSampler" + lightIndex);
  42688. if (defines["PROJECTEDLIGHTTEXTURE" + lightIndex]) {
  42689. samplersList.push("projectionLightSampler" + lightIndex);
  42690. uniformsList.push("textureProjectionMatrix" + lightIndex);
  42691. }
  42692. }
  42693. if (defines["NUM_MORPH_INFLUENCERS"]) {
  42694. uniformsList.push("morphTargetInfluences");
  42695. }
  42696. };
  42697. /**
  42698. * This helps decreasing rank by rank the shadow quality (0 being the highest rank and quality)
  42699. * @param defines The defines to update while falling back
  42700. * @param fallbacks The authorized effect fallbacks
  42701. * @param maxSimultaneousLights The maximum number of lights allowed
  42702. * @param rank the current rank of the Effect
  42703. * @returns The newly affected rank
  42704. */
  42705. MaterialHelper.HandleFallbacksForShadows = function (defines, fallbacks, maxSimultaneousLights, rank) {
  42706. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  42707. if (rank === void 0) { rank = 0; }
  42708. var lightFallbackRank = 0;
  42709. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  42710. if (!defines["LIGHT" + lightIndex]) {
  42711. break;
  42712. }
  42713. if (lightIndex > 0) {
  42714. lightFallbackRank = rank + lightIndex;
  42715. fallbacks.addFallback(lightFallbackRank, "LIGHT" + lightIndex);
  42716. }
  42717. if (!defines["SHADOWS"]) {
  42718. if (defines["SHADOW" + lightIndex]) {
  42719. fallbacks.addFallback(rank, "SHADOW" + lightIndex);
  42720. }
  42721. if (defines["SHADOWPCF" + lightIndex]) {
  42722. fallbacks.addFallback(rank, "SHADOWPCF" + lightIndex);
  42723. }
  42724. if (defines["SHADOWPCSS" + lightIndex]) {
  42725. fallbacks.addFallback(rank, "SHADOWPCSS" + lightIndex);
  42726. }
  42727. if (defines["SHADOWPOISSON" + lightIndex]) {
  42728. fallbacks.addFallback(rank, "SHADOWPOISSON" + lightIndex);
  42729. }
  42730. if (defines["SHADOWESM" + lightIndex]) {
  42731. fallbacks.addFallback(rank, "SHADOWESM" + lightIndex);
  42732. }
  42733. }
  42734. }
  42735. return lightFallbackRank++;
  42736. };
  42737. /**
  42738. * Prepares the list of attributes required for morph targets according to the effect defines.
  42739. * @param attribs The current list of supported attribs
  42740. * @param mesh The mesh to prepare the morph targets attributes for
  42741. * @param defines The current Defines of the effect
  42742. */
  42743. MaterialHelper.PrepareAttributesForMorphTargets = function (attribs, mesh, defines) {
  42744. var influencers = defines["NUM_MORPH_INFLUENCERS"];
  42745. if (influencers > 0 && BABYLON.Engine.LastCreatedEngine) {
  42746. var maxAttributesCount = BABYLON.Engine.LastCreatedEngine.getCaps().maxVertexAttribs;
  42747. var manager = mesh.morphTargetManager;
  42748. var normal = manager && manager.supportsNormals && defines["NORMAL"];
  42749. var tangent = manager && manager.supportsTangents && defines["TANGENT"];
  42750. for (var index = 0; index < influencers; index++) {
  42751. attribs.push(BABYLON.VertexBuffer.PositionKind + index);
  42752. if (normal) {
  42753. attribs.push(BABYLON.VertexBuffer.NormalKind + index);
  42754. }
  42755. if (tangent) {
  42756. attribs.push(BABYLON.VertexBuffer.TangentKind + index);
  42757. }
  42758. if (attribs.length > maxAttributesCount) {
  42759. BABYLON.Tools.Error("Cannot add more vertex attributes for mesh " + mesh.name);
  42760. }
  42761. }
  42762. }
  42763. };
  42764. /**
  42765. * Prepares the list of attributes required for bones according to the effect defines.
  42766. * @param attribs The current list of supported attribs
  42767. * @param mesh The mesh to prepare the bones attributes for
  42768. * @param defines The current Defines of the effect
  42769. * @param fallbacks The current efffect fallback strategy
  42770. */
  42771. MaterialHelper.PrepareAttributesForBones = function (attribs, mesh, defines, fallbacks) {
  42772. if (defines["NUM_BONE_INFLUENCERS"] > 0) {
  42773. fallbacks.addCPUSkinningFallback(0, mesh);
  42774. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  42775. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  42776. if (defines["NUM_BONE_INFLUENCERS"] > 4) {
  42777. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  42778. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  42779. }
  42780. }
  42781. };
  42782. /**
  42783. * Prepares the list of attributes required for instances according to the effect defines.
  42784. * @param attribs The current list of supported attribs
  42785. * @param defines The current Defines of the effect
  42786. */
  42787. MaterialHelper.PrepareAttributesForInstances = function (attribs, defines) {
  42788. if (defines["INSTANCES"]) {
  42789. attribs.push("world0");
  42790. attribs.push("world1");
  42791. attribs.push("world2");
  42792. attribs.push("world3");
  42793. }
  42794. };
  42795. /**
  42796. * Binds the light shadow information to the effect for the given mesh.
  42797. * @param light The light containing the generator
  42798. * @param scene The scene the lights belongs to
  42799. * @param mesh The mesh we are binding the information to render
  42800. * @param lightIndex The light index in the effect used to render the mesh
  42801. * @param effect The effect we are binding the data to
  42802. */
  42803. MaterialHelper.BindLightShadow = function (light, scene, mesh, lightIndex, effect) {
  42804. if (light.shadowEnabled && mesh.receiveShadows) {
  42805. var shadowGenerator = light.getShadowGenerator();
  42806. if (shadowGenerator) {
  42807. shadowGenerator.bindShadowLight(lightIndex, effect);
  42808. }
  42809. }
  42810. };
  42811. /**
  42812. * Binds the light information to the effect.
  42813. * @param light The light containing the generator
  42814. * @param effect The effect we are binding the data to
  42815. * @param lightIndex The light index in the effect used to render
  42816. */
  42817. MaterialHelper.BindLightProperties = function (light, effect, lightIndex) {
  42818. light.transferToEffect(effect, lightIndex + "");
  42819. };
  42820. /**
  42821. * Binds the lights information from the scene to the effect for the given mesh.
  42822. * @param scene The scene the lights belongs to
  42823. * @param mesh The mesh we are binding the information to render
  42824. * @param effect The effect we are binding the data to
  42825. * @param defines The generated defines for the effect
  42826. * @param maxSimultaneousLights The maximum number of light that can be bound to the effect
  42827. * @param usePhysicalLightFalloff Specifies whether the light falloff is defined physically or not
  42828. */
  42829. MaterialHelper.BindLights = function (scene, mesh, effect, defines, maxSimultaneousLights, usePhysicalLightFalloff) {
  42830. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  42831. if (usePhysicalLightFalloff === void 0) { usePhysicalLightFalloff = false; }
  42832. var len = Math.min(mesh._lightSources.length, maxSimultaneousLights);
  42833. for (var i = 0; i < len; i++) {
  42834. var light = mesh._lightSources[i];
  42835. var iAsString = i.toString();
  42836. var scaledIntensity = light.getScaledIntensity();
  42837. light._uniformBuffer.bindToEffect(effect, "Light" + i);
  42838. MaterialHelper.BindLightProperties(light, effect, i);
  42839. light.diffuse.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[0]);
  42840. light._uniformBuffer.updateColor4("vLightDiffuse", BABYLON.Tmp.Color3[0], usePhysicalLightFalloff ? light.radius : light.range, iAsString);
  42841. if (defines["SPECULARTERM"]) {
  42842. light.specular.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[1]);
  42843. light._uniformBuffer.updateColor3("vLightSpecular", BABYLON.Tmp.Color3[1], iAsString);
  42844. }
  42845. // Shadows
  42846. if (scene.shadowsEnabled) {
  42847. this.BindLightShadow(light, scene, mesh, iAsString, effect);
  42848. }
  42849. light._uniformBuffer.update();
  42850. }
  42851. };
  42852. /**
  42853. * Binds the fog information from the scene to the effect for the given mesh.
  42854. * @param scene The scene the lights belongs to
  42855. * @param mesh The mesh we are binding the information to render
  42856. * @param effect The effect we are binding the data to
  42857. */
  42858. MaterialHelper.BindFogParameters = function (scene, mesh, effect) {
  42859. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  42860. effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  42861. effect.setColor3("vFogColor", scene.fogColor);
  42862. }
  42863. };
  42864. /**
  42865. * Binds the bones information from the mesh to the effect.
  42866. * @param mesh The mesh we are binding the information to render
  42867. * @param effect The effect we are binding the data to
  42868. */
  42869. MaterialHelper.BindBonesParameters = function (mesh, effect) {
  42870. if (!effect || !mesh) {
  42871. return;
  42872. }
  42873. if (mesh.computeBonesUsingShaders && effect._bonesComputationForcedToCPU) {
  42874. mesh.computeBonesUsingShaders = false;
  42875. }
  42876. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  42877. var matrices = mesh.skeleton.getTransformMatrices(mesh);
  42878. if (matrices) {
  42879. effect.setMatrices("mBones", matrices);
  42880. }
  42881. }
  42882. };
  42883. /**
  42884. * Binds the morph targets information from the mesh to the effect.
  42885. * @param abstractMesh The mesh we are binding the information to render
  42886. * @param effect The effect we are binding the data to
  42887. */
  42888. MaterialHelper.BindMorphTargetParameters = function (abstractMesh, effect) {
  42889. var manager = abstractMesh.morphTargetManager;
  42890. if (!abstractMesh || !manager) {
  42891. return;
  42892. }
  42893. effect.setFloatArray("morphTargetInfluences", manager.influences);
  42894. };
  42895. /**
  42896. * Binds the logarithmic depth information from the scene to the effect for the given defines.
  42897. * @param defines The generated defines used in the effect
  42898. * @param effect The effect we are binding the data to
  42899. * @param scene The scene we are willing to render with logarithmic scale for
  42900. */
  42901. MaterialHelper.BindLogDepth = function (defines, effect, scene) {
  42902. if (defines["LOGARITHMICDEPTH"]) {
  42903. effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  42904. }
  42905. };
  42906. /**
  42907. * Binds the clip plane information from the scene to the effect.
  42908. * @param scene The scene the clip plane information are extracted from
  42909. * @param effect The effect we are binding the data to
  42910. */
  42911. MaterialHelper.BindClipPlane = function (effect, scene) {
  42912. if (scene.clipPlane) {
  42913. var clipPlane = scene.clipPlane;
  42914. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  42915. }
  42916. };
  42917. return MaterialHelper;
  42918. }());
  42919. BABYLON.MaterialHelper = MaterialHelper;
  42920. })(BABYLON || (BABYLON = {}));
  42921. //# sourceMappingURL=babylon.materialHelper.js.map
  42922. var BABYLON;
  42923. (function (BABYLON) {
  42924. var PushMaterial = /** @class */ (function (_super) {
  42925. __extends(PushMaterial, _super);
  42926. function PushMaterial(name, scene) {
  42927. var _this = _super.call(this, name, scene) || this;
  42928. _this._normalMatrix = new BABYLON.Matrix();
  42929. _this.storeEffectOnSubMeshes = true;
  42930. return _this;
  42931. }
  42932. PushMaterial.prototype.getEffect = function () {
  42933. return this._activeEffect;
  42934. };
  42935. PushMaterial.prototype.isReady = function (mesh, useInstances) {
  42936. if (!mesh) {
  42937. return false;
  42938. }
  42939. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  42940. return true;
  42941. }
  42942. return this.isReadyForSubMesh(mesh, mesh.subMeshes[0], useInstances);
  42943. };
  42944. /**
  42945. * Binds the given world matrix to the active effect
  42946. *
  42947. * @param world the matrix to bind
  42948. */
  42949. PushMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  42950. this._activeEffect.setMatrix("world", world);
  42951. };
  42952. /**
  42953. * Binds the given normal matrix to the active effect
  42954. *
  42955. * @param normalMatrix the matrix to bind
  42956. */
  42957. PushMaterial.prototype.bindOnlyNormalMatrix = function (normalMatrix) {
  42958. this._activeEffect.setMatrix("normalMatrix", normalMatrix);
  42959. };
  42960. PushMaterial.prototype.bind = function (world, mesh) {
  42961. if (!mesh) {
  42962. return;
  42963. }
  42964. this.bindForSubMesh(world, mesh, mesh.subMeshes[0]);
  42965. };
  42966. PushMaterial.prototype._afterBind = function (mesh, effect) {
  42967. if (effect === void 0) { effect = null; }
  42968. _super.prototype._afterBind.call(this, mesh);
  42969. this.getScene()._cachedEffect = effect;
  42970. };
  42971. PushMaterial.prototype._mustRebind = function (scene, effect, visibility) {
  42972. if (visibility === void 0) { visibility = 1; }
  42973. return scene.isCachedMaterialInvalid(this, effect, visibility);
  42974. };
  42975. return PushMaterial;
  42976. }(BABYLON.Material));
  42977. BABYLON.PushMaterial = PushMaterial;
  42978. })(BABYLON || (BABYLON = {}));
  42979. //# sourceMappingURL=babylon.pushMaterial.js.map
  42980. var BABYLON;
  42981. (function (BABYLON) {
  42982. /** @hidden */
  42983. var StandardMaterialDefines = /** @class */ (function (_super) {
  42984. __extends(StandardMaterialDefines, _super);
  42985. function StandardMaterialDefines() {
  42986. var _this = _super.call(this) || this;
  42987. _this.MAINUV1 = false;
  42988. _this.MAINUV2 = false;
  42989. _this.DIFFUSE = false;
  42990. _this.DIFFUSEDIRECTUV = 0;
  42991. _this.AMBIENT = false;
  42992. _this.AMBIENTDIRECTUV = 0;
  42993. _this.OPACITY = false;
  42994. _this.OPACITYDIRECTUV = 0;
  42995. _this.OPACITYRGB = false;
  42996. _this.REFLECTION = false;
  42997. _this.EMISSIVE = false;
  42998. _this.EMISSIVEDIRECTUV = 0;
  42999. _this.SPECULAR = false;
  43000. _this.SPECULARDIRECTUV = 0;
  43001. _this.BUMP = false;
  43002. _this.BUMPDIRECTUV = 0;
  43003. _this.PARALLAX = false;
  43004. _this.PARALLAXOCCLUSION = false;
  43005. _this.SPECULAROVERALPHA = false;
  43006. _this.CLIPPLANE = false;
  43007. _this.ALPHATEST = false;
  43008. _this.DEPTHPREPASS = false;
  43009. _this.ALPHAFROMDIFFUSE = false;
  43010. _this.POINTSIZE = false;
  43011. _this.FOG = false;
  43012. _this.SPECULARTERM = false;
  43013. _this.DIFFUSEFRESNEL = false;
  43014. _this.OPACITYFRESNEL = false;
  43015. _this.REFLECTIONFRESNEL = false;
  43016. _this.REFRACTIONFRESNEL = false;
  43017. _this.EMISSIVEFRESNEL = false;
  43018. _this.FRESNEL = false;
  43019. _this.NORMAL = false;
  43020. _this.UV1 = false;
  43021. _this.UV2 = false;
  43022. _this.VERTEXCOLOR = false;
  43023. _this.VERTEXALPHA = false;
  43024. _this.NUM_BONE_INFLUENCERS = 0;
  43025. _this.BonesPerMesh = 0;
  43026. _this.INSTANCES = false;
  43027. _this.GLOSSINESS = false;
  43028. _this.ROUGHNESS = false;
  43029. _this.EMISSIVEASILLUMINATION = false;
  43030. _this.LINKEMISSIVEWITHDIFFUSE = false;
  43031. _this.REFLECTIONFRESNELFROMSPECULAR = false;
  43032. _this.LIGHTMAP = false;
  43033. _this.LIGHTMAPDIRECTUV = 0;
  43034. _this.OBJECTSPACE_NORMALMAP = false;
  43035. _this.USELIGHTMAPASSHADOWMAP = false;
  43036. _this.REFLECTIONMAP_3D = false;
  43037. _this.REFLECTIONMAP_SPHERICAL = false;
  43038. _this.REFLECTIONMAP_PLANAR = false;
  43039. _this.REFLECTIONMAP_CUBIC = false;
  43040. _this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  43041. _this.REFLECTIONMAP_PROJECTION = false;
  43042. _this.REFLECTIONMAP_SKYBOX = false;
  43043. _this.REFLECTIONMAP_EXPLICIT = false;
  43044. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  43045. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  43046. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  43047. _this.INVERTCUBICMAP = false;
  43048. _this.LOGARITHMICDEPTH = false;
  43049. _this.REFRACTION = false;
  43050. _this.REFRACTIONMAP_3D = false;
  43051. _this.REFLECTIONOVERALPHA = false;
  43052. _this.TWOSIDEDLIGHTING = false;
  43053. _this.SHADOWFLOAT = false;
  43054. _this.MORPHTARGETS = false;
  43055. _this.MORPHTARGETS_NORMAL = false;
  43056. _this.MORPHTARGETS_TANGENT = false;
  43057. _this.NUM_MORPH_INFLUENCERS = 0;
  43058. _this.NONUNIFORMSCALING = false; // https://playground.babylonjs.com#V6DWIH
  43059. _this.PREMULTIPLYALPHA = false; // https://playground.babylonjs.com#LNVJJ7
  43060. _this.IMAGEPROCESSING = false;
  43061. _this.VIGNETTE = false;
  43062. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  43063. _this.VIGNETTEBLENDMODEOPAQUE = false;
  43064. _this.TONEMAPPING = false;
  43065. _this.CONTRAST = false;
  43066. _this.COLORCURVES = false;
  43067. _this.COLORGRADING = false;
  43068. _this.COLORGRADING3D = false;
  43069. _this.SAMPLER3DGREENDEPTH = false;
  43070. _this.SAMPLER3DBGRMAP = false;
  43071. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  43072. /**
  43073. * If the reflection texture on this material is in linear color space
  43074. * @hidden
  43075. */
  43076. _this.IS_REFLECTION_LINEAR = false;
  43077. /**
  43078. * If the refraction texture on this material is in linear color space
  43079. * @hidden
  43080. */
  43081. _this.IS_REFRACTION_LINEAR = false;
  43082. _this.EXPOSURE = false;
  43083. _this.rebuild();
  43084. return _this;
  43085. }
  43086. StandardMaterialDefines.prototype.setReflectionMode = function (modeToEnable) {
  43087. var modes = [
  43088. "REFLECTIONMAP_CUBIC", "REFLECTIONMAP_EXPLICIT", "REFLECTIONMAP_PLANAR",
  43089. "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_SKYBOX",
  43090. "REFLECTIONMAP_SPHERICAL", "REFLECTIONMAP_EQUIRECTANGULAR", "REFLECTIONMAP_EQUIRECTANGULAR_FIXED",
  43091. "REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED"
  43092. ];
  43093. for (var _i = 0, modes_1 = modes; _i < modes_1.length; _i++) {
  43094. var mode = modes_1[_i];
  43095. this[mode] = (mode === modeToEnable);
  43096. }
  43097. };
  43098. return StandardMaterialDefines;
  43099. }(BABYLON.MaterialDefines));
  43100. BABYLON.StandardMaterialDefines = StandardMaterialDefines;
  43101. var StandardMaterial = /** @class */ (function (_super) {
  43102. __extends(StandardMaterial, _super);
  43103. function StandardMaterial(name, scene) {
  43104. var _this = _super.call(this, name, scene) || this;
  43105. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  43106. _this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  43107. _this.specularColor = new BABYLON.Color3(1, 1, 1);
  43108. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  43109. _this.specularPower = 64;
  43110. _this._useAlphaFromDiffuseTexture = false;
  43111. _this._useEmissiveAsIllumination = false;
  43112. _this._linkEmissiveWithDiffuse = false;
  43113. _this._useSpecularOverAlpha = false;
  43114. _this._useReflectionOverAlpha = false;
  43115. _this._disableLighting = false;
  43116. _this._useObjectSpaceNormalMap = false;
  43117. _this._useParallax = false;
  43118. _this._useParallaxOcclusion = false;
  43119. _this.parallaxScaleBias = 0.05;
  43120. _this._roughness = 0;
  43121. _this.indexOfRefraction = 0.98;
  43122. _this.invertRefractionY = true;
  43123. /**
  43124. * Defines the alpha limits in alpha test mode
  43125. */
  43126. _this.alphaCutOff = 0.4;
  43127. _this._useLightmapAsShadowmap = false;
  43128. _this._useReflectionFresnelFromSpecular = false;
  43129. _this._useGlossinessFromSpecularMapAlpha = false;
  43130. _this._maxSimultaneousLights = 4;
  43131. /**
  43132. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  43133. */
  43134. _this._invertNormalMapX = false;
  43135. /**
  43136. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  43137. */
  43138. _this._invertNormalMapY = false;
  43139. /**
  43140. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  43141. */
  43142. _this._twoSidedLighting = false;
  43143. _this._renderTargets = new BABYLON.SmartArray(16);
  43144. _this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  43145. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  43146. // Setup the default processing configuration to the scene.
  43147. _this._attachImageProcessingConfiguration(null);
  43148. _this.getRenderTargetTextures = function () {
  43149. _this._renderTargets.reset();
  43150. if (StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  43151. _this._renderTargets.push(_this._reflectionTexture);
  43152. }
  43153. if (StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  43154. _this._renderTargets.push(_this._refractionTexture);
  43155. }
  43156. return _this._renderTargets;
  43157. };
  43158. return _this;
  43159. }
  43160. Object.defineProperty(StandardMaterial.prototype, "imageProcessingConfiguration", {
  43161. /**
  43162. * Gets the image processing configuration used either in this material.
  43163. */
  43164. get: function () {
  43165. return this._imageProcessingConfiguration;
  43166. },
  43167. /**
  43168. * Sets the Default image processing configuration used either in the this material.
  43169. *
  43170. * If sets to null, the scene one is in use.
  43171. */
  43172. set: function (value) {
  43173. this._attachImageProcessingConfiguration(value);
  43174. // Ensure the effect will be rebuilt.
  43175. this._markAllSubMeshesAsTexturesDirty();
  43176. },
  43177. enumerable: true,
  43178. configurable: true
  43179. });
  43180. /**
  43181. * Attaches a new image processing configuration to the Standard Material.
  43182. * @param configuration
  43183. */
  43184. StandardMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  43185. var _this = this;
  43186. if (configuration === this._imageProcessingConfiguration) {
  43187. return;
  43188. }
  43189. // Detaches observer.
  43190. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  43191. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  43192. }
  43193. // Pick the scene configuration if needed.
  43194. if (!configuration) {
  43195. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  43196. }
  43197. else {
  43198. this._imageProcessingConfiguration = configuration;
  43199. }
  43200. // Attaches observer.
  43201. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  43202. _this._markAllSubMeshesAsImageProcessingDirty();
  43203. });
  43204. };
  43205. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurvesEnabled", {
  43206. /**
  43207. * Gets wether the color curves effect is enabled.
  43208. */
  43209. get: function () {
  43210. return this.imageProcessingConfiguration.colorCurvesEnabled;
  43211. },
  43212. /**
  43213. * Sets wether the color curves effect is enabled.
  43214. */
  43215. set: function (value) {
  43216. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  43217. },
  43218. enumerable: true,
  43219. configurable: true
  43220. });
  43221. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingEnabled", {
  43222. /**
  43223. * Gets wether the color grading effect is enabled.
  43224. */
  43225. get: function () {
  43226. return this.imageProcessingConfiguration.colorGradingEnabled;
  43227. },
  43228. /**
  43229. * Gets wether the color grading effect is enabled.
  43230. */
  43231. set: function (value) {
  43232. this.imageProcessingConfiguration.colorGradingEnabled = value;
  43233. },
  43234. enumerable: true,
  43235. configurable: true
  43236. });
  43237. Object.defineProperty(StandardMaterial.prototype, "cameraToneMappingEnabled", {
  43238. /**
  43239. * Gets wether tonemapping is enabled or not.
  43240. */
  43241. get: function () {
  43242. return this._imageProcessingConfiguration.toneMappingEnabled;
  43243. },
  43244. /**
  43245. * Sets wether tonemapping is enabled or not
  43246. */
  43247. set: function (value) {
  43248. this._imageProcessingConfiguration.toneMappingEnabled = value;
  43249. },
  43250. enumerable: true,
  43251. configurable: true
  43252. });
  43253. ;
  43254. ;
  43255. Object.defineProperty(StandardMaterial.prototype, "cameraExposure", {
  43256. /**
  43257. * The camera exposure used on this material.
  43258. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  43259. * This corresponds to a photographic exposure.
  43260. */
  43261. get: function () {
  43262. return this._imageProcessingConfiguration.exposure;
  43263. },
  43264. /**
  43265. * The camera exposure used on this material.
  43266. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  43267. * This corresponds to a photographic exposure.
  43268. */
  43269. set: function (value) {
  43270. this._imageProcessingConfiguration.exposure = value;
  43271. },
  43272. enumerable: true,
  43273. configurable: true
  43274. });
  43275. ;
  43276. ;
  43277. Object.defineProperty(StandardMaterial.prototype, "cameraContrast", {
  43278. /**
  43279. * Gets The camera contrast used on this material.
  43280. */
  43281. get: function () {
  43282. return this._imageProcessingConfiguration.contrast;
  43283. },
  43284. /**
  43285. * Sets The camera contrast used on this material.
  43286. */
  43287. set: function (value) {
  43288. this._imageProcessingConfiguration.contrast = value;
  43289. },
  43290. enumerable: true,
  43291. configurable: true
  43292. });
  43293. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingTexture", {
  43294. /**
  43295. * Gets the Color Grading 2D Lookup Texture.
  43296. */
  43297. get: function () {
  43298. return this._imageProcessingConfiguration.colorGradingTexture;
  43299. },
  43300. /**
  43301. * Sets the Color Grading 2D Lookup Texture.
  43302. */
  43303. set: function (value) {
  43304. this._imageProcessingConfiguration.colorGradingTexture = value;
  43305. },
  43306. enumerable: true,
  43307. configurable: true
  43308. });
  43309. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurves", {
  43310. /**
  43311. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  43312. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  43313. * 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;
  43314. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  43315. */
  43316. get: function () {
  43317. return this._imageProcessingConfiguration.colorCurves;
  43318. },
  43319. /**
  43320. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  43321. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  43322. * 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;
  43323. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  43324. */
  43325. set: function (value) {
  43326. this._imageProcessingConfiguration.colorCurves = value;
  43327. },
  43328. enumerable: true,
  43329. configurable: true
  43330. });
  43331. StandardMaterial.prototype.getClassName = function () {
  43332. return "StandardMaterial";
  43333. };
  43334. Object.defineProperty(StandardMaterial.prototype, "useLogarithmicDepth", {
  43335. get: function () {
  43336. return this._useLogarithmicDepth;
  43337. },
  43338. set: function (value) {
  43339. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  43340. this._markAllSubMeshesAsMiscDirty();
  43341. },
  43342. enumerable: true,
  43343. configurable: true
  43344. });
  43345. StandardMaterial.prototype.needAlphaBlending = function () {
  43346. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled;
  43347. };
  43348. StandardMaterial.prototype.needAlphaTesting = function () {
  43349. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha;
  43350. };
  43351. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  43352. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha && this._useAlphaFromDiffuseTexture;
  43353. };
  43354. StandardMaterial.prototype.getAlphaTestTexture = function () {
  43355. return this._diffuseTexture;
  43356. };
  43357. /**
  43358. * Child classes can use it to update shaders
  43359. */
  43360. StandardMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  43361. if (useInstances === void 0) { useInstances = false; }
  43362. if (subMesh.effect && this.isFrozen) {
  43363. if (this._wasPreviouslyReady && subMesh.effect) {
  43364. return true;
  43365. }
  43366. }
  43367. if (!subMesh._materialDefines) {
  43368. subMesh._materialDefines = new StandardMaterialDefines();
  43369. }
  43370. var scene = this.getScene();
  43371. var defines = subMesh._materialDefines;
  43372. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  43373. if (defines._renderId === scene.getRenderId()) {
  43374. return true;
  43375. }
  43376. }
  43377. var engine = scene.getEngine();
  43378. // Lights
  43379. defines._needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  43380. // Textures
  43381. if (defines._areTexturesDirty) {
  43382. defines._needUVs = false;
  43383. defines.MAINUV1 = false;
  43384. defines.MAINUV2 = false;
  43385. if (scene.texturesEnabled) {
  43386. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  43387. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  43388. return false;
  43389. }
  43390. else {
  43391. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  43392. }
  43393. }
  43394. else {
  43395. defines.DIFFUSE = false;
  43396. }
  43397. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  43398. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  43399. return false;
  43400. }
  43401. else {
  43402. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  43403. }
  43404. }
  43405. else {
  43406. defines.AMBIENT = false;
  43407. }
  43408. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  43409. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  43410. return false;
  43411. }
  43412. else {
  43413. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  43414. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  43415. }
  43416. }
  43417. else {
  43418. defines.OPACITY = false;
  43419. }
  43420. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  43421. if (!this._reflectionTexture.isReadyOrNotBlocking()) {
  43422. return false;
  43423. }
  43424. else {
  43425. defines._needNormals = true;
  43426. defines.REFLECTION = true;
  43427. defines.ROUGHNESS = (this._roughness > 0);
  43428. defines.REFLECTIONOVERALPHA = this._useReflectionOverAlpha;
  43429. defines.INVERTCUBICMAP = (this._reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE);
  43430. defines.REFLECTIONMAP_3D = this._reflectionTexture.isCube;
  43431. switch (this._reflectionTexture.coordinatesMode) {
  43432. case BABYLON.Texture.EXPLICIT_MODE:
  43433. defines.setReflectionMode("REFLECTIONMAP_EXPLICIT");
  43434. break;
  43435. case BABYLON.Texture.PLANAR_MODE:
  43436. defines.setReflectionMode("REFLECTIONMAP_PLANAR");
  43437. break;
  43438. case BABYLON.Texture.PROJECTION_MODE:
  43439. defines.setReflectionMode("REFLECTIONMAP_PROJECTION");
  43440. break;
  43441. case BABYLON.Texture.SKYBOX_MODE:
  43442. defines.setReflectionMode("REFLECTIONMAP_SKYBOX");
  43443. break;
  43444. case BABYLON.Texture.SPHERICAL_MODE:
  43445. defines.setReflectionMode("REFLECTIONMAP_SPHERICAL");
  43446. break;
  43447. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  43448. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR");
  43449. break;
  43450. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  43451. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR_FIXED");
  43452. break;
  43453. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  43454. defines.setReflectionMode("REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED");
  43455. break;
  43456. case BABYLON.Texture.CUBIC_MODE:
  43457. case BABYLON.Texture.INVCUBIC_MODE:
  43458. default:
  43459. defines.setReflectionMode("REFLECTIONMAP_CUBIC");
  43460. break;
  43461. }
  43462. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = this._reflectionTexture.boundingBoxSize ? true : false;
  43463. }
  43464. }
  43465. else {
  43466. defines.REFLECTION = false;
  43467. }
  43468. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  43469. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  43470. return false;
  43471. }
  43472. else {
  43473. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  43474. }
  43475. }
  43476. else {
  43477. defines.EMISSIVE = false;
  43478. }
  43479. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  43480. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  43481. return false;
  43482. }
  43483. else {
  43484. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  43485. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  43486. }
  43487. }
  43488. else {
  43489. defines.LIGHTMAP = false;
  43490. }
  43491. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  43492. if (!this._specularTexture.isReadyOrNotBlocking()) {
  43493. return false;
  43494. }
  43495. else {
  43496. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._specularTexture, defines, "SPECULAR");
  43497. defines.GLOSSINESS = this._useGlossinessFromSpecularMapAlpha;
  43498. }
  43499. }
  43500. else {
  43501. defines.SPECULAR = false;
  43502. }
  43503. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && StandardMaterial.BumpTextureEnabled) {
  43504. // Bump texure can not be not blocking.
  43505. if (!this._bumpTexture.isReady()) {
  43506. return false;
  43507. }
  43508. else {
  43509. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  43510. defines.PARALLAX = this._useParallax;
  43511. defines.PARALLAXOCCLUSION = this._useParallaxOcclusion;
  43512. }
  43513. defines.OBJECTSPACE_NORMALMAP = this._useObjectSpaceNormalMap;
  43514. }
  43515. else {
  43516. defines.BUMP = false;
  43517. }
  43518. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  43519. if (!this._refractionTexture.isReadyOrNotBlocking()) {
  43520. return false;
  43521. }
  43522. else {
  43523. defines._needUVs = true;
  43524. defines.REFRACTION = true;
  43525. defines.REFRACTIONMAP_3D = this._refractionTexture.isCube;
  43526. }
  43527. }
  43528. else {
  43529. defines.REFRACTION = false;
  43530. }
  43531. defines.TWOSIDEDLIGHTING = !this._backFaceCulling && this._twoSidedLighting;
  43532. }
  43533. else {
  43534. defines.DIFFUSE = false;
  43535. defines.AMBIENT = false;
  43536. defines.OPACITY = false;
  43537. defines.REFLECTION = false;
  43538. defines.EMISSIVE = false;
  43539. defines.LIGHTMAP = false;
  43540. defines.BUMP = false;
  43541. defines.REFRACTION = false;
  43542. }
  43543. defines.ALPHAFROMDIFFUSE = this._shouldUseAlphaFromDiffuseTexture();
  43544. defines.EMISSIVEASILLUMINATION = this._useEmissiveAsIllumination;
  43545. defines.LINKEMISSIVEWITHDIFFUSE = this._linkEmissiveWithDiffuse;
  43546. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  43547. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  43548. }
  43549. if (defines._areImageProcessingDirty) {
  43550. if (!this._imageProcessingConfiguration.isReady()) {
  43551. return false;
  43552. }
  43553. this._imageProcessingConfiguration.prepareDefines(defines);
  43554. defines.IS_REFLECTION_LINEAR = (this.reflectionTexture != null && !this.reflectionTexture.gammaSpace);
  43555. defines.IS_REFRACTION_LINEAR = (this.refractionTexture != null && !this.refractionTexture.gammaSpace);
  43556. }
  43557. if (defines._areFresnelDirty) {
  43558. if (StandardMaterial.FresnelEnabled) {
  43559. // Fresnel
  43560. if (this._diffuseFresnelParameters || this._opacityFresnelParameters ||
  43561. this._emissiveFresnelParameters || this._refractionFresnelParameters ||
  43562. this._reflectionFresnelParameters) {
  43563. defines.DIFFUSEFRESNEL = (this._diffuseFresnelParameters && this._diffuseFresnelParameters.isEnabled);
  43564. defines.OPACITYFRESNEL = (this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled);
  43565. defines.REFLECTIONFRESNEL = (this._reflectionFresnelParameters && this._reflectionFresnelParameters.isEnabled);
  43566. defines.REFLECTIONFRESNELFROMSPECULAR = this._useReflectionFresnelFromSpecular;
  43567. defines.REFRACTIONFRESNEL = (this._refractionFresnelParameters && this._refractionFresnelParameters.isEnabled);
  43568. defines.EMISSIVEFRESNEL = (this._emissiveFresnelParameters && this._emissiveFresnelParameters.isEnabled);
  43569. defines._needNormals = true;
  43570. defines.FRESNEL = true;
  43571. }
  43572. }
  43573. else {
  43574. defines.FRESNEL = false;
  43575. }
  43576. }
  43577. // Misc.
  43578. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  43579. // Attribs
  43580. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true);
  43581. // Values that need to be evaluated on every frame
  43582. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  43583. // Get correct effect
  43584. if (defines.isDirty) {
  43585. defines.markAsProcessed();
  43586. scene.resetCachedMaterial();
  43587. // Fallbacks
  43588. var fallbacks = new BABYLON.EffectFallbacks();
  43589. if (defines.REFLECTION) {
  43590. fallbacks.addFallback(0, "REFLECTION");
  43591. }
  43592. if (defines.SPECULAR) {
  43593. fallbacks.addFallback(0, "SPECULAR");
  43594. }
  43595. if (defines.BUMP) {
  43596. fallbacks.addFallback(0, "BUMP");
  43597. }
  43598. if (defines.PARALLAX) {
  43599. fallbacks.addFallback(1, "PARALLAX");
  43600. }
  43601. if (defines.PARALLAXOCCLUSION) {
  43602. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  43603. }
  43604. if (defines.SPECULAROVERALPHA) {
  43605. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  43606. }
  43607. if (defines.FOG) {
  43608. fallbacks.addFallback(1, "FOG");
  43609. }
  43610. if (defines.POINTSIZE) {
  43611. fallbacks.addFallback(0, "POINTSIZE");
  43612. }
  43613. if (defines.LOGARITHMICDEPTH) {
  43614. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  43615. }
  43616. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  43617. if (defines.SPECULARTERM) {
  43618. fallbacks.addFallback(0, "SPECULARTERM");
  43619. }
  43620. if (defines.DIFFUSEFRESNEL) {
  43621. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  43622. }
  43623. if (defines.OPACITYFRESNEL) {
  43624. fallbacks.addFallback(2, "OPACITYFRESNEL");
  43625. }
  43626. if (defines.REFLECTIONFRESNEL) {
  43627. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  43628. }
  43629. if (defines.EMISSIVEFRESNEL) {
  43630. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  43631. }
  43632. if (defines.FRESNEL) {
  43633. fallbacks.addFallback(4, "FRESNEL");
  43634. }
  43635. //Attributes
  43636. var attribs = [BABYLON.VertexBuffer.PositionKind];
  43637. if (defines.NORMAL) {
  43638. attribs.push(BABYLON.VertexBuffer.NormalKind);
  43639. }
  43640. if (defines.UV1) {
  43641. attribs.push(BABYLON.VertexBuffer.UVKind);
  43642. }
  43643. if (defines.UV2) {
  43644. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  43645. }
  43646. if (defines.VERTEXCOLOR) {
  43647. attribs.push(BABYLON.VertexBuffer.ColorKind);
  43648. }
  43649. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  43650. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  43651. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  43652. var shaderName = "default";
  43653. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  43654. "vFogInfos", "vFogColor", "pointSize",
  43655. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  43656. "mBones",
  43657. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "normalMatrix", "lightmapMatrix", "refractionMatrix",
  43658. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor", "refractionLeftColor", "refractionRightColor",
  43659. "vReflectionPosition", "vReflectionSize",
  43660. "logarithmicDepthConstant", "vTangentSpaceParams", "alphaCutOff"
  43661. ];
  43662. var samplers = ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  43663. var uniformBuffers = ["Material", "Scene"];
  43664. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  43665. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  43666. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  43667. uniformsNames: uniforms,
  43668. uniformBuffersNames: uniformBuffers,
  43669. samplers: samplers,
  43670. defines: defines,
  43671. maxSimultaneousLights: this._maxSimultaneousLights
  43672. });
  43673. if (this.customShaderNameResolve) {
  43674. shaderName = this.customShaderNameResolve(shaderName, uniforms, uniformBuffers, samplers, defines);
  43675. }
  43676. var join = defines.toString();
  43677. subMesh.setEffect(scene.getEngine().createEffect(shaderName, {
  43678. attributes: attribs,
  43679. uniformsNames: uniforms,
  43680. uniformBuffersNames: uniformBuffers,
  43681. samplers: samplers,
  43682. defines: join,
  43683. fallbacks: fallbacks,
  43684. onCompiled: this.onCompiled,
  43685. onError: this.onError,
  43686. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  43687. }, engine), defines);
  43688. this.buildUniformLayout();
  43689. }
  43690. if (!subMesh.effect || !subMesh.effect.isReady()) {
  43691. return false;
  43692. }
  43693. defines._renderId = scene.getRenderId();
  43694. this._wasPreviouslyReady = true;
  43695. return true;
  43696. };
  43697. StandardMaterial.prototype.buildUniformLayout = function () {
  43698. // Order is important !
  43699. this._uniformBuffer.addUniform("diffuseLeftColor", 4);
  43700. this._uniformBuffer.addUniform("diffuseRightColor", 4);
  43701. this._uniformBuffer.addUniform("opacityParts", 4);
  43702. this._uniformBuffer.addUniform("reflectionLeftColor", 4);
  43703. this._uniformBuffer.addUniform("reflectionRightColor", 4);
  43704. this._uniformBuffer.addUniform("refractionLeftColor", 4);
  43705. this._uniformBuffer.addUniform("refractionRightColor", 4);
  43706. this._uniformBuffer.addUniform("emissiveLeftColor", 4);
  43707. this._uniformBuffer.addUniform("emissiveRightColor", 4);
  43708. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  43709. this._uniformBuffer.addUniform("vAmbientInfos", 2);
  43710. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  43711. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  43712. this._uniformBuffer.addUniform("vReflectionPosition", 3);
  43713. this._uniformBuffer.addUniform("vReflectionSize", 3);
  43714. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  43715. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  43716. this._uniformBuffer.addUniform("vSpecularInfos", 2);
  43717. this._uniformBuffer.addUniform("vBumpInfos", 3);
  43718. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  43719. this._uniformBuffer.addUniform("ambientMatrix", 16);
  43720. this._uniformBuffer.addUniform("opacityMatrix", 16);
  43721. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  43722. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  43723. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  43724. this._uniformBuffer.addUniform("specularMatrix", 16);
  43725. this._uniformBuffer.addUniform("bumpMatrix", 16);
  43726. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  43727. this._uniformBuffer.addUniform("refractionMatrix", 16);
  43728. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  43729. this._uniformBuffer.addUniform("vSpecularColor", 4);
  43730. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  43731. this._uniformBuffer.addUniform("vDiffuseColor", 4);
  43732. this._uniformBuffer.addUniform("pointSize", 1);
  43733. this._uniformBuffer.create();
  43734. };
  43735. StandardMaterial.prototype.unbind = function () {
  43736. if (this._activeEffect) {
  43737. var needFlag = false;
  43738. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  43739. this._activeEffect.setTexture("reflection2DSampler", null);
  43740. needFlag = true;
  43741. }
  43742. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  43743. this._activeEffect.setTexture("refraction2DSampler", null);
  43744. needFlag = true;
  43745. }
  43746. if (needFlag) {
  43747. this._markAllSubMeshesAsTexturesDirty();
  43748. }
  43749. }
  43750. _super.prototype.unbind.call(this);
  43751. };
  43752. StandardMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  43753. var scene = this.getScene();
  43754. var defines = subMesh._materialDefines;
  43755. if (!defines) {
  43756. return;
  43757. }
  43758. var effect = subMesh.effect;
  43759. if (!effect) {
  43760. return;
  43761. }
  43762. this._activeEffect = effect;
  43763. // Matrices
  43764. this.bindOnlyWorldMatrix(world);
  43765. // Normal Matrix
  43766. if (defines.OBJECTSPACE_NORMALMAP) {
  43767. world.toNormalMatrix(this._normalMatrix);
  43768. this.bindOnlyNormalMatrix(this._normalMatrix);
  43769. }
  43770. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  43771. // Bones
  43772. BABYLON.MaterialHelper.BindBonesParameters(mesh, effect);
  43773. if (mustRebind) {
  43774. this._uniformBuffer.bindToEffect(effect, "Material");
  43775. this.bindViewProjection(effect);
  43776. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  43777. if (StandardMaterial.FresnelEnabled && defines.FRESNEL) {
  43778. // Fresnel
  43779. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  43780. this._uniformBuffer.updateColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  43781. this._uniformBuffer.updateColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  43782. }
  43783. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  43784. this._uniformBuffer.updateColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  43785. }
  43786. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  43787. this._uniformBuffer.updateColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  43788. this._uniformBuffer.updateColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  43789. }
  43790. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  43791. this._uniformBuffer.updateColor4("refractionLeftColor", this.refractionFresnelParameters.leftColor, this.refractionFresnelParameters.power);
  43792. this._uniformBuffer.updateColor4("refractionRightColor", this.refractionFresnelParameters.rightColor, this.refractionFresnelParameters.bias);
  43793. }
  43794. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  43795. this._uniformBuffer.updateColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  43796. this._uniformBuffer.updateColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  43797. }
  43798. }
  43799. // Textures
  43800. if (scene.texturesEnabled) {
  43801. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  43802. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  43803. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  43804. if (this._diffuseTexture.hasAlpha) {
  43805. effect.setFloat("alphaCutOff", this.alphaCutOff);
  43806. }
  43807. }
  43808. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  43809. this._uniformBuffer.updateFloat2("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level);
  43810. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  43811. }
  43812. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  43813. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  43814. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  43815. }
  43816. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  43817. this._uniformBuffer.updateFloat2("vReflectionInfos", this._reflectionTexture.level, this.roughness);
  43818. this._uniformBuffer.updateMatrix("reflectionMatrix", this._reflectionTexture.getReflectionTextureMatrix());
  43819. if (this._reflectionTexture.boundingBoxSize) {
  43820. var cubeTexture = this._reflectionTexture;
  43821. this._uniformBuffer.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition);
  43822. this._uniformBuffer.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize);
  43823. }
  43824. }
  43825. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  43826. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  43827. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  43828. }
  43829. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  43830. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  43831. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  43832. }
  43833. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  43834. this._uniformBuffer.updateFloat2("vSpecularInfos", this._specularTexture.coordinatesIndex, this._specularTexture.level);
  43835. BABYLON.MaterialHelper.BindTextureMatrix(this._specularTexture, this._uniformBuffer, "specular");
  43836. }
  43837. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  43838. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, 1.0 / this._bumpTexture.level, this.parallaxScaleBias);
  43839. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  43840. if (scene._mirroredCameraPosition) {
  43841. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  43842. }
  43843. else {
  43844. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  43845. }
  43846. }
  43847. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  43848. var depth = 1.0;
  43849. if (!this._refractionTexture.isCube) {
  43850. this._uniformBuffer.updateMatrix("refractionMatrix", this._refractionTexture.getReflectionTextureMatrix());
  43851. if (this._refractionTexture.depth) {
  43852. depth = this._refractionTexture.depth;
  43853. }
  43854. }
  43855. this._uniformBuffer.updateFloat4("vRefractionInfos", this._refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  43856. }
  43857. }
  43858. // Point size
  43859. if (this.pointsCloud) {
  43860. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  43861. }
  43862. if (defines.SPECULARTERM) {
  43863. this._uniformBuffer.updateColor4("vSpecularColor", this.specularColor, this.specularPower);
  43864. }
  43865. this._uniformBuffer.updateColor3("vEmissiveColor", this.emissiveColor);
  43866. // Diffuse
  43867. this._uniformBuffer.updateColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  43868. }
  43869. // Textures
  43870. if (scene.texturesEnabled) {
  43871. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  43872. effect.setTexture("diffuseSampler", this._diffuseTexture);
  43873. }
  43874. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  43875. effect.setTexture("ambientSampler", this._ambientTexture);
  43876. }
  43877. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  43878. effect.setTexture("opacitySampler", this._opacityTexture);
  43879. }
  43880. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  43881. if (this._reflectionTexture.isCube) {
  43882. effect.setTexture("reflectionCubeSampler", this._reflectionTexture);
  43883. }
  43884. else {
  43885. effect.setTexture("reflection2DSampler", this._reflectionTexture);
  43886. }
  43887. }
  43888. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  43889. effect.setTexture("emissiveSampler", this._emissiveTexture);
  43890. }
  43891. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  43892. effect.setTexture("lightmapSampler", this._lightmapTexture);
  43893. }
  43894. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  43895. effect.setTexture("specularSampler", this._specularTexture);
  43896. }
  43897. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  43898. effect.setTexture("bumpSampler", this._bumpTexture);
  43899. }
  43900. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  43901. var depth = 1.0;
  43902. if (this._refractionTexture.isCube) {
  43903. effect.setTexture("refractionCubeSampler", this._refractionTexture);
  43904. }
  43905. else {
  43906. effect.setTexture("refraction2DSampler", this._refractionTexture);
  43907. }
  43908. }
  43909. }
  43910. // Clip plane
  43911. BABYLON.MaterialHelper.BindClipPlane(effect, scene);
  43912. // Colors
  43913. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  43914. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  43915. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  43916. }
  43917. if (mustRebind || !this.isFrozen) {
  43918. // Lights
  43919. if (scene.lightsEnabled && !this._disableLighting) {
  43920. BABYLON.MaterialHelper.BindLights(scene, mesh, effect, defines, this._maxSimultaneousLights);
  43921. }
  43922. // View
  43923. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this._reflectionTexture || this._refractionTexture) {
  43924. this.bindView(effect);
  43925. }
  43926. // Fog
  43927. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, effect);
  43928. // Morph targets
  43929. if (defines.NUM_MORPH_INFLUENCERS) {
  43930. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, effect);
  43931. }
  43932. // Log. depth
  43933. BABYLON.MaterialHelper.BindLogDepth(defines, effect, scene);
  43934. // image processing
  43935. if (!this._imageProcessingConfiguration.applyByPostProcess) {
  43936. this._imageProcessingConfiguration.bind(this._activeEffect);
  43937. }
  43938. }
  43939. this._uniformBuffer.update();
  43940. this._afterBind(mesh, this._activeEffect);
  43941. };
  43942. StandardMaterial.prototype.getAnimatables = function () {
  43943. var results = [];
  43944. if (this._diffuseTexture && this._diffuseTexture.animations && this._diffuseTexture.animations.length > 0) {
  43945. results.push(this._diffuseTexture);
  43946. }
  43947. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  43948. results.push(this._ambientTexture);
  43949. }
  43950. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  43951. results.push(this._opacityTexture);
  43952. }
  43953. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  43954. results.push(this._reflectionTexture);
  43955. }
  43956. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  43957. results.push(this._emissiveTexture);
  43958. }
  43959. if (this._specularTexture && this._specularTexture.animations && this._specularTexture.animations.length > 0) {
  43960. results.push(this._specularTexture);
  43961. }
  43962. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  43963. results.push(this._bumpTexture);
  43964. }
  43965. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  43966. results.push(this._lightmapTexture);
  43967. }
  43968. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  43969. results.push(this._refractionTexture);
  43970. }
  43971. return results;
  43972. };
  43973. StandardMaterial.prototype.getActiveTextures = function () {
  43974. var activeTextures = _super.prototype.getActiveTextures.call(this);
  43975. if (this._diffuseTexture) {
  43976. activeTextures.push(this._diffuseTexture);
  43977. }
  43978. if (this._ambientTexture) {
  43979. activeTextures.push(this._ambientTexture);
  43980. }
  43981. if (this._opacityTexture) {
  43982. activeTextures.push(this._opacityTexture);
  43983. }
  43984. if (this._reflectionTexture) {
  43985. activeTextures.push(this._reflectionTexture);
  43986. }
  43987. if (this._emissiveTexture) {
  43988. activeTextures.push(this._emissiveTexture);
  43989. }
  43990. if (this._specularTexture) {
  43991. activeTextures.push(this._specularTexture);
  43992. }
  43993. if (this._bumpTexture) {
  43994. activeTextures.push(this._bumpTexture);
  43995. }
  43996. if (this._lightmapTexture) {
  43997. activeTextures.push(this._lightmapTexture);
  43998. }
  43999. if (this._refractionTexture) {
  44000. activeTextures.push(this._refractionTexture);
  44001. }
  44002. return activeTextures;
  44003. };
  44004. StandardMaterial.prototype.hasTexture = function (texture) {
  44005. if (_super.prototype.hasTexture.call(this, texture)) {
  44006. return true;
  44007. }
  44008. if (this._diffuseTexture === texture) {
  44009. return true;
  44010. }
  44011. if (this._ambientTexture === texture) {
  44012. return true;
  44013. }
  44014. if (this._opacityTexture === texture) {
  44015. return true;
  44016. }
  44017. if (this._reflectionTexture === texture) {
  44018. return true;
  44019. }
  44020. if (this._emissiveTexture === texture) {
  44021. return true;
  44022. }
  44023. if (this._specularTexture === texture) {
  44024. return true;
  44025. }
  44026. if (this._bumpTexture === texture) {
  44027. return true;
  44028. }
  44029. if (this._lightmapTexture === texture) {
  44030. return true;
  44031. }
  44032. if (this._refractionTexture === texture) {
  44033. return true;
  44034. }
  44035. return false;
  44036. };
  44037. StandardMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  44038. if (forceDisposeTextures) {
  44039. if (this._diffuseTexture) {
  44040. this._diffuseTexture.dispose();
  44041. }
  44042. if (this._ambientTexture) {
  44043. this._ambientTexture.dispose();
  44044. }
  44045. if (this._opacityTexture) {
  44046. this._opacityTexture.dispose();
  44047. }
  44048. if (this._reflectionTexture) {
  44049. this._reflectionTexture.dispose();
  44050. }
  44051. if (this._emissiveTexture) {
  44052. this._emissiveTexture.dispose();
  44053. }
  44054. if (this._specularTexture) {
  44055. this._specularTexture.dispose();
  44056. }
  44057. if (this._bumpTexture) {
  44058. this._bumpTexture.dispose();
  44059. }
  44060. if (this._lightmapTexture) {
  44061. this._lightmapTexture.dispose();
  44062. }
  44063. if (this._refractionTexture) {
  44064. this._refractionTexture.dispose();
  44065. }
  44066. }
  44067. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  44068. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  44069. }
  44070. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  44071. };
  44072. StandardMaterial.prototype.clone = function (name) {
  44073. var _this = this;
  44074. var result = BABYLON.SerializationHelper.Clone(function () { return new StandardMaterial(name, _this.getScene()); }, this);
  44075. result.name = name;
  44076. result.id = name;
  44077. return result;
  44078. };
  44079. StandardMaterial.prototype.serialize = function () {
  44080. return BABYLON.SerializationHelper.Serialize(this);
  44081. };
  44082. // Statics
  44083. StandardMaterial.Parse = function (source, scene, rootUrl) {
  44084. return BABYLON.SerializationHelper.Parse(function () { return new StandardMaterial(source.name, scene); }, source, scene, rootUrl);
  44085. };
  44086. Object.defineProperty(StandardMaterial, "DiffuseTextureEnabled", {
  44087. get: function () {
  44088. return StandardMaterial._DiffuseTextureEnabled;
  44089. },
  44090. set: function (value) {
  44091. if (StandardMaterial._DiffuseTextureEnabled === value) {
  44092. return;
  44093. }
  44094. StandardMaterial._DiffuseTextureEnabled = value;
  44095. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  44096. },
  44097. enumerable: true,
  44098. configurable: true
  44099. });
  44100. Object.defineProperty(StandardMaterial, "AmbientTextureEnabled", {
  44101. get: function () {
  44102. return StandardMaterial._AmbientTextureEnabled;
  44103. },
  44104. set: function (value) {
  44105. if (StandardMaterial._AmbientTextureEnabled === value) {
  44106. return;
  44107. }
  44108. StandardMaterial._AmbientTextureEnabled = value;
  44109. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  44110. },
  44111. enumerable: true,
  44112. configurable: true
  44113. });
  44114. Object.defineProperty(StandardMaterial, "OpacityTextureEnabled", {
  44115. get: function () {
  44116. return StandardMaterial._OpacityTextureEnabled;
  44117. },
  44118. set: function (value) {
  44119. if (StandardMaterial._OpacityTextureEnabled === value) {
  44120. return;
  44121. }
  44122. StandardMaterial._OpacityTextureEnabled = value;
  44123. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  44124. },
  44125. enumerable: true,
  44126. configurable: true
  44127. });
  44128. Object.defineProperty(StandardMaterial, "ReflectionTextureEnabled", {
  44129. get: function () {
  44130. return StandardMaterial._ReflectionTextureEnabled;
  44131. },
  44132. set: function (value) {
  44133. if (StandardMaterial._ReflectionTextureEnabled === value) {
  44134. return;
  44135. }
  44136. StandardMaterial._ReflectionTextureEnabled = value;
  44137. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  44138. },
  44139. enumerable: true,
  44140. configurable: true
  44141. });
  44142. Object.defineProperty(StandardMaterial, "EmissiveTextureEnabled", {
  44143. get: function () {
  44144. return StandardMaterial._EmissiveTextureEnabled;
  44145. },
  44146. set: function (value) {
  44147. if (StandardMaterial._EmissiveTextureEnabled === value) {
  44148. return;
  44149. }
  44150. StandardMaterial._EmissiveTextureEnabled = value;
  44151. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  44152. },
  44153. enumerable: true,
  44154. configurable: true
  44155. });
  44156. Object.defineProperty(StandardMaterial, "SpecularTextureEnabled", {
  44157. get: function () {
  44158. return StandardMaterial._SpecularTextureEnabled;
  44159. },
  44160. set: function (value) {
  44161. if (StandardMaterial._SpecularTextureEnabled === value) {
  44162. return;
  44163. }
  44164. StandardMaterial._SpecularTextureEnabled = value;
  44165. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  44166. },
  44167. enumerable: true,
  44168. configurable: true
  44169. });
  44170. Object.defineProperty(StandardMaterial, "BumpTextureEnabled", {
  44171. get: function () {
  44172. return StandardMaterial._BumpTextureEnabled;
  44173. },
  44174. set: function (value) {
  44175. if (StandardMaterial._BumpTextureEnabled === value) {
  44176. return;
  44177. }
  44178. StandardMaterial._BumpTextureEnabled = value;
  44179. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  44180. },
  44181. enumerable: true,
  44182. configurable: true
  44183. });
  44184. Object.defineProperty(StandardMaterial, "LightmapTextureEnabled", {
  44185. get: function () {
  44186. return StandardMaterial._LightmapTextureEnabled;
  44187. },
  44188. set: function (value) {
  44189. if (StandardMaterial._LightmapTextureEnabled === value) {
  44190. return;
  44191. }
  44192. StandardMaterial._LightmapTextureEnabled = value;
  44193. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  44194. },
  44195. enumerable: true,
  44196. configurable: true
  44197. });
  44198. Object.defineProperty(StandardMaterial, "RefractionTextureEnabled", {
  44199. get: function () {
  44200. return StandardMaterial._RefractionTextureEnabled;
  44201. },
  44202. set: function (value) {
  44203. if (StandardMaterial._RefractionTextureEnabled === value) {
  44204. return;
  44205. }
  44206. StandardMaterial._RefractionTextureEnabled = value;
  44207. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  44208. },
  44209. enumerable: true,
  44210. configurable: true
  44211. });
  44212. Object.defineProperty(StandardMaterial, "ColorGradingTextureEnabled", {
  44213. get: function () {
  44214. return StandardMaterial._ColorGradingTextureEnabled;
  44215. },
  44216. set: function (value) {
  44217. if (StandardMaterial._ColorGradingTextureEnabled === value) {
  44218. return;
  44219. }
  44220. StandardMaterial._ColorGradingTextureEnabled = value;
  44221. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  44222. },
  44223. enumerable: true,
  44224. configurable: true
  44225. });
  44226. Object.defineProperty(StandardMaterial, "FresnelEnabled", {
  44227. get: function () {
  44228. return StandardMaterial._FresnelEnabled;
  44229. },
  44230. set: function (value) {
  44231. if (StandardMaterial._FresnelEnabled === value) {
  44232. return;
  44233. }
  44234. StandardMaterial._FresnelEnabled = value;
  44235. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag);
  44236. },
  44237. enumerable: true,
  44238. configurable: true
  44239. });
  44240. // Flags used to enable or disable a type of texture for all Standard Materials
  44241. StandardMaterial._DiffuseTextureEnabled = true;
  44242. StandardMaterial._AmbientTextureEnabled = true;
  44243. StandardMaterial._OpacityTextureEnabled = true;
  44244. StandardMaterial._ReflectionTextureEnabled = true;
  44245. StandardMaterial._EmissiveTextureEnabled = true;
  44246. StandardMaterial._SpecularTextureEnabled = true;
  44247. StandardMaterial._BumpTextureEnabled = true;
  44248. StandardMaterial._LightmapTextureEnabled = true;
  44249. StandardMaterial._RefractionTextureEnabled = true;
  44250. StandardMaterial._ColorGradingTextureEnabled = true;
  44251. StandardMaterial._FresnelEnabled = true;
  44252. __decorate([
  44253. BABYLON.serializeAsTexture("diffuseTexture")
  44254. ], StandardMaterial.prototype, "_diffuseTexture", void 0);
  44255. __decorate([
  44256. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  44257. ], StandardMaterial.prototype, "diffuseTexture", void 0);
  44258. __decorate([
  44259. BABYLON.serializeAsTexture("ambientTexture")
  44260. ], StandardMaterial.prototype, "_ambientTexture", void 0);
  44261. __decorate([
  44262. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44263. ], StandardMaterial.prototype, "ambientTexture", void 0);
  44264. __decorate([
  44265. BABYLON.serializeAsTexture("opacityTexture")
  44266. ], StandardMaterial.prototype, "_opacityTexture", void 0);
  44267. __decorate([
  44268. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  44269. ], StandardMaterial.prototype, "opacityTexture", void 0);
  44270. __decorate([
  44271. BABYLON.serializeAsTexture("reflectionTexture")
  44272. ], StandardMaterial.prototype, "_reflectionTexture", void 0);
  44273. __decorate([
  44274. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44275. ], StandardMaterial.prototype, "reflectionTexture", void 0);
  44276. __decorate([
  44277. BABYLON.serializeAsTexture("emissiveTexture")
  44278. ], StandardMaterial.prototype, "_emissiveTexture", void 0);
  44279. __decorate([
  44280. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44281. ], StandardMaterial.prototype, "emissiveTexture", void 0);
  44282. __decorate([
  44283. BABYLON.serializeAsTexture("specularTexture")
  44284. ], StandardMaterial.prototype, "_specularTexture", void 0);
  44285. __decorate([
  44286. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44287. ], StandardMaterial.prototype, "specularTexture", void 0);
  44288. __decorate([
  44289. BABYLON.serializeAsTexture("bumpTexture")
  44290. ], StandardMaterial.prototype, "_bumpTexture", void 0);
  44291. __decorate([
  44292. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44293. ], StandardMaterial.prototype, "bumpTexture", void 0);
  44294. __decorate([
  44295. BABYLON.serializeAsTexture("lightmapTexture")
  44296. ], StandardMaterial.prototype, "_lightmapTexture", void 0);
  44297. __decorate([
  44298. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44299. ], StandardMaterial.prototype, "lightmapTexture", void 0);
  44300. __decorate([
  44301. BABYLON.serializeAsTexture("refractionTexture")
  44302. ], StandardMaterial.prototype, "_refractionTexture", void 0);
  44303. __decorate([
  44304. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44305. ], StandardMaterial.prototype, "refractionTexture", void 0);
  44306. __decorate([
  44307. BABYLON.serializeAsColor3("ambient")
  44308. ], StandardMaterial.prototype, "ambientColor", void 0);
  44309. __decorate([
  44310. BABYLON.serializeAsColor3("diffuse")
  44311. ], StandardMaterial.prototype, "diffuseColor", void 0);
  44312. __decorate([
  44313. BABYLON.serializeAsColor3("specular")
  44314. ], StandardMaterial.prototype, "specularColor", void 0);
  44315. __decorate([
  44316. BABYLON.serializeAsColor3("emissive")
  44317. ], StandardMaterial.prototype, "emissiveColor", void 0);
  44318. __decorate([
  44319. BABYLON.serialize()
  44320. ], StandardMaterial.prototype, "specularPower", void 0);
  44321. __decorate([
  44322. BABYLON.serialize("useAlphaFromDiffuseTexture")
  44323. ], StandardMaterial.prototype, "_useAlphaFromDiffuseTexture", void 0);
  44324. __decorate([
  44325. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44326. ], StandardMaterial.prototype, "useAlphaFromDiffuseTexture", void 0);
  44327. __decorate([
  44328. BABYLON.serialize("useEmissiveAsIllumination")
  44329. ], StandardMaterial.prototype, "_useEmissiveAsIllumination", void 0);
  44330. __decorate([
  44331. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44332. ], StandardMaterial.prototype, "useEmissiveAsIllumination", void 0);
  44333. __decorate([
  44334. BABYLON.serialize("linkEmissiveWithDiffuse")
  44335. ], StandardMaterial.prototype, "_linkEmissiveWithDiffuse", void 0);
  44336. __decorate([
  44337. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44338. ], StandardMaterial.prototype, "linkEmissiveWithDiffuse", void 0);
  44339. __decorate([
  44340. BABYLON.serialize("useSpecularOverAlpha")
  44341. ], StandardMaterial.prototype, "_useSpecularOverAlpha", void 0);
  44342. __decorate([
  44343. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44344. ], StandardMaterial.prototype, "useSpecularOverAlpha", void 0);
  44345. __decorate([
  44346. BABYLON.serialize("useReflectionOverAlpha")
  44347. ], StandardMaterial.prototype, "_useReflectionOverAlpha", void 0);
  44348. __decorate([
  44349. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44350. ], StandardMaterial.prototype, "useReflectionOverAlpha", void 0);
  44351. __decorate([
  44352. BABYLON.serialize("disableLighting")
  44353. ], StandardMaterial.prototype, "_disableLighting", void 0);
  44354. __decorate([
  44355. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  44356. ], StandardMaterial.prototype, "disableLighting", void 0);
  44357. __decorate([
  44358. BABYLON.serialize("useObjectSpaceNormalMap")
  44359. ], StandardMaterial.prototype, "_useObjectSpaceNormalMap", void 0);
  44360. __decorate([
  44361. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44362. ], StandardMaterial.prototype, "useObjectSpaceNormalMap", void 0);
  44363. __decorate([
  44364. BABYLON.serialize("useParallax")
  44365. ], StandardMaterial.prototype, "_useParallax", void 0);
  44366. __decorate([
  44367. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44368. ], StandardMaterial.prototype, "useParallax", void 0);
  44369. __decorate([
  44370. BABYLON.serialize("useParallaxOcclusion")
  44371. ], StandardMaterial.prototype, "_useParallaxOcclusion", void 0);
  44372. __decorate([
  44373. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44374. ], StandardMaterial.prototype, "useParallaxOcclusion", void 0);
  44375. __decorate([
  44376. BABYLON.serialize()
  44377. ], StandardMaterial.prototype, "parallaxScaleBias", void 0);
  44378. __decorate([
  44379. BABYLON.serialize("roughness")
  44380. ], StandardMaterial.prototype, "_roughness", void 0);
  44381. __decorate([
  44382. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44383. ], StandardMaterial.prototype, "roughness", void 0);
  44384. __decorate([
  44385. BABYLON.serialize()
  44386. ], StandardMaterial.prototype, "indexOfRefraction", void 0);
  44387. __decorate([
  44388. BABYLON.serialize()
  44389. ], StandardMaterial.prototype, "invertRefractionY", void 0);
  44390. __decorate([
  44391. BABYLON.serialize()
  44392. ], StandardMaterial.prototype, "alphaCutOff", void 0);
  44393. __decorate([
  44394. BABYLON.serialize("useLightmapAsShadowmap")
  44395. ], StandardMaterial.prototype, "_useLightmapAsShadowmap", void 0);
  44396. __decorate([
  44397. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44398. ], StandardMaterial.prototype, "useLightmapAsShadowmap", void 0);
  44399. __decorate([
  44400. BABYLON.serializeAsFresnelParameters("diffuseFresnelParameters")
  44401. ], StandardMaterial.prototype, "_diffuseFresnelParameters", void 0);
  44402. __decorate([
  44403. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  44404. ], StandardMaterial.prototype, "diffuseFresnelParameters", void 0);
  44405. __decorate([
  44406. BABYLON.serializeAsFresnelParameters("opacityFresnelParameters")
  44407. ], StandardMaterial.prototype, "_opacityFresnelParameters", void 0);
  44408. __decorate([
  44409. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelAndMiscDirty")
  44410. ], StandardMaterial.prototype, "opacityFresnelParameters", void 0);
  44411. __decorate([
  44412. BABYLON.serializeAsFresnelParameters("reflectionFresnelParameters")
  44413. ], StandardMaterial.prototype, "_reflectionFresnelParameters", void 0);
  44414. __decorate([
  44415. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  44416. ], StandardMaterial.prototype, "reflectionFresnelParameters", void 0);
  44417. __decorate([
  44418. BABYLON.serializeAsFresnelParameters("refractionFresnelParameters")
  44419. ], StandardMaterial.prototype, "_refractionFresnelParameters", void 0);
  44420. __decorate([
  44421. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  44422. ], StandardMaterial.prototype, "refractionFresnelParameters", void 0);
  44423. __decorate([
  44424. BABYLON.serializeAsFresnelParameters("emissiveFresnelParameters")
  44425. ], StandardMaterial.prototype, "_emissiveFresnelParameters", void 0);
  44426. __decorate([
  44427. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  44428. ], StandardMaterial.prototype, "emissiveFresnelParameters", void 0);
  44429. __decorate([
  44430. BABYLON.serialize("useReflectionFresnelFromSpecular")
  44431. ], StandardMaterial.prototype, "_useReflectionFresnelFromSpecular", void 0);
  44432. __decorate([
  44433. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  44434. ], StandardMaterial.prototype, "useReflectionFresnelFromSpecular", void 0);
  44435. __decorate([
  44436. BABYLON.serialize("useGlossinessFromSpecularMapAlpha")
  44437. ], StandardMaterial.prototype, "_useGlossinessFromSpecularMapAlpha", void 0);
  44438. __decorate([
  44439. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44440. ], StandardMaterial.prototype, "useGlossinessFromSpecularMapAlpha", void 0);
  44441. __decorate([
  44442. BABYLON.serialize("maxSimultaneousLights")
  44443. ], StandardMaterial.prototype, "_maxSimultaneousLights", void 0);
  44444. __decorate([
  44445. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  44446. ], StandardMaterial.prototype, "maxSimultaneousLights", void 0);
  44447. __decorate([
  44448. BABYLON.serialize("invertNormalMapX")
  44449. ], StandardMaterial.prototype, "_invertNormalMapX", void 0);
  44450. __decorate([
  44451. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44452. ], StandardMaterial.prototype, "invertNormalMapX", void 0);
  44453. __decorate([
  44454. BABYLON.serialize("invertNormalMapY")
  44455. ], StandardMaterial.prototype, "_invertNormalMapY", void 0);
  44456. __decorate([
  44457. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44458. ], StandardMaterial.prototype, "invertNormalMapY", void 0);
  44459. __decorate([
  44460. BABYLON.serialize("twoSidedLighting")
  44461. ], StandardMaterial.prototype, "_twoSidedLighting", void 0);
  44462. __decorate([
  44463. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44464. ], StandardMaterial.prototype, "twoSidedLighting", void 0);
  44465. __decorate([
  44466. BABYLON.serialize()
  44467. ], StandardMaterial.prototype, "useLogarithmicDepth", null);
  44468. return StandardMaterial;
  44469. }(BABYLON.PushMaterial));
  44470. BABYLON.StandardMaterial = StandardMaterial;
  44471. })(BABYLON || (BABYLON = {}));
  44472. //# sourceMappingURL=babylon.standardMaterial.js.map
  44473. var BABYLON;
  44474. (function (BABYLON) {
  44475. /**
  44476. * Manages the defines for the PBR Material.
  44477. * @hiddenChildren
  44478. */
  44479. var PBRMaterialDefines = /** @class */ (function (_super) {
  44480. __extends(PBRMaterialDefines, _super);
  44481. /**
  44482. * Initializes the PBR Material defines.
  44483. */
  44484. function PBRMaterialDefines() {
  44485. var _this = _super.call(this) || this;
  44486. _this.PBR = true;
  44487. _this.MAINUV1 = false;
  44488. _this.MAINUV2 = false;
  44489. _this.UV1 = false;
  44490. _this.UV2 = false;
  44491. _this.ALBEDO = false;
  44492. _this.ALBEDODIRECTUV = 0;
  44493. _this.VERTEXCOLOR = false;
  44494. _this.AMBIENT = false;
  44495. _this.AMBIENTDIRECTUV = 0;
  44496. _this.AMBIENTINGRAYSCALE = false;
  44497. _this.OPACITY = false;
  44498. _this.VERTEXALPHA = false;
  44499. _this.OPACITYDIRECTUV = 0;
  44500. _this.OPACITYRGB = false;
  44501. _this.ALPHATEST = false;
  44502. _this.DEPTHPREPASS = false;
  44503. _this.ALPHABLEND = false;
  44504. _this.ALPHAFROMALBEDO = false;
  44505. _this.ALPHATESTVALUE = "0.5";
  44506. _this.SPECULAROVERALPHA = false;
  44507. _this.RADIANCEOVERALPHA = false;
  44508. _this.ALPHAFRESNEL = false;
  44509. _this.LINEARALPHAFRESNEL = false;
  44510. _this.PREMULTIPLYALPHA = false;
  44511. _this.EMISSIVE = false;
  44512. _this.EMISSIVEDIRECTUV = 0;
  44513. _this.REFLECTIVITY = false;
  44514. _this.REFLECTIVITYDIRECTUV = 0;
  44515. _this.SPECULARTERM = false;
  44516. _this.MICROSURFACEFROMREFLECTIVITYMAP = false;
  44517. _this.MICROSURFACEAUTOMATIC = false;
  44518. _this.LODBASEDMICROSFURACE = false;
  44519. _this.MICROSURFACEMAP = false;
  44520. _this.MICROSURFACEMAPDIRECTUV = 0;
  44521. _this.METALLICWORKFLOW = false;
  44522. _this.ROUGHNESSSTOREINMETALMAPALPHA = false;
  44523. _this.ROUGHNESSSTOREINMETALMAPGREEN = false;
  44524. _this.METALLNESSSTOREINMETALMAPBLUE = false;
  44525. _this.AOSTOREINMETALMAPRED = false;
  44526. _this.ENVIRONMENTBRDF = false;
  44527. _this.NORMAL = false;
  44528. _this.TANGENT = false;
  44529. _this.BUMP = false;
  44530. _this.BUMPDIRECTUV = 0;
  44531. _this.OBJECTSPACE_NORMALMAP = false;
  44532. _this.PARALLAX = false;
  44533. _this.PARALLAXOCCLUSION = false;
  44534. _this.NORMALXYSCALE = true;
  44535. _this.LIGHTMAP = false;
  44536. _this.LIGHTMAPDIRECTUV = 0;
  44537. _this.USELIGHTMAPASSHADOWMAP = false;
  44538. _this.GAMMALIGHTMAP = false;
  44539. _this.REFLECTION = false;
  44540. _this.REFLECTIONMAP_3D = false;
  44541. _this.REFLECTIONMAP_SPHERICAL = false;
  44542. _this.REFLECTIONMAP_PLANAR = false;
  44543. _this.REFLECTIONMAP_CUBIC = false;
  44544. _this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  44545. _this.REFLECTIONMAP_PROJECTION = false;
  44546. _this.REFLECTIONMAP_SKYBOX = false;
  44547. _this.REFLECTIONMAP_EXPLICIT = false;
  44548. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  44549. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  44550. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  44551. _this.INVERTCUBICMAP = false;
  44552. _this.USESPHERICALFROMREFLECTIONMAP = false;
  44553. _this.USESPHERICALINVERTEX = false;
  44554. _this.REFLECTIONMAP_OPPOSITEZ = false;
  44555. _this.LODINREFLECTIONALPHA = false;
  44556. _this.GAMMAREFLECTION = false;
  44557. _this.RADIANCEOCCLUSION = false;
  44558. _this.HORIZONOCCLUSION = false;
  44559. _this.REFRACTION = false;
  44560. _this.REFRACTIONMAP_3D = false;
  44561. _this.REFRACTIONMAP_OPPOSITEZ = false;
  44562. _this.LODINREFRACTIONALPHA = false;
  44563. _this.GAMMAREFRACTION = false;
  44564. _this.LINKREFRACTIONTOTRANSPARENCY = false;
  44565. _this.INSTANCES = false;
  44566. _this.NUM_BONE_INFLUENCERS = 0;
  44567. _this.BonesPerMesh = 0;
  44568. _this.NONUNIFORMSCALING = false;
  44569. _this.MORPHTARGETS = false;
  44570. _this.MORPHTARGETS_NORMAL = false;
  44571. _this.MORPHTARGETS_TANGENT = false;
  44572. _this.NUM_MORPH_INFLUENCERS = 0;
  44573. _this.IMAGEPROCESSING = false;
  44574. _this.VIGNETTE = false;
  44575. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  44576. _this.VIGNETTEBLENDMODEOPAQUE = false;
  44577. _this.TONEMAPPING = false;
  44578. _this.CONTRAST = false;
  44579. _this.COLORCURVES = false;
  44580. _this.COLORGRADING = false;
  44581. _this.COLORGRADING3D = false;
  44582. _this.SAMPLER3DGREENDEPTH = false;
  44583. _this.SAMPLER3DBGRMAP = false;
  44584. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  44585. _this.EXPOSURE = false;
  44586. _this.USEPHYSICALLIGHTFALLOFF = false;
  44587. _this.TWOSIDEDLIGHTING = false;
  44588. _this.SHADOWFLOAT = false;
  44589. _this.CLIPPLANE = false;
  44590. _this.POINTSIZE = false;
  44591. _this.FOG = false;
  44592. _this.LOGARITHMICDEPTH = false;
  44593. _this.FORCENORMALFORWARD = false;
  44594. _this.SPECULARAA = false;
  44595. _this.UNLIT = false;
  44596. _this.rebuild();
  44597. return _this;
  44598. }
  44599. /**
  44600. * Resets the PBR Material defines.
  44601. */
  44602. PBRMaterialDefines.prototype.reset = function () {
  44603. _super.prototype.reset.call(this);
  44604. this.ALPHATESTVALUE = "0.5";
  44605. this.PBR = true;
  44606. };
  44607. return PBRMaterialDefines;
  44608. }(BABYLON.MaterialDefines));
  44609. /**
  44610. * The Physically based material base class of BJS.
  44611. *
  44612. * This offers the main features of a standard PBR material.
  44613. * For more information, please refer to the documentation :
  44614. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  44615. */
  44616. var PBRBaseMaterial = /** @class */ (function (_super) {
  44617. __extends(PBRBaseMaterial, _super);
  44618. /**
  44619. * Instantiates a new PBRMaterial instance.
  44620. *
  44621. * @param name The material name
  44622. * @param scene The scene the material will be use in.
  44623. */
  44624. function PBRBaseMaterial(name, scene) {
  44625. var _this = _super.call(this, name, scene) || this;
  44626. /**
  44627. * Intensity of the direct lights e.g. the four lights available in your scene.
  44628. * This impacts both the direct diffuse and specular highlights.
  44629. */
  44630. _this._directIntensity = 1.0;
  44631. /**
  44632. * Intensity of the emissive part of the material.
  44633. * This helps controlling the emissive effect without modifying the emissive color.
  44634. */
  44635. _this._emissiveIntensity = 1.0;
  44636. /**
  44637. * Intensity of the environment e.g. how much the environment will light the object
  44638. * either through harmonics for rough material or through the refelction for shiny ones.
  44639. */
  44640. _this._environmentIntensity = 1.0;
  44641. /**
  44642. * This is a special control allowing the reduction of the specular highlights coming from the
  44643. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  44644. */
  44645. _this._specularIntensity = 1.0;
  44646. /**
  44647. * This stores the direct, emissive, environment, and specular light intensities into a Vector4.
  44648. */
  44649. _this._lightingInfos = new BABYLON.Vector4(_this._directIntensity, _this._emissiveIntensity, _this._environmentIntensity, _this._specularIntensity);
  44650. /**
  44651. * Debug Control allowing disabling the bump map on this material.
  44652. */
  44653. _this._disableBumpMap = false;
  44654. /**
  44655. * AKA Occlusion Texture Intensity in other nomenclature.
  44656. */
  44657. _this._ambientTextureStrength = 1.0;
  44658. /**
  44659. * The color of a material in ambient lighting.
  44660. */
  44661. _this._ambientColor = new BABYLON.Color3(0, 0, 0);
  44662. /**
  44663. * AKA Diffuse Color in other nomenclature.
  44664. */
  44665. _this._albedoColor = new BABYLON.Color3(1, 1, 1);
  44666. /**
  44667. * AKA Specular Color in other nomenclature.
  44668. */
  44669. _this._reflectivityColor = new BABYLON.Color3(1, 1, 1);
  44670. /**
  44671. * The color applied when light is reflected from a material.
  44672. */
  44673. _this._reflectionColor = new BABYLON.Color3(1, 1, 1);
  44674. /**
  44675. * The color applied when light is emitted from a material.
  44676. */
  44677. _this._emissiveColor = new BABYLON.Color3(0, 0, 0);
  44678. /**
  44679. * AKA Glossiness in other nomenclature.
  44680. */
  44681. _this._microSurface = 0.9;
  44682. /**
  44683. * source material index of refraction (IOR)' / 'destination material IOR.
  44684. */
  44685. _this._indexOfRefraction = 0.66;
  44686. /**
  44687. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  44688. */
  44689. _this._invertRefractionY = false;
  44690. /**
  44691. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  44692. * Materials half opaque for instance using refraction could benefit from this control.
  44693. */
  44694. _this._linkRefractionWithTransparency = false;
  44695. /**
  44696. * Specifies that the material will use the light map as a show map.
  44697. */
  44698. _this._useLightmapAsShadowmap = false;
  44699. /**
  44700. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  44701. * makes the reflect vector face the model (under horizon).
  44702. */
  44703. _this._useHorizonOcclusion = true;
  44704. /**
  44705. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  44706. * too much the area relying on ambient texture to define their ambient occlusion.
  44707. */
  44708. _this._useRadianceOcclusion = true;
  44709. /**
  44710. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  44711. */
  44712. _this._useAlphaFromAlbedoTexture = false;
  44713. /**
  44714. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  44715. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  44716. */
  44717. _this._useSpecularOverAlpha = true;
  44718. /**
  44719. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  44720. */
  44721. _this._useMicroSurfaceFromReflectivityMapAlpha = false;
  44722. /**
  44723. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  44724. */
  44725. _this._useRoughnessFromMetallicTextureAlpha = true;
  44726. /**
  44727. * Specifies if the metallic texture contains the roughness information in its green channel.
  44728. */
  44729. _this._useRoughnessFromMetallicTextureGreen = false;
  44730. /**
  44731. * Specifies if the metallic texture contains the metallness information in its blue channel.
  44732. */
  44733. _this._useMetallnessFromMetallicTextureBlue = false;
  44734. /**
  44735. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  44736. */
  44737. _this._useAmbientOcclusionFromMetallicTextureRed = false;
  44738. /**
  44739. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  44740. */
  44741. _this._useAmbientInGrayScale = false;
  44742. /**
  44743. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  44744. * The material will try to infer what glossiness each pixel should be.
  44745. */
  44746. _this._useAutoMicroSurfaceFromReflectivityMap = false;
  44747. /**
  44748. * BJS is using an harcoded light falloff based on a manually sets up range.
  44749. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  44750. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  44751. */
  44752. _this._usePhysicalLightFalloff = true;
  44753. /**
  44754. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  44755. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  44756. */
  44757. _this._useRadianceOverAlpha = true;
  44758. /**
  44759. * Allows using an object space normal map (instead of tangent space).
  44760. */
  44761. _this._useObjectSpaceNormalMap = false;
  44762. /**
  44763. * Allows using the bump map in parallax mode.
  44764. */
  44765. _this._useParallax = false;
  44766. /**
  44767. * Allows using the bump map in parallax occlusion mode.
  44768. */
  44769. _this._useParallaxOcclusion = false;
  44770. /**
  44771. * Controls the scale bias of the parallax mode.
  44772. */
  44773. _this._parallaxScaleBias = 0.05;
  44774. /**
  44775. * If sets to true, disables all the lights affecting the material.
  44776. */
  44777. _this._disableLighting = false;
  44778. /**
  44779. * Number of Simultaneous lights allowed on the material.
  44780. */
  44781. _this._maxSimultaneousLights = 4;
  44782. /**
  44783. * If sets to true, x component of normal map value will be inverted (x = 1.0 - x).
  44784. */
  44785. _this._invertNormalMapX = false;
  44786. /**
  44787. * If sets to true, y component of normal map value will be inverted (y = 1.0 - y).
  44788. */
  44789. _this._invertNormalMapY = false;
  44790. /**
  44791. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  44792. */
  44793. _this._twoSidedLighting = false;
  44794. /**
  44795. * Defines the alpha limits in alpha test mode.
  44796. */
  44797. _this._alphaCutOff = 0.4;
  44798. /**
  44799. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  44800. */
  44801. _this._forceAlphaTest = false;
  44802. /**
  44803. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  44804. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  44805. */
  44806. _this._useAlphaFresnel = false;
  44807. /**
  44808. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  44809. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  44810. */
  44811. _this._useLinearAlphaFresnel = false;
  44812. /**
  44813. * The transparency mode of the material.
  44814. */
  44815. _this._transparencyMode = null;
  44816. /**
  44817. * Specifies the environment BRDF texture used to comput the scale and offset roughness values
  44818. * from cos thetav and roughness:
  44819. * http://blog.selfshadow.com/publications/s2013-shading-course/karis/s2013_pbs_epic_notes_v2.pdf
  44820. */
  44821. _this._environmentBRDFTexture = null;
  44822. /**
  44823. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  44824. */
  44825. _this._forceIrradianceInFragment = false;
  44826. /**
  44827. * Force normal to face away from face.
  44828. */
  44829. _this._forceNormalForward = false;
  44830. /**
  44831. * Enables specular anti aliasing in the PBR shader.
  44832. * It will both interacts on the Geometry for analytical and IBL lighting.
  44833. * It also prefilter the roughness map based on the bump values.
  44834. */
  44835. _this._enableSpecularAntiAliasing = false;
  44836. /**
  44837. * Stores the available render targets.
  44838. */
  44839. _this._renderTargets = new BABYLON.SmartArray(16);
  44840. /**
  44841. * Sets the global ambient color for the material used in lighting calculations.
  44842. */
  44843. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  44844. /**
  44845. * If set to true, no lighting calculations will be applied.
  44846. */
  44847. _this._unlit = false;
  44848. // Setup the default processing configuration to the scene.
  44849. _this._attachImageProcessingConfiguration(null);
  44850. _this.getRenderTargetTextures = function () {
  44851. _this._renderTargets.reset();
  44852. if (BABYLON.StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  44853. _this._renderTargets.push(_this._reflectionTexture);
  44854. }
  44855. if (BABYLON.StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  44856. _this._renderTargets.push(_this._refractionTexture);
  44857. }
  44858. return _this._renderTargets;
  44859. };
  44860. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  44861. return _this;
  44862. }
  44863. /**
  44864. * Attaches a new image processing configuration to the PBR Material.
  44865. * @param configuration
  44866. */
  44867. PBRBaseMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  44868. var _this = this;
  44869. if (configuration === this._imageProcessingConfiguration) {
  44870. return;
  44871. }
  44872. // Detaches observer.
  44873. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  44874. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  44875. }
  44876. // Pick the scene configuration if needed.
  44877. if (!configuration) {
  44878. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  44879. }
  44880. else {
  44881. this._imageProcessingConfiguration = configuration;
  44882. }
  44883. // Attaches observer.
  44884. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  44885. _this._markAllSubMeshesAsImageProcessingDirty();
  44886. });
  44887. };
  44888. /**
  44889. * Gets the name of the material class.
  44890. */
  44891. PBRBaseMaterial.prototype.getClassName = function () {
  44892. return "PBRBaseMaterial";
  44893. };
  44894. Object.defineProperty(PBRBaseMaterial.prototype, "useLogarithmicDepth", {
  44895. /**
  44896. * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.
  44897. */
  44898. get: function () {
  44899. return this._useLogarithmicDepth;
  44900. },
  44901. /**
  44902. * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.
  44903. */
  44904. set: function (value) {
  44905. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  44906. },
  44907. enumerable: true,
  44908. configurable: true
  44909. });
  44910. Object.defineProperty(PBRBaseMaterial.prototype, "transparencyMode", {
  44911. /**
  44912. * Gets the current transparency mode.
  44913. */
  44914. get: function () {
  44915. return this._transparencyMode;
  44916. },
  44917. /**
  44918. * Sets the transparency mode of the material.
  44919. */
  44920. set: function (value) {
  44921. if (this._transparencyMode === value) {
  44922. return;
  44923. }
  44924. this._transparencyMode = value;
  44925. this._forceAlphaTest = (value === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND);
  44926. this._markAllSubMeshesAsTexturesAndMiscDirty();
  44927. },
  44928. enumerable: true,
  44929. configurable: true
  44930. });
  44931. Object.defineProperty(PBRBaseMaterial.prototype, "_disableAlphaBlending", {
  44932. /**
  44933. * Returns true if alpha blending should be disabled.
  44934. */
  44935. get: function () {
  44936. return (this._linkRefractionWithTransparency ||
  44937. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE ||
  44938. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  44939. },
  44940. enumerable: true,
  44941. configurable: true
  44942. });
  44943. /**
  44944. * Specifies whether or not this material should be rendered in alpha blend mode.
  44945. */
  44946. PBRBaseMaterial.prototype.needAlphaBlending = function () {
  44947. if (this._disableAlphaBlending) {
  44948. return false;
  44949. }
  44950. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromAlbedoTexture();
  44951. };
  44952. /**
  44953. * Specifies if the mesh will require alpha blending.
  44954. * @param mesh - BJS mesh.
  44955. */
  44956. PBRBaseMaterial.prototype.needAlphaBlendingForMesh = function (mesh) {
  44957. if (this._disableAlphaBlending) {
  44958. return false;
  44959. }
  44960. return _super.prototype.needAlphaBlendingForMesh.call(this, mesh);
  44961. };
  44962. /**
  44963. * Specifies whether or not this material should be rendered in alpha test mode.
  44964. */
  44965. PBRBaseMaterial.prototype.needAlphaTesting = function () {
  44966. if (this._forceAlphaTest) {
  44967. return true;
  44968. }
  44969. if (this._linkRefractionWithTransparency) {
  44970. return false;
  44971. }
  44972. return this._albedoTexture != null && this._albedoTexture.hasAlpha && (this._transparencyMode == null || this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  44973. };
  44974. /**
  44975. * Specifies whether or not the alpha value of the albedo texture should be used for alpha blending.
  44976. */
  44977. PBRBaseMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  44978. return this._albedoTexture != null && this._albedoTexture.hasAlpha && this._useAlphaFromAlbedoTexture && this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  44979. };
  44980. /**
  44981. * Gets the texture used for the alpha test.
  44982. */
  44983. PBRBaseMaterial.prototype.getAlphaTestTexture = function () {
  44984. return this._albedoTexture;
  44985. };
  44986. /**
  44987. * Specifies that the submesh is ready to be used.
  44988. * @param mesh - BJS mesh.
  44989. * @param subMesh - A submesh of the BJS mesh. Used to check if it is ready.
  44990. * @param useInstances - Specifies that instances should be used.
  44991. * @returns - boolean indicating that the submesh is ready or not.
  44992. */
  44993. PBRBaseMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  44994. if (subMesh.effect && this.isFrozen) {
  44995. if (this._wasPreviouslyReady) {
  44996. return true;
  44997. }
  44998. }
  44999. if (!subMesh._materialDefines) {
  45000. subMesh._materialDefines = new PBRMaterialDefines();
  45001. }
  45002. var defines = subMesh._materialDefines;
  45003. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  45004. if (defines._renderId === this.getScene().getRenderId()) {
  45005. return true;
  45006. }
  45007. }
  45008. var scene = this.getScene();
  45009. var engine = scene.getEngine();
  45010. if (defines._areTexturesDirty) {
  45011. if (scene.texturesEnabled) {
  45012. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  45013. if (!this._albedoTexture.isReadyOrNotBlocking()) {
  45014. return false;
  45015. }
  45016. }
  45017. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  45018. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  45019. return false;
  45020. }
  45021. }
  45022. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  45023. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  45024. return false;
  45025. }
  45026. }
  45027. var reflectionTexture = this._getReflectionTexture();
  45028. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  45029. if (!reflectionTexture.isReadyOrNotBlocking()) {
  45030. return false;
  45031. }
  45032. }
  45033. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  45034. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  45035. return false;
  45036. }
  45037. }
  45038. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  45039. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  45040. return false;
  45041. }
  45042. }
  45043. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  45044. if (this._metallicTexture) {
  45045. if (!this._metallicTexture.isReadyOrNotBlocking()) {
  45046. return false;
  45047. }
  45048. }
  45049. else if (this._reflectivityTexture) {
  45050. if (!this._reflectivityTexture.isReadyOrNotBlocking()) {
  45051. return false;
  45052. }
  45053. }
  45054. if (this._microSurfaceTexture) {
  45055. if (!this._microSurfaceTexture.isReadyOrNotBlocking()) {
  45056. return false;
  45057. }
  45058. }
  45059. }
  45060. if (engine.getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  45061. // Bump texture cannot be not blocking.
  45062. if (!this._bumpTexture.isReady()) {
  45063. return false;
  45064. }
  45065. }
  45066. var refractionTexture = this._getRefractionTexture();
  45067. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  45068. if (!refractionTexture.isReadyOrNotBlocking()) {
  45069. return false;
  45070. }
  45071. }
  45072. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  45073. // This is blocking.
  45074. if (!this._environmentBRDFTexture.isReady()) {
  45075. return false;
  45076. }
  45077. }
  45078. }
  45079. }
  45080. if (defines._areImageProcessingDirty) {
  45081. if (!this._imageProcessingConfiguration.isReady()) {
  45082. return false;
  45083. }
  45084. }
  45085. if (!engine.getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  45086. mesh.createNormals(true);
  45087. BABYLON.Tools.Warn("PBRMaterial: Normals have been created for the mesh: " + mesh.name);
  45088. }
  45089. var effect = this._prepareEffect(mesh, defines, this.onCompiled, this.onError, useInstances);
  45090. if (effect) {
  45091. scene.resetCachedMaterial();
  45092. subMesh.setEffect(effect, defines);
  45093. this.buildUniformLayout();
  45094. }
  45095. if (!subMesh.effect || !subMesh.effect.isReady()) {
  45096. return false;
  45097. }
  45098. defines._renderId = scene.getRenderId();
  45099. this._wasPreviouslyReady = true;
  45100. return true;
  45101. };
  45102. /**
  45103. * Specifies if the material uses metallic roughness workflow.
  45104. * @returns boolean specifiying if the material uses metallic roughness workflow.
  45105. */
  45106. PBRBaseMaterial.prototype.isMetallicWorkflow = function () {
  45107. if (this._metallic != null || this._roughness != null || this._metallicTexture) {
  45108. return true;
  45109. }
  45110. return false;
  45111. };
  45112. PBRBaseMaterial.prototype._prepareEffect = function (mesh, defines, onCompiled, onError, useInstances, useClipPlane) {
  45113. if (onCompiled === void 0) { onCompiled = null; }
  45114. if (onError === void 0) { onError = null; }
  45115. if (useInstances === void 0) { useInstances = null; }
  45116. if (useClipPlane === void 0) { useClipPlane = null; }
  45117. this._prepareDefines(mesh, defines, useInstances, useClipPlane);
  45118. if (!defines.isDirty) {
  45119. return null;
  45120. }
  45121. defines.markAsProcessed();
  45122. var scene = this.getScene();
  45123. var engine = scene.getEngine();
  45124. // Fallbacks
  45125. var fallbacks = new BABYLON.EffectFallbacks();
  45126. var fallbackRank = 0;
  45127. if (defines.USESPHERICALINVERTEX) {
  45128. fallbacks.addFallback(fallbackRank++, "USESPHERICALINVERTEX");
  45129. }
  45130. if (defines.FOG) {
  45131. fallbacks.addFallback(fallbackRank, "FOG");
  45132. }
  45133. if (defines.SPECULARAA) {
  45134. fallbacks.addFallback(fallbackRank, "SPECULARAA");
  45135. }
  45136. if (defines.POINTSIZE) {
  45137. fallbacks.addFallback(fallbackRank, "POINTSIZE");
  45138. }
  45139. if (defines.LOGARITHMICDEPTH) {
  45140. fallbacks.addFallback(fallbackRank, "LOGARITHMICDEPTH");
  45141. }
  45142. if (defines.PARALLAX) {
  45143. fallbacks.addFallback(fallbackRank, "PARALLAX");
  45144. }
  45145. if (defines.PARALLAXOCCLUSION) {
  45146. fallbacks.addFallback(fallbackRank++, "PARALLAXOCCLUSION");
  45147. }
  45148. if (defines.ENVIRONMENTBRDF) {
  45149. fallbacks.addFallback(fallbackRank++, "ENVIRONMENTBRDF");
  45150. }
  45151. if (defines.TANGENT) {
  45152. fallbacks.addFallback(fallbackRank++, "TANGENT");
  45153. }
  45154. if (defines.BUMP) {
  45155. fallbacks.addFallback(fallbackRank++, "BUMP");
  45156. }
  45157. fallbackRank = BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights, fallbackRank++);
  45158. if (defines.SPECULARTERM) {
  45159. fallbacks.addFallback(fallbackRank++, "SPECULARTERM");
  45160. }
  45161. if (defines.USESPHERICALFROMREFLECTIONMAP) {
  45162. fallbacks.addFallback(fallbackRank++, "USESPHERICALFROMREFLECTIONMAP");
  45163. }
  45164. if (defines.LIGHTMAP) {
  45165. fallbacks.addFallback(fallbackRank++, "LIGHTMAP");
  45166. }
  45167. if (defines.NORMAL) {
  45168. fallbacks.addFallback(fallbackRank++, "NORMAL");
  45169. }
  45170. if (defines.AMBIENT) {
  45171. fallbacks.addFallback(fallbackRank++, "AMBIENT");
  45172. }
  45173. if (defines.EMISSIVE) {
  45174. fallbacks.addFallback(fallbackRank++, "EMISSIVE");
  45175. }
  45176. if (defines.VERTEXCOLOR) {
  45177. fallbacks.addFallback(fallbackRank++, "VERTEXCOLOR");
  45178. }
  45179. if (defines.NUM_BONE_INFLUENCERS > 0) {
  45180. fallbacks.addCPUSkinningFallback(fallbackRank++, mesh);
  45181. }
  45182. if (defines.MORPHTARGETS) {
  45183. fallbacks.addFallback(fallbackRank++, "MORPHTARGETS");
  45184. }
  45185. //Attributes
  45186. var attribs = [BABYLON.VertexBuffer.PositionKind];
  45187. if (defines.NORMAL) {
  45188. attribs.push(BABYLON.VertexBuffer.NormalKind);
  45189. }
  45190. if (defines.TANGENT) {
  45191. attribs.push(BABYLON.VertexBuffer.TangentKind);
  45192. }
  45193. if (defines.UV1) {
  45194. attribs.push(BABYLON.VertexBuffer.UVKind);
  45195. }
  45196. if (defines.UV2) {
  45197. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  45198. }
  45199. if (defines.VERTEXCOLOR) {
  45200. attribs.push(BABYLON.VertexBuffer.ColorKind);
  45201. }
  45202. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  45203. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  45204. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  45205. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vAlbedoColor", "vReflectivityColor", "vEmissiveColor", "vReflectionColor",
  45206. "vFogInfos", "vFogColor", "pointSize",
  45207. "vAlbedoInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vReflectionPosition", "vReflectionSize", "vEmissiveInfos", "vReflectivityInfos",
  45208. "vMicroSurfaceSamplerInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  45209. "mBones",
  45210. "vClipPlane", "albedoMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "reflectivityMatrix", "normalMatrix", "microSurfaceSamplerMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  45211. "vLightingIntensity",
  45212. "logarithmicDepthConstant",
  45213. "vSphericalX", "vSphericalY", "vSphericalZ",
  45214. "vSphericalXX", "vSphericalYY", "vSphericalZZ",
  45215. "vSphericalXY", "vSphericalYZ", "vSphericalZX",
  45216. "vReflectionMicrosurfaceInfos", "vRefractionMicrosurfaceInfos",
  45217. "vTangentSpaceParams"
  45218. ];
  45219. var samplers = ["albedoSampler", "reflectivitySampler", "ambientSampler", "emissiveSampler",
  45220. "bumpSampler", "lightmapSampler", "opacitySampler",
  45221. "refractionSampler", "refractionSamplerLow", "refractionSamplerHigh",
  45222. "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh",
  45223. "microSurfaceSampler", "environmentBrdfSampler"];
  45224. var uniformBuffers = ["Material", "Scene"];
  45225. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  45226. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  45227. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  45228. uniformsNames: uniforms,
  45229. uniformBuffersNames: uniformBuffers,
  45230. samplers: samplers,
  45231. defines: defines,
  45232. maxSimultaneousLights: this._maxSimultaneousLights
  45233. });
  45234. var join = defines.toString();
  45235. return engine.createEffect("pbr", {
  45236. attributes: attribs,
  45237. uniformsNames: uniforms,
  45238. uniformBuffersNames: uniformBuffers,
  45239. samplers: samplers,
  45240. defines: join,
  45241. fallbacks: fallbacks,
  45242. onCompiled: onCompiled,
  45243. onError: onError,
  45244. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  45245. }, engine);
  45246. };
  45247. PBRBaseMaterial.prototype._prepareDefines = function (mesh, defines, useInstances, useClipPlane) {
  45248. if (useInstances === void 0) { useInstances = null; }
  45249. if (useClipPlane === void 0) { useClipPlane = null; }
  45250. var scene = this.getScene();
  45251. var engine = scene.getEngine();
  45252. // Lights
  45253. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  45254. defines._needNormals = true;
  45255. // Textures
  45256. defines.METALLICWORKFLOW = this.isMetallicWorkflow();
  45257. if (defines._areTexturesDirty) {
  45258. defines._needUVs = false;
  45259. if (scene.texturesEnabled) {
  45260. if (scene.getEngine().getCaps().textureLOD) {
  45261. defines.LODBASEDMICROSFURACE = true;
  45262. }
  45263. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  45264. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._albedoTexture, defines, "ALBEDO");
  45265. }
  45266. else {
  45267. defines.ALBEDO = false;
  45268. }
  45269. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  45270. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  45271. defines.AMBIENTINGRAYSCALE = this._useAmbientInGrayScale;
  45272. }
  45273. else {
  45274. defines.AMBIENT = false;
  45275. }
  45276. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  45277. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  45278. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  45279. }
  45280. else {
  45281. defines.OPACITY = false;
  45282. }
  45283. var reflectionTexture = this._getReflectionTexture();
  45284. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  45285. defines.REFLECTION = true;
  45286. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  45287. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  45288. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  45289. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  45290. defines.INVERTCUBICMAP = true;
  45291. }
  45292. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  45293. switch (reflectionTexture.coordinatesMode) {
  45294. case BABYLON.Texture.EXPLICIT_MODE:
  45295. defines.REFLECTIONMAP_EXPLICIT = true;
  45296. break;
  45297. case BABYLON.Texture.PLANAR_MODE:
  45298. defines.REFLECTIONMAP_PLANAR = true;
  45299. break;
  45300. case BABYLON.Texture.PROJECTION_MODE:
  45301. defines.REFLECTIONMAP_PROJECTION = true;
  45302. break;
  45303. case BABYLON.Texture.SKYBOX_MODE:
  45304. defines.REFLECTIONMAP_SKYBOX = true;
  45305. break;
  45306. case BABYLON.Texture.SPHERICAL_MODE:
  45307. defines.REFLECTIONMAP_SPHERICAL = true;
  45308. break;
  45309. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  45310. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  45311. break;
  45312. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  45313. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  45314. break;
  45315. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  45316. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  45317. break;
  45318. case BABYLON.Texture.CUBIC_MODE:
  45319. case BABYLON.Texture.INVCUBIC_MODE:
  45320. default:
  45321. defines.REFLECTIONMAP_CUBIC = true;
  45322. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = reflectionTexture.boundingBoxSize ? true : false;
  45323. break;
  45324. }
  45325. if (reflectionTexture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) {
  45326. if (reflectionTexture.sphericalPolynomial) {
  45327. defines.USESPHERICALFROMREFLECTIONMAP = true;
  45328. if (this._forceIrradianceInFragment || scene.getEngine().getCaps().maxVaryingVectors <= 8) {
  45329. defines.USESPHERICALINVERTEX = false;
  45330. }
  45331. else {
  45332. defines.USESPHERICALINVERTEX = true;
  45333. }
  45334. }
  45335. }
  45336. }
  45337. else {
  45338. defines.REFLECTION = false;
  45339. defines.REFLECTIONMAP_3D = false;
  45340. defines.REFLECTIONMAP_SPHERICAL = false;
  45341. defines.REFLECTIONMAP_PLANAR = false;
  45342. defines.REFLECTIONMAP_CUBIC = false;
  45343. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  45344. defines.REFLECTIONMAP_PROJECTION = false;
  45345. defines.REFLECTIONMAP_SKYBOX = false;
  45346. defines.REFLECTIONMAP_EXPLICIT = false;
  45347. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  45348. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  45349. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  45350. defines.INVERTCUBICMAP = false;
  45351. defines.USESPHERICALFROMREFLECTIONMAP = false;
  45352. defines.USESPHERICALINVERTEX = false;
  45353. defines.REFLECTIONMAP_OPPOSITEZ = false;
  45354. defines.LODINREFLECTIONALPHA = false;
  45355. defines.GAMMAREFLECTION = false;
  45356. }
  45357. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  45358. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  45359. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  45360. defines.GAMMALIGHTMAP = this._lightmapTexture.gammaSpace;
  45361. }
  45362. else {
  45363. defines.LIGHTMAP = false;
  45364. }
  45365. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  45366. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  45367. }
  45368. else {
  45369. defines.EMISSIVE = false;
  45370. }
  45371. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  45372. if (this._metallicTexture) {
  45373. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._metallicTexture, defines, "REFLECTIVITY");
  45374. defines.ROUGHNESSSTOREINMETALMAPALPHA = this._useRoughnessFromMetallicTextureAlpha;
  45375. defines.ROUGHNESSSTOREINMETALMAPGREEN = !this._useRoughnessFromMetallicTextureAlpha && this._useRoughnessFromMetallicTextureGreen;
  45376. defines.METALLNESSSTOREINMETALMAPBLUE = this._useMetallnessFromMetallicTextureBlue;
  45377. defines.AOSTOREINMETALMAPRED = this._useAmbientOcclusionFromMetallicTextureRed;
  45378. }
  45379. else if (this._reflectivityTexture) {
  45380. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._reflectivityTexture, defines, "REFLECTIVITY");
  45381. defines.MICROSURFACEFROMREFLECTIVITYMAP = this._useMicroSurfaceFromReflectivityMapAlpha;
  45382. defines.MICROSURFACEAUTOMATIC = this._useAutoMicroSurfaceFromReflectivityMap;
  45383. }
  45384. else {
  45385. defines.REFLECTIVITY = false;
  45386. }
  45387. if (this._microSurfaceTexture) {
  45388. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._microSurfaceTexture, defines, "MICROSURFACEMAP");
  45389. }
  45390. else {
  45391. defines.MICROSURFACEMAP = false;
  45392. }
  45393. }
  45394. else {
  45395. defines.REFLECTIVITY = false;
  45396. defines.MICROSURFACEMAP = false;
  45397. }
  45398. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  45399. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  45400. if (this._useParallax && this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  45401. defines.PARALLAX = true;
  45402. defines.PARALLAXOCCLUSION = !!this._useParallaxOcclusion;
  45403. }
  45404. else {
  45405. defines.PARALLAX = false;
  45406. }
  45407. defines.OBJECTSPACE_NORMALMAP = this._useObjectSpaceNormalMap;
  45408. }
  45409. else {
  45410. defines.BUMP = false;
  45411. }
  45412. var refractionTexture = this._getRefractionTexture();
  45413. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  45414. defines.REFRACTION = true;
  45415. defines.REFRACTIONMAP_3D = refractionTexture.isCube;
  45416. defines.GAMMAREFRACTION = refractionTexture.gammaSpace;
  45417. defines.REFRACTIONMAP_OPPOSITEZ = refractionTexture.invertZ;
  45418. defines.LODINREFRACTIONALPHA = refractionTexture.lodLevelInAlpha;
  45419. if (this._linkRefractionWithTransparency) {
  45420. defines.LINKREFRACTIONTOTRANSPARENCY = true;
  45421. }
  45422. }
  45423. else {
  45424. defines.REFRACTION = false;
  45425. }
  45426. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  45427. defines.ENVIRONMENTBRDF = true;
  45428. }
  45429. else {
  45430. defines.ENVIRONMENTBRDF = false;
  45431. }
  45432. if (this._shouldUseAlphaFromAlbedoTexture()) {
  45433. defines.ALPHAFROMALBEDO = true;
  45434. }
  45435. else {
  45436. defines.ALPHAFROMALBEDO = false;
  45437. }
  45438. }
  45439. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  45440. defines.USEPHYSICALLIGHTFALLOFF = this._usePhysicalLightFalloff;
  45441. defines.RADIANCEOVERALPHA = this._useRadianceOverAlpha;
  45442. if (!this.backFaceCulling && this._twoSidedLighting) {
  45443. defines.TWOSIDEDLIGHTING = true;
  45444. }
  45445. else {
  45446. defines.TWOSIDEDLIGHTING = false;
  45447. }
  45448. defines.ALPHATESTVALUE = "" + this._alphaCutOff + (this._alphaCutOff % 1 === 0 ? "." : "");
  45449. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  45450. defines.ALPHABLEND = this.needAlphaBlendingForMesh(mesh);
  45451. defines.ALPHAFRESNEL = this._useAlphaFresnel || this._useLinearAlphaFresnel;
  45452. defines.LINEARALPHAFRESNEL = this._useLinearAlphaFresnel;
  45453. defines.SPECULARAA = scene.getEngine().getCaps().standardDerivatives && this._enableSpecularAntiAliasing;
  45454. }
  45455. if (defines._areImageProcessingDirty) {
  45456. this._imageProcessingConfiguration.prepareDefines(defines);
  45457. }
  45458. defines.FORCENORMALFORWARD = this._forceNormalForward;
  45459. defines.RADIANCEOCCLUSION = this._useRadianceOcclusion;
  45460. defines.HORIZONOCCLUSION = this._useHorizonOcclusion;
  45461. // Misc.
  45462. if (defines._areMiscDirty) {
  45463. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh) || this._forceAlphaTest, defines);
  45464. defines.UNLIT = this._unlit || ((this.pointsCloud || this.wireframe) && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  45465. }
  45466. // Values that need to be evaluated on every frame
  45467. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances ? true : false, useClipPlane);
  45468. // Attribs
  45469. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true, this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE);
  45470. };
  45471. /**
  45472. * Force shader compilation
  45473. */
  45474. PBRBaseMaterial.prototype.forceCompilation = function (mesh, onCompiled, options) {
  45475. var _this = this;
  45476. var localOptions = __assign({ clipPlane: false }, options);
  45477. var defines = new PBRMaterialDefines();
  45478. var effect = this._prepareEffect(mesh, defines, undefined, undefined, undefined, localOptions.clipPlane);
  45479. if (effect.isReady()) {
  45480. if (onCompiled) {
  45481. onCompiled(this);
  45482. }
  45483. }
  45484. else {
  45485. effect.onCompileObservable.add(function () {
  45486. if (onCompiled) {
  45487. onCompiled(_this);
  45488. }
  45489. });
  45490. }
  45491. };
  45492. /**
  45493. * Initializes the uniform buffer layout for the shader.
  45494. */
  45495. PBRBaseMaterial.prototype.buildUniformLayout = function () {
  45496. // Order is important !
  45497. this._uniformBuffer.addUniform("vAlbedoInfos", 2);
  45498. this._uniformBuffer.addUniform("vAmbientInfos", 3);
  45499. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  45500. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  45501. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  45502. this._uniformBuffer.addUniform("vReflectivityInfos", 3);
  45503. this._uniformBuffer.addUniform("vMicroSurfaceSamplerInfos", 2);
  45504. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  45505. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  45506. this._uniformBuffer.addUniform("vReflectionPosition", 3);
  45507. this._uniformBuffer.addUniform("vReflectionSize", 3);
  45508. this._uniformBuffer.addUniform("vBumpInfos", 3);
  45509. this._uniformBuffer.addUniform("albedoMatrix", 16);
  45510. this._uniformBuffer.addUniform("ambientMatrix", 16);
  45511. this._uniformBuffer.addUniform("opacityMatrix", 16);
  45512. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  45513. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  45514. this._uniformBuffer.addUniform("reflectivityMatrix", 16);
  45515. this._uniformBuffer.addUniform("microSurfaceSamplerMatrix", 16);
  45516. this._uniformBuffer.addUniform("bumpMatrix", 16);
  45517. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  45518. this._uniformBuffer.addUniform("refractionMatrix", 16);
  45519. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  45520. this._uniformBuffer.addUniform("vReflectionColor", 3);
  45521. this._uniformBuffer.addUniform("vAlbedoColor", 4);
  45522. this._uniformBuffer.addUniform("vLightingIntensity", 4);
  45523. this._uniformBuffer.addUniform("vRefractionMicrosurfaceInfos", 3);
  45524. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  45525. this._uniformBuffer.addUniform("vReflectivityColor", 4);
  45526. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  45527. this._uniformBuffer.addUniform("pointSize", 1);
  45528. this._uniformBuffer.create();
  45529. };
  45530. /**
  45531. * Unbinds the textures.
  45532. */
  45533. PBRBaseMaterial.prototype.unbind = function () {
  45534. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  45535. this._uniformBuffer.setTexture("reflectionSampler", null);
  45536. }
  45537. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  45538. this._uniformBuffer.setTexture("refractionSampler", null);
  45539. }
  45540. _super.prototype.unbind.call(this);
  45541. };
  45542. /**
  45543. * Binds the submesh data.
  45544. * @param world - The world matrix.
  45545. * @param mesh - The BJS mesh.
  45546. * @param subMesh - A submesh of the BJS mesh.
  45547. */
  45548. PBRBaseMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  45549. var scene = this.getScene();
  45550. var defines = subMesh._materialDefines;
  45551. if (!defines) {
  45552. return;
  45553. }
  45554. var effect = subMesh.effect;
  45555. if (!effect) {
  45556. return;
  45557. }
  45558. this._activeEffect = effect;
  45559. // Matrices
  45560. this.bindOnlyWorldMatrix(world);
  45561. // Normal Matrix
  45562. if (defines.OBJECTSPACE_NORMALMAP) {
  45563. world.toNormalMatrix(this._normalMatrix);
  45564. this.bindOnlyNormalMatrix(this._normalMatrix);
  45565. }
  45566. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  45567. // Bones
  45568. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  45569. var reflectionTexture = null;
  45570. if (mustRebind) {
  45571. this._uniformBuffer.bindToEffect(effect, "Material");
  45572. this.bindViewProjection(effect);
  45573. reflectionTexture = this._getReflectionTexture();
  45574. var refractionTexture = this._getRefractionTexture();
  45575. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  45576. // Texture uniforms
  45577. if (scene.texturesEnabled) {
  45578. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  45579. this._uniformBuffer.updateFloat2("vAlbedoInfos", this._albedoTexture.coordinatesIndex, this._albedoTexture.level);
  45580. BABYLON.MaterialHelper.BindTextureMatrix(this._albedoTexture, this._uniformBuffer, "albedo");
  45581. }
  45582. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  45583. this._uniformBuffer.updateFloat3("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level, this._ambientTextureStrength);
  45584. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  45585. }
  45586. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  45587. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  45588. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  45589. }
  45590. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  45591. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  45592. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, 0);
  45593. if (reflectionTexture.boundingBoxSize) {
  45594. var cubeTexture = reflectionTexture;
  45595. this._uniformBuffer.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition);
  45596. this._uniformBuffer.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize);
  45597. }
  45598. var polynomials = reflectionTexture.sphericalPolynomial;
  45599. if (defines.USESPHERICALFROMREFLECTIONMAP && polynomials) {
  45600. this._activeEffect.setFloat3("vSphericalX", polynomials.x.x, polynomials.x.y, polynomials.x.z);
  45601. this._activeEffect.setFloat3("vSphericalY", polynomials.y.x, polynomials.y.y, polynomials.y.z);
  45602. this._activeEffect.setFloat3("vSphericalZ", polynomials.z.x, polynomials.z.y, polynomials.z.z);
  45603. this._activeEffect.setFloat3("vSphericalXX_ZZ", polynomials.xx.x - polynomials.zz.x, polynomials.xx.y - polynomials.zz.y, polynomials.xx.z - polynomials.zz.z);
  45604. this._activeEffect.setFloat3("vSphericalYY_ZZ", polynomials.yy.x - polynomials.zz.x, polynomials.yy.y - polynomials.zz.y, polynomials.yy.z - polynomials.zz.z);
  45605. this._activeEffect.setFloat3("vSphericalZZ", polynomials.zz.x, polynomials.zz.y, polynomials.zz.z);
  45606. this._activeEffect.setFloat3("vSphericalXY", polynomials.xy.x, polynomials.xy.y, polynomials.xy.z);
  45607. this._activeEffect.setFloat3("vSphericalYZ", polynomials.yz.x, polynomials.yz.y, polynomials.yz.z);
  45608. this._activeEffect.setFloat3("vSphericalZX", polynomials.zx.x, polynomials.zx.y, polynomials.zx.z);
  45609. }
  45610. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  45611. }
  45612. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  45613. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  45614. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  45615. }
  45616. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  45617. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  45618. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  45619. }
  45620. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  45621. if (this._metallicTexture) {
  45622. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._metallicTexture.coordinatesIndex, this._metallicTexture.level, this._ambientTextureStrength);
  45623. BABYLON.MaterialHelper.BindTextureMatrix(this._metallicTexture, this._uniformBuffer, "reflectivity");
  45624. }
  45625. else if (this._reflectivityTexture) {
  45626. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._reflectivityTexture.coordinatesIndex, this._reflectivityTexture.level, 1.0);
  45627. BABYLON.MaterialHelper.BindTextureMatrix(this._reflectivityTexture, this._uniformBuffer, "reflectivity");
  45628. }
  45629. if (this._microSurfaceTexture) {
  45630. this._uniformBuffer.updateFloat2("vMicroSurfaceSamplerInfos", this._microSurfaceTexture.coordinatesIndex, this._microSurfaceTexture.level);
  45631. BABYLON.MaterialHelper.BindTextureMatrix(this._microSurfaceTexture, this._uniformBuffer, "microSurfaceSampler");
  45632. }
  45633. }
  45634. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  45635. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, this._bumpTexture.level, this._parallaxScaleBias);
  45636. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  45637. if (scene._mirroredCameraPosition) {
  45638. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  45639. }
  45640. else {
  45641. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  45642. }
  45643. }
  45644. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  45645. this._uniformBuffer.updateMatrix("refractionMatrix", refractionTexture.getReflectionTextureMatrix());
  45646. var depth = 1.0;
  45647. if (!refractionTexture.isCube) {
  45648. if (refractionTexture.depth) {
  45649. depth = refractionTexture.depth;
  45650. }
  45651. }
  45652. this._uniformBuffer.updateFloat4("vRefractionInfos", refractionTexture.level, this._indexOfRefraction, depth, this._invertRefractionY ? -1 : 1);
  45653. this._uniformBuffer.updateFloat3("vRefractionMicrosurfaceInfos", refractionTexture.getSize().width, refractionTexture.lodGenerationScale, refractionTexture.lodGenerationOffset);
  45654. }
  45655. }
  45656. // Point size
  45657. if (this.pointsCloud) {
  45658. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  45659. }
  45660. // Colors
  45661. if (defines.METALLICWORKFLOW) {
  45662. BABYLON.PBRMaterial._scaledReflectivity.r = (this._metallic === undefined || this._metallic === null) ? 1 : this._metallic;
  45663. BABYLON.PBRMaterial._scaledReflectivity.g = (this._roughness === undefined || this._roughness === null) ? 1 : this._roughness;
  45664. this._uniformBuffer.updateColor4("vReflectivityColor", BABYLON.PBRMaterial._scaledReflectivity, 0);
  45665. }
  45666. else {
  45667. this._uniformBuffer.updateColor4("vReflectivityColor", this._reflectivityColor, this._microSurface);
  45668. }
  45669. this._uniformBuffer.updateColor3("vEmissiveColor", this._emissiveColor);
  45670. this._uniformBuffer.updateColor3("vReflectionColor", this._reflectionColor);
  45671. this._uniformBuffer.updateColor4("vAlbedoColor", this._albedoColor, this.alpha * mesh.visibility);
  45672. // Misc
  45673. this._lightingInfos.x = this._directIntensity;
  45674. this._lightingInfos.y = this._emissiveIntensity;
  45675. this._lightingInfos.z = this._environmentIntensity;
  45676. this._lightingInfos.w = this._specularIntensity;
  45677. this._uniformBuffer.updateVector4("vLightingIntensity", this._lightingInfos);
  45678. }
  45679. // Textures
  45680. if (scene.texturesEnabled) {
  45681. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  45682. this._uniformBuffer.setTexture("albedoSampler", this._albedoTexture);
  45683. }
  45684. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  45685. this._uniformBuffer.setTexture("ambientSampler", this._ambientTexture);
  45686. }
  45687. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  45688. this._uniformBuffer.setTexture("opacitySampler", this._opacityTexture);
  45689. }
  45690. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  45691. if (defines.LODBASEDMICROSFURACE) {
  45692. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  45693. }
  45694. else {
  45695. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  45696. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  45697. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  45698. }
  45699. }
  45700. if (defines.ENVIRONMENTBRDF) {
  45701. this._uniformBuffer.setTexture("environmentBrdfSampler", this._environmentBRDFTexture);
  45702. }
  45703. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  45704. if (defines.LODBASEDMICROSFURACE) {
  45705. this._uniformBuffer.setTexture("refractionSampler", refractionTexture);
  45706. }
  45707. else {
  45708. this._uniformBuffer.setTexture("refractionSampler", refractionTexture._lodTextureMid || refractionTexture);
  45709. this._uniformBuffer.setTexture("refractionSamplerLow", refractionTexture._lodTextureLow || refractionTexture);
  45710. this._uniformBuffer.setTexture("refractionSamplerHigh", refractionTexture._lodTextureHigh || refractionTexture);
  45711. }
  45712. }
  45713. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  45714. this._uniformBuffer.setTexture("emissiveSampler", this._emissiveTexture);
  45715. }
  45716. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  45717. this._uniformBuffer.setTexture("lightmapSampler", this._lightmapTexture);
  45718. }
  45719. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  45720. if (this._metallicTexture) {
  45721. this._uniformBuffer.setTexture("reflectivitySampler", this._metallicTexture);
  45722. }
  45723. else if (this._reflectivityTexture) {
  45724. this._uniformBuffer.setTexture("reflectivitySampler", this._reflectivityTexture);
  45725. }
  45726. if (this._microSurfaceTexture) {
  45727. this._uniformBuffer.setTexture("microSurfaceSampler", this._microSurfaceTexture);
  45728. }
  45729. }
  45730. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  45731. this._uniformBuffer.setTexture("bumpSampler", this._bumpTexture);
  45732. }
  45733. }
  45734. // Clip plane
  45735. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  45736. // Colors
  45737. scene.ambientColor.multiplyToRef(this._ambientColor, this._globalAmbientColor);
  45738. var eyePosition = scene._forcedViewPosition ? scene._forcedViewPosition : (scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  45739. var invertNormal = (scene.useRightHandedSystem === (scene._mirroredCameraPosition != null));
  45740. effect.setFloat4("vEyePosition", eyePosition.x, eyePosition.y, eyePosition.z, invertNormal ? -1 : 1);
  45741. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  45742. }
  45743. if (mustRebind || !this.isFrozen) {
  45744. // Lights
  45745. if (scene.lightsEnabled && !this._disableLighting) {
  45746. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, this._usePhysicalLightFalloff);
  45747. }
  45748. // View
  45749. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || reflectionTexture) {
  45750. this.bindView(effect);
  45751. }
  45752. // Fog
  45753. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  45754. // Morph targets
  45755. if (defines.NUM_MORPH_INFLUENCERS) {
  45756. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._activeEffect);
  45757. }
  45758. // image processing
  45759. this._imageProcessingConfiguration.bind(this._activeEffect);
  45760. // Log. depth
  45761. BABYLON.MaterialHelper.BindLogDepth(defines, this._activeEffect, scene);
  45762. }
  45763. this._uniformBuffer.update();
  45764. this._afterBind(mesh, this._activeEffect);
  45765. };
  45766. /**
  45767. * Returns the animatable textures.
  45768. * @returns - Array of animatable textures.
  45769. */
  45770. PBRBaseMaterial.prototype.getAnimatables = function () {
  45771. var results = [];
  45772. if (this._albedoTexture && this._albedoTexture.animations && this._albedoTexture.animations.length > 0) {
  45773. results.push(this._albedoTexture);
  45774. }
  45775. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  45776. results.push(this._ambientTexture);
  45777. }
  45778. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  45779. results.push(this._opacityTexture);
  45780. }
  45781. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  45782. results.push(this._reflectionTexture);
  45783. }
  45784. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  45785. results.push(this._emissiveTexture);
  45786. }
  45787. if (this._metallicTexture && this._metallicTexture.animations && this._metallicTexture.animations.length > 0) {
  45788. results.push(this._metallicTexture);
  45789. }
  45790. else if (this._reflectivityTexture && this._reflectivityTexture.animations && this._reflectivityTexture.animations.length > 0) {
  45791. results.push(this._reflectivityTexture);
  45792. }
  45793. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  45794. results.push(this._bumpTexture);
  45795. }
  45796. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  45797. results.push(this._lightmapTexture);
  45798. }
  45799. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  45800. results.push(this._refractionTexture);
  45801. }
  45802. return results;
  45803. };
  45804. /**
  45805. * Returns the texture used for reflections.
  45806. * @returns - Reflection texture if present. Otherwise, returns the environment texture.
  45807. */
  45808. PBRBaseMaterial.prototype._getReflectionTexture = function () {
  45809. if (this._reflectionTexture) {
  45810. return this._reflectionTexture;
  45811. }
  45812. return this.getScene().environmentTexture;
  45813. };
  45814. /**
  45815. * Returns the texture used for refraction or null if none is used.
  45816. * @returns - Refection texture if present. If no refraction texture and refraction
  45817. * is linked with transparency, returns environment texture. Otherwise, returns null.
  45818. */
  45819. PBRBaseMaterial.prototype._getRefractionTexture = function () {
  45820. if (this._refractionTexture) {
  45821. return this._refractionTexture;
  45822. }
  45823. if (this._linkRefractionWithTransparency) {
  45824. return this.getScene().environmentTexture;
  45825. }
  45826. return null;
  45827. };
  45828. /**
  45829. * Disposes the resources of the material.
  45830. * @param forceDisposeEffect - Forces the disposal of effects.
  45831. * @param forceDisposeTextures - Forces the disposal of all textures.
  45832. */
  45833. PBRBaseMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  45834. if (forceDisposeTextures) {
  45835. if (this._albedoTexture) {
  45836. this._albedoTexture.dispose();
  45837. }
  45838. if (this._ambientTexture) {
  45839. this._ambientTexture.dispose();
  45840. }
  45841. if (this._opacityTexture) {
  45842. this._opacityTexture.dispose();
  45843. }
  45844. if (this._reflectionTexture) {
  45845. this._reflectionTexture.dispose();
  45846. }
  45847. if (this._environmentBRDFTexture && this.getScene()._environmentBRDFTexture !== this._environmentBRDFTexture) {
  45848. this._environmentBRDFTexture.dispose();
  45849. }
  45850. if (this._emissiveTexture) {
  45851. this._emissiveTexture.dispose();
  45852. }
  45853. if (this._metallicTexture) {
  45854. this._metallicTexture.dispose();
  45855. }
  45856. if (this._reflectivityTexture) {
  45857. this._reflectivityTexture.dispose();
  45858. }
  45859. if (this._bumpTexture) {
  45860. this._bumpTexture.dispose();
  45861. }
  45862. if (this._lightmapTexture) {
  45863. this._lightmapTexture.dispose();
  45864. }
  45865. if (this._refractionTexture) {
  45866. this._refractionTexture.dispose();
  45867. }
  45868. }
  45869. this._renderTargets.dispose();
  45870. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  45871. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  45872. }
  45873. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  45874. };
  45875. /**
  45876. * Stores the reflectivity values based on metallic roughness workflow.
  45877. */
  45878. PBRBaseMaterial._scaledReflectivity = new BABYLON.Color3();
  45879. __decorate([
  45880. BABYLON.serializeAsImageProcessingConfiguration()
  45881. ], PBRBaseMaterial.prototype, "_imageProcessingConfiguration", void 0);
  45882. __decorate([
  45883. BABYLON.serialize()
  45884. ], PBRBaseMaterial.prototype, "useLogarithmicDepth", null);
  45885. __decorate([
  45886. BABYLON.serialize()
  45887. ], PBRBaseMaterial.prototype, "transparencyMode", null);
  45888. return PBRBaseMaterial;
  45889. }(BABYLON.PushMaterial));
  45890. BABYLON.PBRBaseMaterial = PBRBaseMaterial;
  45891. })(BABYLON || (BABYLON = {}));
  45892. //# sourceMappingURL=babylon.pbrBaseMaterial.js.map
  45893. var BABYLON;
  45894. (function (BABYLON) {
  45895. /**
  45896. * The Physically based simple base material of BJS.
  45897. *
  45898. * This enables better naming and convention enforcements on top of the pbrMaterial.
  45899. * It is used as the base class for both the specGloss and metalRough conventions.
  45900. */
  45901. var PBRBaseSimpleMaterial = /** @class */ (function (_super) {
  45902. __extends(PBRBaseSimpleMaterial, _super);
  45903. /**
  45904. * Instantiates a new PBRMaterial instance.
  45905. *
  45906. * @param name The material name
  45907. * @param scene The scene the material will be use in.
  45908. */
  45909. function PBRBaseSimpleMaterial(name, scene) {
  45910. var _this = _super.call(this, name, scene) || this;
  45911. /**
  45912. * Number of Simultaneous lights allowed on the material.
  45913. */
  45914. _this.maxSimultaneousLights = 4;
  45915. /**
  45916. * If sets to true, disables all the lights affecting the material.
  45917. */
  45918. _this.disableLighting = false;
  45919. /**
  45920. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  45921. */
  45922. _this.invertNormalMapX = false;
  45923. /**
  45924. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  45925. */
  45926. _this.invertNormalMapY = false;
  45927. /**
  45928. * Emissivie color used to self-illuminate the model.
  45929. */
  45930. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  45931. /**
  45932. * Occlusion Channel Strenght.
  45933. */
  45934. _this.occlusionStrength = 1.0;
  45935. _this.useLightmapAsShadowmap = false;
  45936. _this._useAlphaFromAlbedoTexture = true;
  45937. _this._useAmbientInGrayScale = true;
  45938. return _this;
  45939. }
  45940. Object.defineProperty(PBRBaseSimpleMaterial.prototype, "doubleSided", {
  45941. /**
  45942. * Gets the current double sided mode.
  45943. */
  45944. get: function () {
  45945. return this._twoSidedLighting;
  45946. },
  45947. /**
  45948. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  45949. */
  45950. set: function (value) {
  45951. if (this._twoSidedLighting === value) {
  45952. return;
  45953. }
  45954. this._twoSidedLighting = value;
  45955. this.backFaceCulling = !value;
  45956. this._markAllSubMeshesAsTexturesDirty();
  45957. },
  45958. enumerable: true,
  45959. configurable: true
  45960. });
  45961. /**
  45962. * Return the active textures of the material.
  45963. */
  45964. PBRBaseSimpleMaterial.prototype.getActiveTextures = function () {
  45965. var activeTextures = _super.prototype.getActiveTextures.call(this);
  45966. if (this.environmentTexture) {
  45967. activeTextures.push(this.environmentTexture);
  45968. }
  45969. if (this.normalTexture) {
  45970. activeTextures.push(this.normalTexture);
  45971. }
  45972. if (this.emissiveTexture) {
  45973. activeTextures.push(this.emissiveTexture);
  45974. }
  45975. if (this.occlusionTexture) {
  45976. activeTextures.push(this.occlusionTexture);
  45977. }
  45978. if (this.lightmapTexture) {
  45979. activeTextures.push(this.lightmapTexture);
  45980. }
  45981. return activeTextures;
  45982. };
  45983. PBRBaseSimpleMaterial.prototype.hasTexture = function (texture) {
  45984. if (_super.prototype.hasTexture.call(this, texture)) {
  45985. return true;
  45986. }
  45987. if (this.lightmapTexture === texture) {
  45988. return true;
  45989. }
  45990. return false;
  45991. };
  45992. PBRBaseSimpleMaterial.prototype.getClassName = function () {
  45993. return "PBRBaseSimpleMaterial";
  45994. };
  45995. __decorate([
  45996. BABYLON.serialize(),
  45997. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  45998. ], PBRBaseSimpleMaterial.prototype, "maxSimultaneousLights", void 0);
  45999. __decorate([
  46000. BABYLON.serialize(),
  46001. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  46002. ], PBRBaseSimpleMaterial.prototype, "disableLighting", void 0);
  46003. __decorate([
  46004. BABYLON.serializeAsTexture(),
  46005. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectionTexture")
  46006. ], PBRBaseSimpleMaterial.prototype, "environmentTexture", void 0);
  46007. __decorate([
  46008. BABYLON.serialize(),
  46009. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46010. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapX", void 0);
  46011. __decorate([
  46012. BABYLON.serialize(),
  46013. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46014. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapY", void 0);
  46015. __decorate([
  46016. BABYLON.serializeAsTexture(),
  46017. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_bumpTexture")
  46018. ], PBRBaseSimpleMaterial.prototype, "normalTexture", void 0);
  46019. __decorate([
  46020. BABYLON.serializeAsColor3("emissive"),
  46021. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46022. ], PBRBaseSimpleMaterial.prototype, "emissiveColor", void 0);
  46023. __decorate([
  46024. BABYLON.serializeAsTexture(),
  46025. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46026. ], PBRBaseSimpleMaterial.prototype, "emissiveTexture", void 0);
  46027. __decorate([
  46028. BABYLON.serialize(),
  46029. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTextureStrength")
  46030. ], PBRBaseSimpleMaterial.prototype, "occlusionStrength", void 0);
  46031. __decorate([
  46032. BABYLON.serializeAsTexture(),
  46033. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTexture")
  46034. ], PBRBaseSimpleMaterial.prototype, "occlusionTexture", void 0);
  46035. __decorate([
  46036. BABYLON.serialize(),
  46037. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_alphaCutOff")
  46038. ], PBRBaseSimpleMaterial.prototype, "alphaCutOff", void 0);
  46039. __decorate([
  46040. BABYLON.serialize()
  46041. ], PBRBaseSimpleMaterial.prototype, "doubleSided", null);
  46042. __decorate([
  46043. BABYLON.serializeAsTexture(),
  46044. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  46045. ], PBRBaseSimpleMaterial.prototype, "lightmapTexture", void 0);
  46046. __decorate([
  46047. BABYLON.serialize(),
  46048. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46049. ], PBRBaseSimpleMaterial.prototype, "useLightmapAsShadowmap", void 0);
  46050. return PBRBaseSimpleMaterial;
  46051. }(BABYLON.PBRBaseMaterial));
  46052. BABYLON.PBRBaseSimpleMaterial = PBRBaseSimpleMaterial;
  46053. })(BABYLON || (BABYLON = {}));
  46054. //# sourceMappingURL=babylon.pbrBaseSimpleMaterial.js.map
  46055. var BABYLON;
  46056. (function (BABYLON) {
  46057. /**
  46058. * The Physically based material of BJS.
  46059. *
  46060. * This offers the main features of a standard PBR material.
  46061. * For more information, please refer to the documentation :
  46062. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  46063. */
  46064. var PBRMaterial = /** @class */ (function (_super) {
  46065. __extends(PBRMaterial, _super);
  46066. /**
  46067. * Instantiates a new PBRMaterial instance.
  46068. *
  46069. * @param name The material name
  46070. * @param scene The scene the material will be use in.
  46071. */
  46072. function PBRMaterial(name, scene) {
  46073. var _this = _super.call(this, name, scene) || this;
  46074. /**
  46075. * Intensity of the direct lights e.g. the four lights available in your scene.
  46076. * This impacts both the direct diffuse and specular highlights.
  46077. */
  46078. _this.directIntensity = 1.0;
  46079. /**
  46080. * Intensity of the emissive part of the material.
  46081. * This helps controlling the emissive effect without modifying the emissive color.
  46082. */
  46083. _this.emissiveIntensity = 1.0;
  46084. /**
  46085. * Intensity of the environment e.g. how much the environment will light the object
  46086. * either through harmonics for rough material or through the refelction for shiny ones.
  46087. */
  46088. _this.environmentIntensity = 1.0;
  46089. /**
  46090. * This is a special control allowing the reduction of the specular highlights coming from the
  46091. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  46092. */
  46093. _this.specularIntensity = 1.0;
  46094. /**
  46095. * Debug Control allowing disabling the bump map on this material.
  46096. */
  46097. _this.disableBumpMap = false;
  46098. /**
  46099. * AKA Occlusion Texture Intensity in other nomenclature.
  46100. */
  46101. _this.ambientTextureStrength = 1.0;
  46102. /**
  46103. * The color of a material in ambient lighting.
  46104. */
  46105. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  46106. /**
  46107. * AKA Diffuse Color in other nomenclature.
  46108. */
  46109. _this.albedoColor = new BABYLON.Color3(1, 1, 1);
  46110. /**
  46111. * AKA Specular Color in other nomenclature.
  46112. */
  46113. _this.reflectivityColor = new BABYLON.Color3(1, 1, 1);
  46114. /**
  46115. * The color reflected from the material.
  46116. */
  46117. _this.reflectionColor = new BABYLON.Color3(1.0, 1.0, 1.0);
  46118. /**
  46119. * The color emitted from the material.
  46120. */
  46121. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  46122. /**
  46123. * AKA Glossiness in other nomenclature.
  46124. */
  46125. _this.microSurface = 1.0;
  46126. /**
  46127. * source material index of refraction (IOR)' / 'destination material IOR.
  46128. */
  46129. _this.indexOfRefraction = 0.66;
  46130. /**
  46131. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  46132. */
  46133. _this.invertRefractionY = false;
  46134. /**
  46135. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  46136. * Materials half opaque for instance using refraction could benefit from this control.
  46137. */
  46138. _this.linkRefractionWithTransparency = false;
  46139. _this.useLightmapAsShadowmap = false;
  46140. /**
  46141. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  46142. */
  46143. _this.useAlphaFromAlbedoTexture = false;
  46144. /**
  46145. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  46146. */
  46147. _this.forceAlphaTest = false;
  46148. /**
  46149. * Defines the alpha limits in alpha test mode.
  46150. */
  46151. _this.alphaCutOff = 0.4;
  46152. /**
  46153. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  46154. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  46155. */
  46156. _this.useSpecularOverAlpha = true;
  46157. /**
  46158. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  46159. */
  46160. _this.useMicroSurfaceFromReflectivityMapAlpha = false;
  46161. /**
  46162. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  46163. */
  46164. _this.useRoughnessFromMetallicTextureAlpha = true;
  46165. /**
  46166. * Specifies if the metallic texture contains the roughness information in its green channel.
  46167. */
  46168. _this.useRoughnessFromMetallicTextureGreen = false;
  46169. /**
  46170. * Specifies if the metallic texture contains the metallness information in its blue channel.
  46171. */
  46172. _this.useMetallnessFromMetallicTextureBlue = false;
  46173. /**
  46174. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  46175. */
  46176. _this.useAmbientOcclusionFromMetallicTextureRed = false;
  46177. /**
  46178. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  46179. */
  46180. _this.useAmbientInGrayScale = false;
  46181. /**
  46182. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  46183. * The material will try to infer what glossiness each pixel should be.
  46184. */
  46185. _this.useAutoMicroSurfaceFromReflectivityMap = false;
  46186. /**
  46187. * BJS is using an harcoded light falloff based on a manually sets up range.
  46188. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  46189. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  46190. */
  46191. _this.usePhysicalLightFalloff = true;
  46192. /**
  46193. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  46194. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  46195. */
  46196. _this.useRadianceOverAlpha = true;
  46197. /**
  46198. * Allows using an object space normal map (instead of tangent space).
  46199. */
  46200. _this.useObjectSpaceNormalMap = false;
  46201. /**
  46202. * Allows using the bump map in parallax mode.
  46203. */
  46204. _this.useParallax = false;
  46205. /**
  46206. * Allows using the bump map in parallax occlusion mode.
  46207. */
  46208. _this.useParallaxOcclusion = false;
  46209. /**
  46210. * Controls the scale bias of the parallax mode.
  46211. */
  46212. _this.parallaxScaleBias = 0.05;
  46213. /**
  46214. * If sets to true, disables all the lights affecting the material.
  46215. */
  46216. _this.disableLighting = false;
  46217. /**
  46218. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  46219. */
  46220. _this.forceIrradianceInFragment = false;
  46221. /**
  46222. * Number of Simultaneous lights allowed on the material.
  46223. */
  46224. _this.maxSimultaneousLights = 4;
  46225. /**
  46226. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  46227. */
  46228. _this.invertNormalMapX = false;
  46229. /**
  46230. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  46231. */
  46232. _this.invertNormalMapY = false;
  46233. /**
  46234. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  46235. */
  46236. _this.twoSidedLighting = false;
  46237. /**
  46238. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  46239. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  46240. */
  46241. _this.useAlphaFresnel = false;
  46242. /**
  46243. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  46244. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  46245. */
  46246. _this.useLinearAlphaFresnel = false;
  46247. /**
  46248. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  46249. * And/Or occlude the blended part.
  46250. */
  46251. _this.environmentBRDFTexture = null;
  46252. /**
  46253. * Force normal to face away from face.
  46254. */
  46255. _this.forceNormalForward = false;
  46256. /**
  46257. * Enables specular anti aliasing in the PBR shader.
  46258. * It will both interacts on the Geometry for analytical and IBL lighting.
  46259. * It also prefilter the roughness map based on the bump values.
  46260. */
  46261. _this.enableSpecularAntiAliasing = false;
  46262. /**
  46263. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  46264. * makes the reflect vector face the model (under horizon).
  46265. */
  46266. _this.useHorizonOcclusion = true;
  46267. /**
  46268. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  46269. * too much the area relying on ambient texture to define their ambient occlusion.
  46270. */
  46271. _this.useRadianceOcclusion = true;
  46272. /**
  46273. * If set to true, no lighting calculations will be applied.
  46274. */
  46275. _this.unlit = false;
  46276. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  46277. return _this;
  46278. }
  46279. Object.defineProperty(PBRMaterial, "PBRMATERIAL_OPAQUE", {
  46280. /**
  46281. * PBRMaterialTransparencyMode: No transparency mode, Alpha channel is not use.
  46282. */
  46283. get: function () {
  46284. return this._PBRMATERIAL_OPAQUE;
  46285. },
  46286. enumerable: true,
  46287. configurable: true
  46288. });
  46289. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATEST", {
  46290. /**
  46291. * PBRMaterialTransparencyMode: Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  46292. */
  46293. get: function () {
  46294. return this._PBRMATERIAL_ALPHATEST;
  46295. },
  46296. enumerable: true,
  46297. configurable: true
  46298. });
  46299. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHABLEND", {
  46300. /**
  46301. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  46302. */
  46303. get: function () {
  46304. return this._PBRMATERIAL_ALPHABLEND;
  46305. },
  46306. enumerable: true,
  46307. configurable: true
  46308. });
  46309. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATESTANDBLEND", {
  46310. /**
  46311. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  46312. * They are also discarded below the alpha cutoff threshold to improve performances.
  46313. */
  46314. get: function () {
  46315. return this._PBRMATERIAL_ALPHATESTANDBLEND;
  46316. },
  46317. enumerable: true,
  46318. configurable: true
  46319. });
  46320. Object.defineProperty(PBRMaterial.prototype, "imageProcessingConfiguration", {
  46321. /**
  46322. * Gets the image processing configuration used either in this material.
  46323. */
  46324. get: function () {
  46325. return this._imageProcessingConfiguration;
  46326. },
  46327. /**
  46328. * Sets the Default image processing configuration used either in the this material.
  46329. *
  46330. * If sets to null, the scene one is in use.
  46331. */
  46332. set: function (value) {
  46333. this._attachImageProcessingConfiguration(value);
  46334. // Ensure the effect will be rebuilt.
  46335. this._markAllSubMeshesAsTexturesDirty();
  46336. },
  46337. enumerable: true,
  46338. configurable: true
  46339. });
  46340. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurvesEnabled", {
  46341. /**
  46342. * Gets wether the color curves effect is enabled.
  46343. */
  46344. get: function () {
  46345. return this.imageProcessingConfiguration.colorCurvesEnabled;
  46346. },
  46347. /**
  46348. * Sets wether the color curves effect is enabled.
  46349. */
  46350. set: function (value) {
  46351. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  46352. },
  46353. enumerable: true,
  46354. configurable: true
  46355. });
  46356. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingEnabled", {
  46357. /**
  46358. * Gets wether the color grading effect is enabled.
  46359. */
  46360. get: function () {
  46361. return this.imageProcessingConfiguration.colorGradingEnabled;
  46362. },
  46363. /**
  46364. * Gets wether the color grading effect is enabled.
  46365. */
  46366. set: function (value) {
  46367. this.imageProcessingConfiguration.colorGradingEnabled = value;
  46368. },
  46369. enumerable: true,
  46370. configurable: true
  46371. });
  46372. Object.defineProperty(PBRMaterial.prototype, "cameraToneMappingEnabled", {
  46373. /**
  46374. * Gets wether tonemapping is enabled or not.
  46375. */
  46376. get: function () {
  46377. return this._imageProcessingConfiguration.toneMappingEnabled;
  46378. },
  46379. /**
  46380. * Sets wether tonemapping is enabled or not
  46381. */
  46382. set: function (value) {
  46383. this._imageProcessingConfiguration.toneMappingEnabled = value;
  46384. },
  46385. enumerable: true,
  46386. configurable: true
  46387. });
  46388. ;
  46389. ;
  46390. Object.defineProperty(PBRMaterial.prototype, "cameraExposure", {
  46391. /**
  46392. * The camera exposure used on this material.
  46393. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  46394. * This corresponds to a photographic exposure.
  46395. */
  46396. get: function () {
  46397. return this._imageProcessingConfiguration.exposure;
  46398. },
  46399. /**
  46400. * The camera exposure used on this material.
  46401. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  46402. * This corresponds to a photographic exposure.
  46403. */
  46404. set: function (value) {
  46405. this._imageProcessingConfiguration.exposure = value;
  46406. },
  46407. enumerable: true,
  46408. configurable: true
  46409. });
  46410. ;
  46411. ;
  46412. Object.defineProperty(PBRMaterial.prototype, "cameraContrast", {
  46413. /**
  46414. * Gets The camera contrast used on this material.
  46415. */
  46416. get: function () {
  46417. return this._imageProcessingConfiguration.contrast;
  46418. },
  46419. /**
  46420. * Sets The camera contrast used on this material.
  46421. */
  46422. set: function (value) {
  46423. this._imageProcessingConfiguration.contrast = value;
  46424. },
  46425. enumerable: true,
  46426. configurable: true
  46427. });
  46428. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingTexture", {
  46429. /**
  46430. * Gets the Color Grading 2D Lookup Texture.
  46431. */
  46432. get: function () {
  46433. return this._imageProcessingConfiguration.colorGradingTexture;
  46434. },
  46435. /**
  46436. * Sets the Color Grading 2D Lookup Texture.
  46437. */
  46438. set: function (value) {
  46439. this._imageProcessingConfiguration.colorGradingTexture = value;
  46440. },
  46441. enumerable: true,
  46442. configurable: true
  46443. });
  46444. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurves", {
  46445. /**
  46446. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  46447. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  46448. * 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;
  46449. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  46450. */
  46451. get: function () {
  46452. return this._imageProcessingConfiguration.colorCurves;
  46453. },
  46454. /**
  46455. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  46456. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  46457. * 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;
  46458. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  46459. */
  46460. set: function (value) {
  46461. this._imageProcessingConfiguration.colorCurves = value;
  46462. },
  46463. enumerable: true,
  46464. configurable: true
  46465. });
  46466. /**
  46467. * Returns the name of this material class.
  46468. */
  46469. PBRMaterial.prototype.getClassName = function () {
  46470. return "PBRMaterial";
  46471. };
  46472. /**
  46473. * Returns an array of the actively used textures.
  46474. * @returns - Array of BaseTextures
  46475. */
  46476. PBRMaterial.prototype.getActiveTextures = function () {
  46477. var activeTextures = _super.prototype.getActiveTextures.call(this);
  46478. if (this._albedoTexture) {
  46479. activeTextures.push(this._albedoTexture);
  46480. }
  46481. if (this._ambientTexture) {
  46482. activeTextures.push(this._ambientTexture);
  46483. }
  46484. if (this._opacityTexture) {
  46485. activeTextures.push(this._opacityTexture);
  46486. }
  46487. if (this._reflectionTexture) {
  46488. activeTextures.push(this._reflectionTexture);
  46489. }
  46490. if (this._emissiveTexture) {
  46491. activeTextures.push(this._emissiveTexture);
  46492. }
  46493. if (this._reflectivityTexture) {
  46494. activeTextures.push(this._reflectivityTexture);
  46495. }
  46496. if (this._metallicTexture) {
  46497. activeTextures.push(this._metallicTexture);
  46498. }
  46499. if (this._microSurfaceTexture) {
  46500. activeTextures.push(this._microSurfaceTexture);
  46501. }
  46502. if (this._bumpTexture) {
  46503. activeTextures.push(this._bumpTexture);
  46504. }
  46505. if (this._lightmapTexture) {
  46506. activeTextures.push(this._lightmapTexture);
  46507. }
  46508. if (this._refractionTexture) {
  46509. activeTextures.push(this._refractionTexture);
  46510. }
  46511. return activeTextures;
  46512. };
  46513. /**
  46514. * Checks to see if a texture is used in the material.
  46515. * @param texture - Base texture to use.
  46516. * @returns - Boolean specifying if a texture is used in the material.
  46517. */
  46518. PBRMaterial.prototype.hasTexture = function (texture) {
  46519. if (_super.prototype.hasTexture.call(this, texture)) {
  46520. return true;
  46521. }
  46522. if (this._albedoTexture === texture) {
  46523. return true;
  46524. }
  46525. if (this._ambientTexture === texture) {
  46526. return true;
  46527. }
  46528. if (this._opacityTexture === texture) {
  46529. return true;
  46530. }
  46531. if (this._reflectionTexture === texture) {
  46532. return true;
  46533. }
  46534. if (this._reflectivityTexture === texture) {
  46535. return true;
  46536. }
  46537. if (this._metallicTexture === texture) {
  46538. return true;
  46539. }
  46540. if (this._microSurfaceTexture === texture) {
  46541. return true;
  46542. }
  46543. if (this._bumpTexture === texture) {
  46544. return true;
  46545. }
  46546. if (this._lightmapTexture === texture) {
  46547. return true;
  46548. }
  46549. if (this._refractionTexture === texture) {
  46550. return true;
  46551. }
  46552. return false;
  46553. };
  46554. /**
  46555. * Makes a duplicate of the current material.
  46556. * @param name - name to use for the new material.
  46557. */
  46558. PBRMaterial.prototype.clone = function (name) {
  46559. var _this = this;
  46560. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMaterial(name, _this.getScene()); }, this);
  46561. clone.id = name;
  46562. clone.name = name;
  46563. return clone;
  46564. };
  46565. /**
  46566. * Serializes this PBR Material.
  46567. * @returns - An object with the serialized material.
  46568. */
  46569. PBRMaterial.prototype.serialize = function () {
  46570. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  46571. serializationObject.customType = "BABYLON.PBRMaterial";
  46572. return serializationObject;
  46573. };
  46574. // Statics
  46575. /**
  46576. * Parses a PBR Material from a serialized object.
  46577. * @param source - Serialized object.
  46578. * @param scene - BJS scene instance.
  46579. * @param rootUrl - url for the scene object
  46580. * @returns - PBRMaterial
  46581. */
  46582. PBRMaterial.Parse = function (source, scene, rootUrl) {
  46583. return BABYLON.SerializationHelper.Parse(function () { return new PBRMaterial(source.name, scene); }, source, scene, rootUrl);
  46584. };
  46585. PBRMaterial._PBRMATERIAL_OPAQUE = 0;
  46586. /**
  46587. * Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  46588. */
  46589. PBRMaterial._PBRMATERIAL_ALPHATEST = 1;
  46590. /**
  46591. * Represents the value for Alpha Blend. Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  46592. */
  46593. PBRMaterial._PBRMATERIAL_ALPHABLEND = 2;
  46594. /**
  46595. * Represents the value for Alpha Test and Blend. Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  46596. * They are also discarded below the alpha cutoff threshold to improve performances.
  46597. */
  46598. PBRMaterial._PBRMATERIAL_ALPHATESTANDBLEND = 3;
  46599. __decorate([
  46600. BABYLON.serialize(),
  46601. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46602. ], PBRMaterial.prototype, "directIntensity", void 0);
  46603. __decorate([
  46604. BABYLON.serialize(),
  46605. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46606. ], PBRMaterial.prototype, "emissiveIntensity", void 0);
  46607. __decorate([
  46608. BABYLON.serialize(),
  46609. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46610. ], PBRMaterial.prototype, "environmentIntensity", void 0);
  46611. __decorate([
  46612. BABYLON.serialize(),
  46613. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46614. ], PBRMaterial.prototype, "specularIntensity", void 0);
  46615. __decorate([
  46616. BABYLON.serialize(),
  46617. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46618. ], PBRMaterial.prototype, "disableBumpMap", void 0);
  46619. __decorate([
  46620. BABYLON.serializeAsTexture(),
  46621. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46622. ], PBRMaterial.prototype, "albedoTexture", void 0);
  46623. __decorate([
  46624. BABYLON.serializeAsTexture(),
  46625. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46626. ], PBRMaterial.prototype, "ambientTexture", void 0);
  46627. __decorate([
  46628. BABYLON.serialize(),
  46629. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46630. ], PBRMaterial.prototype, "ambientTextureStrength", void 0);
  46631. __decorate([
  46632. BABYLON.serializeAsTexture(),
  46633. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  46634. ], PBRMaterial.prototype, "opacityTexture", void 0);
  46635. __decorate([
  46636. BABYLON.serializeAsTexture(),
  46637. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46638. ], PBRMaterial.prototype, "reflectionTexture", void 0);
  46639. __decorate([
  46640. BABYLON.serializeAsTexture(),
  46641. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46642. ], PBRMaterial.prototype, "emissiveTexture", void 0);
  46643. __decorate([
  46644. BABYLON.serializeAsTexture(),
  46645. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46646. ], PBRMaterial.prototype, "reflectivityTexture", void 0);
  46647. __decorate([
  46648. BABYLON.serializeAsTexture(),
  46649. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46650. ], PBRMaterial.prototype, "metallicTexture", void 0);
  46651. __decorate([
  46652. BABYLON.serialize(),
  46653. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46654. ], PBRMaterial.prototype, "metallic", void 0);
  46655. __decorate([
  46656. BABYLON.serialize(),
  46657. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46658. ], PBRMaterial.prototype, "roughness", void 0);
  46659. __decorate([
  46660. BABYLON.serializeAsTexture(),
  46661. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46662. ], PBRMaterial.prototype, "microSurfaceTexture", void 0);
  46663. __decorate([
  46664. BABYLON.serializeAsTexture(),
  46665. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46666. ], PBRMaterial.prototype, "bumpTexture", void 0);
  46667. __decorate([
  46668. BABYLON.serializeAsTexture(),
  46669. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  46670. ], PBRMaterial.prototype, "lightmapTexture", void 0);
  46671. __decorate([
  46672. BABYLON.serializeAsTexture(),
  46673. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46674. ], PBRMaterial.prototype, "refractionTexture", void 0);
  46675. __decorate([
  46676. BABYLON.serializeAsColor3("ambient"),
  46677. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46678. ], PBRMaterial.prototype, "ambientColor", void 0);
  46679. __decorate([
  46680. BABYLON.serializeAsColor3("albedo"),
  46681. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46682. ], PBRMaterial.prototype, "albedoColor", void 0);
  46683. __decorate([
  46684. BABYLON.serializeAsColor3("reflectivity"),
  46685. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46686. ], PBRMaterial.prototype, "reflectivityColor", void 0);
  46687. __decorate([
  46688. BABYLON.serializeAsColor3("reflection"),
  46689. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46690. ], PBRMaterial.prototype, "reflectionColor", void 0);
  46691. __decorate([
  46692. BABYLON.serializeAsColor3("emissive"),
  46693. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46694. ], PBRMaterial.prototype, "emissiveColor", void 0);
  46695. __decorate([
  46696. BABYLON.serialize(),
  46697. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46698. ], PBRMaterial.prototype, "microSurface", void 0);
  46699. __decorate([
  46700. BABYLON.serialize(),
  46701. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46702. ], PBRMaterial.prototype, "indexOfRefraction", void 0);
  46703. __decorate([
  46704. BABYLON.serialize(),
  46705. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46706. ], PBRMaterial.prototype, "invertRefractionY", void 0);
  46707. __decorate([
  46708. BABYLON.serialize(),
  46709. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46710. ], PBRMaterial.prototype, "linkRefractionWithTransparency", void 0);
  46711. __decorate([
  46712. BABYLON.serialize(),
  46713. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46714. ], PBRMaterial.prototype, "useLightmapAsShadowmap", void 0);
  46715. __decorate([
  46716. BABYLON.serialize(),
  46717. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  46718. ], PBRMaterial.prototype, "useAlphaFromAlbedoTexture", void 0);
  46719. __decorate([
  46720. BABYLON.serialize(),
  46721. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  46722. ], PBRMaterial.prototype, "forceAlphaTest", void 0);
  46723. __decorate([
  46724. BABYLON.serialize(),
  46725. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  46726. ], PBRMaterial.prototype, "alphaCutOff", void 0);
  46727. __decorate([
  46728. BABYLON.serialize(),
  46729. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46730. ], PBRMaterial.prototype, "useSpecularOverAlpha", void 0);
  46731. __decorate([
  46732. BABYLON.serialize(),
  46733. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46734. ], PBRMaterial.prototype, "useMicroSurfaceFromReflectivityMapAlpha", void 0);
  46735. __decorate([
  46736. BABYLON.serialize(),
  46737. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46738. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureAlpha", void 0);
  46739. __decorate([
  46740. BABYLON.serialize(),
  46741. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46742. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureGreen", void 0);
  46743. __decorate([
  46744. BABYLON.serialize(),
  46745. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46746. ], PBRMaterial.prototype, "useMetallnessFromMetallicTextureBlue", void 0);
  46747. __decorate([
  46748. BABYLON.serialize(),
  46749. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46750. ], PBRMaterial.prototype, "useAmbientOcclusionFromMetallicTextureRed", void 0);
  46751. __decorate([
  46752. BABYLON.serialize(),
  46753. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46754. ], PBRMaterial.prototype, "useAmbientInGrayScale", void 0);
  46755. __decorate([
  46756. BABYLON.serialize(),
  46757. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46758. ], PBRMaterial.prototype, "useAutoMicroSurfaceFromReflectivityMap", void 0);
  46759. __decorate([
  46760. BABYLON.serialize(),
  46761. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46762. ], PBRMaterial.prototype, "usePhysicalLightFalloff", void 0);
  46763. __decorate([
  46764. BABYLON.serialize(),
  46765. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46766. ], PBRMaterial.prototype, "useRadianceOverAlpha", void 0);
  46767. __decorate([
  46768. BABYLON.serialize(),
  46769. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46770. ], PBRMaterial.prototype, "useObjectSpaceNormalMap", void 0);
  46771. __decorate([
  46772. BABYLON.serialize(),
  46773. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46774. ], PBRMaterial.prototype, "useParallax", void 0);
  46775. __decorate([
  46776. BABYLON.serialize(),
  46777. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46778. ], PBRMaterial.prototype, "useParallaxOcclusion", void 0);
  46779. __decorate([
  46780. BABYLON.serialize(),
  46781. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46782. ], PBRMaterial.prototype, "parallaxScaleBias", void 0);
  46783. __decorate([
  46784. BABYLON.serialize(),
  46785. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  46786. ], PBRMaterial.prototype, "disableLighting", void 0);
  46787. __decorate([
  46788. BABYLON.serialize(),
  46789. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46790. ], PBRMaterial.prototype, "forceIrradianceInFragment", void 0);
  46791. __decorate([
  46792. BABYLON.serialize(),
  46793. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  46794. ], PBRMaterial.prototype, "maxSimultaneousLights", void 0);
  46795. __decorate([
  46796. BABYLON.serialize(),
  46797. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46798. ], PBRMaterial.prototype, "invertNormalMapX", void 0);
  46799. __decorate([
  46800. BABYLON.serialize(),
  46801. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46802. ], PBRMaterial.prototype, "invertNormalMapY", void 0);
  46803. __decorate([
  46804. BABYLON.serialize(),
  46805. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46806. ], PBRMaterial.prototype, "twoSidedLighting", void 0);
  46807. __decorate([
  46808. BABYLON.serialize(),
  46809. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46810. ], PBRMaterial.prototype, "useAlphaFresnel", void 0);
  46811. __decorate([
  46812. BABYLON.serialize(),
  46813. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46814. ], PBRMaterial.prototype, "useLinearAlphaFresnel", void 0);
  46815. __decorate([
  46816. BABYLON.serializeAsTexture(),
  46817. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46818. ], PBRMaterial.prototype, "environmentBRDFTexture", void 0);
  46819. __decorate([
  46820. BABYLON.serialize(),
  46821. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46822. ], PBRMaterial.prototype, "forceNormalForward", void 0);
  46823. __decorate([
  46824. BABYLON.serialize(),
  46825. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46826. ], PBRMaterial.prototype, "enableSpecularAntiAliasing", void 0);
  46827. __decorate([
  46828. BABYLON.serialize(),
  46829. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46830. ], PBRMaterial.prototype, "useHorizonOcclusion", void 0);
  46831. __decorate([
  46832. BABYLON.serialize(),
  46833. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46834. ], PBRMaterial.prototype, "useRadianceOcclusion", void 0);
  46835. __decorate([
  46836. BABYLON.serialize(),
  46837. BABYLON.expandToProperty("_markAllSubMeshesAsMiscDirty")
  46838. ], PBRMaterial.prototype, "unlit", void 0);
  46839. return PBRMaterial;
  46840. }(BABYLON.PBRBaseMaterial));
  46841. BABYLON.PBRMaterial = PBRMaterial;
  46842. })(BABYLON || (BABYLON = {}));
  46843. //# sourceMappingURL=babylon.pbrMaterial.js.map
  46844. var BABYLON;
  46845. (function (BABYLON) {
  46846. /**
  46847. * The PBR material of BJS following the metal roughness convention.
  46848. *
  46849. * This fits to the PBR convention in the GLTF definition:
  46850. * https://github.com/KhronosGroup/glTF/tree/2.0/specification/2.0
  46851. */
  46852. var PBRMetallicRoughnessMaterial = /** @class */ (function (_super) {
  46853. __extends(PBRMetallicRoughnessMaterial, _super);
  46854. /**
  46855. * Instantiates a new PBRMetalRoughnessMaterial instance.
  46856. *
  46857. * @param name The material name
  46858. * @param scene The scene the material will be use in.
  46859. */
  46860. function PBRMetallicRoughnessMaterial(name, scene) {
  46861. var _this = _super.call(this, name, scene) || this;
  46862. _this._useRoughnessFromMetallicTextureAlpha = false;
  46863. _this._useRoughnessFromMetallicTextureGreen = true;
  46864. _this._useMetallnessFromMetallicTextureBlue = true;
  46865. _this.metallic = 1.0;
  46866. _this.roughness = 1.0;
  46867. return _this;
  46868. }
  46869. /**
  46870. * Return the currrent class name of the material.
  46871. */
  46872. PBRMetallicRoughnessMaterial.prototype.getClassName = function () {
  46873. return "PBRMetallicRoughnessMaterial";
  46874. };
  46875. /**
  46876. * Return the active textures of the material.
  46877. */
  46878. PBRMetallicRoughnessMaterial.prototype.getActiveTextures = function () {
  46879. var activeTextures = _super.prototype.getActiveTextures.call(this);
  46880. if (this.baseTexture) {
  46881. activeTextures.push(this.baseTexture);
  46882. }
  46883. if (this.metallicRoughnessTexture) {
  46884. activeTextures.push(this.metallicRoughnessTexture);
  46885. }
  46886. return activeTextures;
  46887. };
  46888. /**
  46889. * Checks to see if a texture is used in the material.
  46890. * @param texture - Base texture to use.
  46891. * @returns - Boolean specifying if a texture is used in the material.
  46892. */
  46893. PBRMetallicRoughnessMaterial.prototype.hasTexture = function (texture) {
  46894. if (_super.prototype.hasTexture.call(this, texture)) {
  46895. return true;
  46896. }
  46897. if (this.baseTexture === texture) {
  46898. return true;
  46899. }
  46900. if (this.metallicRoughnessTexture === texture) {
  46901. return true;
  46902. }
  46903. return false;
  46904. };
  46905. /**
  46906. * Makes a duplicate of the current material.
  46907. * @param name - name to use for the new material.
  46908. */
  46909. PBRMetallicRoughnessMaterial.prototype.clone = function (name) {
  46910. var _this = this;
  46911. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMetallicRoughnessMaterial(name, _this.getScene()); }, this);
  46912. clone.id = name;
  46913. clone.name = name;
  46914. return clone;
  46915. };
  46916. /**
  46917. * Serialize the material to a parsable JSON object.
  46918. */
  46919. PBRMetallicRoughnessMaterial.prototype.serialize = function () {
  46920. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  46921. serializationObject.customType = "BABYLON.PBRMetallicRoughnessMaterial";
  46922. return serializationObject;
  46923. };
  46924. /**
  46925. * Parses a JSON object correponding to the serialize function.
  46926. */
  46927. PBRMetallicRoughnessMaterial.Parse = function (source, scene, rootUrl) {
  46928. return BABYLON.SerializationHelper.Parse(function () { return new PBRMetallicRoughnessMaterial(source.name, scene); }, source, scene, rootUrl);
  46929. };
  46930. __decorate([
  46931. BABYLON.serializeAsColor3(),
  46932. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  46933. ], PBRMetallicRoughnessMaterial.prototype, "baseColor", void 0);
  46934. __decorate([
  46935. BABYLON.serializeAsTexture(),
  46936. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  46937. ], PBRMetallicRoughnessMaterial.prototype, "baseTexture", void 0);
  46938. __decorate([
  46939. BABYLON.serialize(),
  46940. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46941. ], PBRMetallicRoughnessMaterial.prototype, "metallic", void 0);
  46942. __decorate([
  46943. BABYLON.serialize(),
  46944. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46945. ], PBRMetallicRoughnessMaterial.prototype, "roughness", void 0);
  46946. __decorate([
  46947. BABYLON.serializeAsTexture(),
  46948. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_metallicTexture")
  46949. ], PBRMetallicRoughnessMaterial.prototype, "metallicRoughnessTexture", void 0);
  46950. return PBRMetallicRoughnessMaterial;
  46951. }(BABYLON.PBRBaseSimpleMaterial));
  46952. BABYLON.PBRMetallicRoughnessMaterial = PBRMetallicRoughnessMaterial;
  46953. })(BABYLON || (BABYLON = {}));
  46954. //# sourceMappingURL=babylon.pbrMetallicRoughnessMaterial.js.map
  46955. var BABYLON;
  46956. (function (BABYLON) {
  46957. /**
  46958. * The PBR material of BJS following the specular glossiness convention.
  46959. *
  46960. * This fits to the PBR convention in the GLTF definition:
  46961. * https://github.com/KhronosGroup/glTF/tree/2.0/extensions/Khronos/KHR_materials_pbrSpecularGlossiness
  46962. */
  46963. var PBRSpecularGlossinessMaterial = /** @class */ (function (_super) {
  46964. __extends(PBRSpecularGlossinessMaterial, _super);
  46965. /**
  46966. * Instantiates a new PBRSpecularGlossinessMaterial instance.
  46967. *
  46968. * @param name The material name
  46969. * @param scene The scene the material will be use in.
  46970. */
  46971. function PBRSpecularGlossinessMaterial(name, scene) {
  46972. var _this = _super.call(this, name, scene) || this;
  46973. _this._useMicroSurfaceFromReflectivityMapAlpha = true;
  46974. return _this;
  46975. }
  46976. /**
  46977. * Return the currrent class name of the material.
  46978. */
  46979. PBRSpecularGlossinessMaterial.prototype.getClassName = function () {
  46980. return "PBRSpecularGlossinessMaterial";
  46981. };
  46982. /**
  46983. * Return the active textures of the material.
  46984. */
  46985. PBRSpecularGlossinessMaterial.prototype.getActiveTextures = function () {
  46986. var activeTextures = _super.prototype.getActiveTextures.call(this);
  46987. if (this.diffuseTexture) {
  46988. activeTextures.push(this.diffuseTexture);
  46989. }
  46990. if (this.specularGlossinessTexture) {
  46991. activeTextures.push(this.specularGlossinessTexture);
  46992. }
  46993. return activeTextures;
  46994. };
  46995. /**
  46996. * Checks to see if a texture is used in the material.
  46997. * @param texture - Base texture to use.
  46998. * @returns - Boolean specifying if a texture is used in the material.
  46999. */
  47000. PBRSpecularGlossinessMaterial.prototype.hasTexture = function (texture) {
  47001. if (_super.prototype.hasTexture.call(this, texture)) {
  47002. return true;
  47003. }
  47004. if (this.diffuseTexture === texture) {
  47005. return true;
  47006. }
  47007. if (this.specularGlossinessTexture === texture) {
  47008. return true;
  47009. }
  47010. return false;
  47011. };
  47012. /**
  47013. * Makes a duplicate of the current material.
  47014. * @param name - name to use for the new material.
  47015. */
  47016. PBRSpecularGlossinessMaterial.prototype.clone = function (name) {
  47017. var _this = this;
  47018. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRSpecularGlossinessMaterial(name, _this.getScene()); }, this);
  47019. clone.id = name;
  47020. clone.name = name;
  47021. return clone;
  47022. };
  47023. /**
  47024. * Serialize the material to a parsable JSON object.
  47025. */
  47026. PBRSpecularGlossinessMaterial.prototype.serialize = function () {
  47027. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  47028. serializationObject.customType = "BABYLON.PBRSpecularGlossinessMaterial";
  47029. return serializationObject;
  47030. };
  47031. /**
  47032. * Parses a JSON object correponding to the serialize function.
  47033. */
  47034. PBRSpecularGlossinessMaterial.Parse = function (source, scene, rootUrl) {
  47035. return BABYLON.SerializationHelper.Parse(function () { return new PBRSpecularGlossinessMaterial(source.name, scene); }, source, scene, rootUrl);
  47036. };
  47037. __decorate([
  47038. BABYLON.serializeAsColor3("diffuse"),
  47039. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  47040. ], PBRSpecularGlossinessMaterial.prototype, "diffuseColor", void 0);
  47041. __decorate([
  47042. BABYLON.serializeAsTexture(),
  47043. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  47044. ], PBRSpecularGlossinessMaterial.prototype, "diffuseTexture", void 0);
  47045. __decorate([
  47046. BABYLON.serializeAsColor3("specular"),
  47047. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityColor")
  47048. ], PBRSpecularGlossinessMaterial.prototype, "specularColor", void 0);
  47049. __decorate([
  47050. BABYLON.serialize(),
  47051. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_microSurface")
  47052. ], PBRSpecularGlossinessMaterial.prototype, "glossiness", void 0);
  47053. __decorate([
  47054. BABYLON.serializeAsTexture(),
  47055. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityTexture")
  47056. ], PBRSpecularGlossinessMaterial.prototype, "specularGlossinessTexture", void 0);
  47057. return PBRSpecularGlossinessMaterial;
  47058. }(BABYLON.PBRBaseSimpleMaterial));
  47059. BABYLON.PBRSpecularGlossinessMaterial = PBRSpecularGlossinessMaterial;
  47060. })(BABYLON || (BABYLON = {}));
  47061. //# sourceMappingURL=babylon.pbrSpecularGlossinessMaterial.js.map
  47062. var BABYLON;
  47063. (function (BABYLON) {
  47064. BABYLON.CameraInputTypes = {};
  47065. var CameraInputsManager = /** @class */ (function () {
  47066. function CameraInputsManager(camera) {
  47067. this.attached = {};
  47068. this.camera = camera;
  47069. this.checkInputs = function () { };
  47070. }
  47071. /**
  47072. * Add an input method to a camera.
  47073. * builtin inputs example: camera.inputs.addGamepad();
  47074. * custom inputs example: camera.inputs.add(new BABYLON.FreeCameraGamepadInput());
  47075. * @param input camera input method
  47076. */
  47077. CameraInputsManager.prototype.add = function (input) {
  47078. var type = input.getSimpleName();
  47079. if (this.attached[type]) {
  47080. BABYLON.Tools.Warn("camera input of type " + type + " already exists on camera");
  47081. return;
  47082. }
  47083. this.attached[type] = input;
  47084. input.camera = this.camera;
  47085. //for checkInputs, we are dynamically creating a function
  47086. //the goal is to avoid the performance penalty of looping for inputs in the render loop
  47087. if (input.checkInputs) {
  47088. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  47089. }
  47090. if (this.attachedElement) {
  47091. input.attachControl(this.attachedElement);
  47092. }
  47093. };
  47094. /**
  47095. * Remove a specific input method from a camera
  47096. * example: camera.inputs.remove(camera.inputs.attached.mouse);
  47097. * @param inputToRemove camera input method
  47098. */
  47099. CameraInputsManager.prototype.remove = function (inputToRemove) {
  47100. for (var cam in this.attached) {
  47101. var input = this.attached[cam];
  47102. if (input === inputToRemove) {
  47103. input.detachControl(this.attachedElement);
  47104. input.camera = null;
  47105. delete this.attached[cam];
  47106. this.rebuildInputCheck();
  47107. }
  47108. }
  47109. };
  47110. CameraInputsManager.prototype.removeByType = function (inputType) {
  47111. for (var cam in this.attached) {
  47112. var input = this.attached[cam];
  47113. if (input.getClassName() === inputType) {
  47114. input.detachControl(this.attachedElement);
  47115. input.camera = null;
  47116. delete this.attached[cam];
  47117. this.rebuildInputCheck();
  47118. }
  47119. }
  47120. };
  47121. CameraInputsManager.prototype._addCheckInputs = function (fn) {
  47122. var current = this.checkInputs;
  47123. return function () {
  47124. current();
  47125. fn();
  47126. };
  47127. };
  47128. CameraInputsManager.prototype.attachInput = function (input) {
  47129. if (this.attachedElement) {
  47130. input.attachControl(this.attachedElement, this.noPreventDefault);
  47131. }
  47132. };
  47133. CameraInputsManager.prototype.attachElement = function (element, noPreventDefault) {
  47134. if (noPreventDefault === void 0) { noPreventDefault = false; }
  47135. if (this.attachedElement) {
  47136. return;
  47137. }
  47138. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  47139. this.attachedElement = element;
  47140. this.noPreventDefault = noPreventDefault;
  47141. for (var cam in this.attached) {
  47142. this.attached[cam].attachControl(element, noPreventDefault);
  47143. }
  47144. };
  47145. CameraInputsManager.prototype.detachElement = function (element, disconnect) {
  47146. if (disconnect === void 0) { disconnect = false; }
  47147. if (this.attachedElement !== element) {
  47148. return;
  47149. }
  47150. for (var cam in this.attached) {
  47151. this.attached[cam].detachControl(element);
  47152. if (disconnect) {
  47153. this.attached[cam].camera = null;
  47154. }
  47155. }
  47156. this.attachedElement = null;
  47157. };
  47158. CameraInputsManager.prototype.rebuildInputCheck = function () {
  47159. this.checkInputs = function () { };
  47160. for (var cam in this.attached) {
  47161. var input = this.attached[cam];
  47162. if (input.checkInputs) {
  47163. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  47164. }
  47165. }
  47166. };
  47167. /**
  47168. * Remove all attached input methods from a camera
  47169. */
  47170. CameraInputsManager.prototype.clear = function () {
  47171. if (this.attachedElement) {
  47172. this.detachElement(this.attachedElement, true);
  47173. }
  47174. this.attached = {};
  47175. this.attachedElement = null;
  47176. this.checkInputs = function () { };
  47177. };
  47178. CameraInputsManager.prototype.serialize = function (serializedCamera) {
  47179. var inputs = {};
  47180. for (var cam in this.attached) {
  47181. var input = this.attached[cam];
  47182. var res = BABYLON.SerializationHelper.Serialize(input);
  47183. inputs[input.getClassName()] = res;
  47184. }
  47185. serializedCamera.inputsmgr = inputs;
  47186. };
  47187. CameraInputsManager.prototype.parse = function (parsedCamera) {
  47188. var parsedInputs = parsedCamera.inputsmgr;
  47189. if (parsedInputs) {
  47190. this.clear();
  47191. for (var n in parsedInputs) {
  47192. var construct = BABYLON.CameraInputTypes[n];
  47193. if (construct) {
  47194. var parsedinput = parsedInputs[n];
  47195. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedinput, null);
  47196. this.add(input);
  47197. }
  47198. }
  47199. }
  47200. else {
  47201. //2016-03-08 this part is for managing backward compatibility
  47202. for (var n in this.attached) {
  47203. var construct = BABYLON.CameraInputTypes[this.attached[n].getClassName()];
  47204. if (construct) {
  47205. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedCamera, null);
  47206. this.remove(this.attached[n]);
  47207. this.add(input);
  47208. }
  47209. }
  47210. }
  47211. };
  47212. return CameraInputsManager;
  47213. }());
  47214. BABYLON.CameraInputsManager = CameraInputsManager;
  47215. })(BABYLON || (BABYLON = {}));
  47216. //# sourceMappingURL=babylon.cameraInputsManager.js.map
  47217. var BABYLON;
  47218. (function (BABYLON) {
  47219. var TargetCamera = /** @class */ (function (_super) {
  47220. __extends(TargetCamera, _super);
  47221. function TargetCamera(name, position, scene, setActiveOnSceneIfNoneActive) {
  47222. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  47223. var _this = _super.call(this, name, position, scene, setActiveOnSceneIfNoneActive) || this;
  47224. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  47225. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  47226. _this.rotation = new BABYLON.Vector3(0, 0, 0);
  47227. _this.speed = 2.0;
  47228. _this.noRotationConstraint = false;
  47229. _this.lockedTarget = null;
  47230. _this._currentTarget = BABYLON.Vector3.Zero();
  47231. _this._viewMatrix = BABYLON.Matrix.Zero();
  47232. _this._camMatrix = BABYLON.Matrix.Zero();
  47233. _this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  47234. _this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  47235. _this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  47236. _this._currentUpVector = new BABYLON.Vector3(0, 1, 0);
  47237. _this._transformedReferencePoint = BABYLON.Vector3.Zero();
  47238. _this._globalCurrentTarget = BABYLON.Vector3.Zero();
  47239. _this._globalCurrentUpVector = BABYLON.Vector3.Zero();
  47240. return _this;
  47241. }
  47242. TargetCamera.prototype.getFrontPosition = function (distance) {
  47243. this.getWorldMatrix();
  47244. var direction = this.getTarget().subtract(this.position);
  47245. direction.normalize();
  47246. direction.scaleInPlace(distance);
  47247. return this.globalPosition.add(direction);
  47248. };
  47249. TargetCamera.prototype._getLockedTargetPosition = function () {
  47250. if (!this.lockedTarget) {
  47251. return null;
  47252. }
  47253. if (this.lockedTarget.absolutePosition) {
  47254. this.lockedTarget.computeWorldMatrix();
  47255. }
  47256. return this.lockedTarget.absolutePosition || this.lockedTarget;
  47257. };
  47258. TargetCamera.prototype.storeState = function () {
  47259. this._storedPosition = this.position.clone();
  47260. this._storedRotation = this.rotation.clone();
  47261. if (this.rotationQuaternion) {
  47262. this._storedRotationQuaternion = this.rotationQuaternion.clone();
  47263. }
  47264. return _super.prototype.storeState.call(this);
  47265. };
  47266. /**
  47267. * Restored camera state. You must call storeState() first
  47268. */
  47269. TargetCamera.prototype._restoreStateValues = function () {
  47270. if (!_super.prototype._restoreStateValues.call(this)) {
  47271. return false;
  47272. }
  47273. this.position = this._storedPosition.clone();
  47274. this.rotation = this._storedRotation.clone();
  47275. if (this.rotationQuaternion) {
  47276. this.rotationQuaternion = this._storedRotationQuaternion.clone();
  47277. }
  47278. this.cameraDirection.copyFromFloats(0, 0, 0);
  47279. this.cameraRotation.copyFromFloats(0, 0);
  47280. return true;
  47281. };
  47282. // Cache
  47283. TargetCamera.prototype._initCache = function () {
  47284. _super.prototype._initCache.call(this);
  47285. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  47286. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  47287. this._cache.rotationQuaternion = new BABYLON.Quaternion(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  47288. };
  47289. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  47290. if (!ignoreParentClass) {
  47291. _super.prototype._updateCache.call(this);
  47292. }
  47293. var lockedTargetPosition = this._getLockedTargetPosition();
  47294. if (!lockedTargetPosition) {
  47295. this._cache.lockedTarget = null;
  47296. }
  47297. else {
  47298. if (!this._cache.lockedTarget) {
  47299. this._cache.lockedTarget = lockedTargetPosition.clone();
  47300. }
  47301. else {
  47302. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  47303. }
  47304. }
  47305. this._cache.rotation.copyFrom(this.rotation);
  47306. if (this.rotationQuaternion)
  47307. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  47308. };
  47309. // Synchronized
  47310. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  47311. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  47312. return false;
  47313. }
  47314. var lockedTargetPosition = this._getLockedTargetPosition();
  47315. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  47316. && (this.rotationQuaternion ? this.rotationQuaternion.equals(this._cache.rotationQuaternion) : this._cache.rotation.equals(this.rotation));
  47317. };
  47318. // Methods
  47319. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  47320. var engine = this.getEngine();
  47321. return this.speed * Math.sqrt((engine.getDeltaTime() / (engine.getFps() * 100.0)));
  47322. };
  47323. // Target
  47324. TargetCamera.prototype.setTarget = function (target) {
  47325. this.upVector.normalize();
  47326. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._camMatrix);
  47327. this._camMatrix.invert();
  47328. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  47329. var vDir = target.subtract(this.position);
  47330. if (vDir.x >= 0.0) {
  47331. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  47332. }
  47333. else {
  47334. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  47335. }
  47336. this.rotation.z = 0;
  47337. if (isNaN(this.rotation.x)) {
  47338. this.rotation.x = 0;
  47339. }
  47340. if (isNaN(this.rotation.y)) {
  47341. this.rotation.y = 0;
  47342. }
  47343. if (isNaN(this.rotation.z)) {
  47344. this.rotation.z = 0;
  47345. }
  47346. if (this.rotationQuaternion) {
  47347. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  47348. }
  47349. };
  47350. /**
  47351. * Return the current target position of the camera. This value is expressed in local space.
  47352. */
  47353. TargetCamera.prototype.getTarget = function () {
  47354. return this._currentTarget;
  47355. };
  47356. TargetCamera.prototype._decideIfNeedsToMove = function () {
  47357. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  47358. };
  47359. TargetCamera.prototype._updatePosition = function () {
  47360. if (this.parent) {
  47361. this.parent.getWorldMatrix().invertToRef(BABYLON.Tmp.Matrix[0]);
  47362. BABYLON.Vector3.TransformNormalToRef(this.cameraDirection, BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Vector3[0]);
  47363. this.position.addInPlace(BABYLON.Tmp.Vector3[0]);
  47364. return;
  47365. }
  47366. this.position.addInPlace(this.cameraDirection);
  47367. };
  47368. TargetCamera.prototype._checkInputs = function () {
  47369. var needToMove = this._decideIfNeedsToMove();
  47370. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  47371. // Move
  47372. if (needToMove) {
  47373. this._updatePosition();
  47374. }
  47375. // Rotate
  47376. if (needToRotate) {
  47377. this.rotation.x += this.cameraRotation.x;
  47378. this.rotation.y += this.cameraRotation.y;
  47379. //rotate, if quaternion is set and rotation was used
  47380. if (this.rotationQuaternion) {
  47381. var len = this.rotation.lengthSquared();
  47382. if (len) {
  47383. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  47384. }
  47385. }
  47386. if (!this.noRotationConstraint) {
  47387. var limit = (Math.PI / 2) * 0.95;
  47388. if (this.rotation.x > limit)
  47389. this.rotation.x = limit;
  47390. if (this.rotation.x < -limit)
  47391. this.rotation.x = -limit;
  47392. }
  47393. }
  47394. // Inertia
  47395. if (needToMove) {
  47396. if (Math.abs(this.cameraDirection.x) < this.speed * BABYLON.Epsilon) {
  47397. this.cameraDirection.x = 0;
  47398. }
  47399. if (Math.abs(this.cameraDirection.y) < this.speed * BABYLON.Epsilon) {
  47400. this.cameraDirection.y = 0;
  47401. }
  47402. if (Math.abs(this.cameraDirection.z) < this.speed * BABYLON.Epsilon) {
  47403. this.cameraDirection.z = 0;
  47404. }
  47405. this.cameraDirection.scaleInPlace(this.inertia);
  47406. }
  47407. if (needToRotate) {
  47408. if (Math.abs(this.cameraRotation.x) < this.speed * BABYLON.Epsilon) {
  47409. this.cameraRotation.x = 0;
  47410. }
  47411. if (Math.abs(this.cameraRotation.y) < this.speed * BABYLON.Epsilon) {
  47412. this.cameraRotation.y = 0;
  47413. }
  47414. this.cameraRotation.scaleInPlace(this.inertia);
  47415. }
  47416. _super.prototype._checkInputs.call(this);
  47417. };
  47418. TargetCamera.prototype._updateCameraRotationMatrix = function () {
  47419. if (this.rotationQuaternion) {
  47420. this.rotationQuaternion.toRotationMatrix(this._cameraRotationMatrix);
  47421. }
  47422. else {
  47423. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  47424. }
  47425. //update the up vector!
  47426. BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._currentUpVector);
  47427. };
  47428. TargetCamera.prototype._getViewMatrix = function () {
  47429. if (this.lockedTarget) {
  47430. this.setTarget(this._getLockedTargetPosition());
  47431. }
  47432. // Compute
  47433. this._updateCameraRotationMatrix();
  47434. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  47435. // Computing target and final matrix
  47436. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  47437. this._computeViewMatrix(this.position, this._currentTarget, this._currentUpVector);
  47438. return this._viewMatrix;
  47439. };
  47440. TargetCamera.prototype._computeViewMatrix = function (position, target, up) {
  47441. if (this.parent) {
  47442. var parentWorldMatrix = this.parent.getWorldMatrix();
  47443. BABYLON.Vector3.TransformCoordinatesToRef(this.position, parentWorldMatrix, this._globalPosition);
  47444. BABYLON.Vector3.TransformCoordinatesToRef(target, parentWorldMatrix, this._globalCurrentTarget);
  47445. BABYLON.Vector3.TransformNormalToRef(up, parentWorldMatrix, this._globalCurrentUpVector);
  47446. this._markSyncedWithParent();
  47447. }
  47448. else {
  47449. this._globalPosition.copyFrom(this.position);
  47450. this._globalCurrentTarget.copyFrom(target);
  47451. this._globalCurrentUpVector.copyFrom(up);
  47452. }
  47453. if (this.getScene().useRightHandedSystem) {
  47454. BABYLON.Matrix.LookAtRHToRef(this._globalPosition, this._globalCurrentTarget, this._globalCurrentUpVector, this._viewMatrix);
  47455. }
  47456. else {
  47457. BABYLON.Matrix.LookAtLHToRef(this._globalPosition, this._globalCurrentTarget, this._globalCurrentUpVector, this._viewMatrix);
  47458. }
  47459. };
  47460. /**
  47461. * @override
  47462. * Override Camera.createRigCamera
  47463. */
  47464. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  47465. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  47466. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  47467. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR || this.cameraRigMode === BABYLON.Camera.RIG_MODE_WEBVR) {
  47468. if (!this.rotationQuaternion) {
  47469. this.rotationQuaternion = new BABYLON.Quaternion();
  47470. }
  47471. rigCamera._cameraRigParams = {};
  47472. rigCamera.rotationQuaternion = new BABYLON.Quaternion();
  47473. }
  47474. return rigCamera;
  47475. }
  47476. return null;
  47477. };
  47478. /**
  47479. * @override
  47480. * Override Camera._updateRigCameras
  47481. */
  47482. TargetCamera.prototype._updateRigCameras = function () {
  47483. var camLeft = this._rigCameras[0];
  47484. var camRight = this._rigCameras[1];
  47485. switch (this.cameraRigMode) {
  47486. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  47487. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  47488. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  47489. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  47490. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  47491. var leftSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : -1;
  47492. var rightSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? -1 : 1;
  47493. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * leftSign, camLeft.position);
  47494. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * rightSign, camRight.position);
  47495. camLeft.setTarget(this.getTarget());
  47496. camRight.setTarget(this.getTarget());
  47497. break;
  47498. case BABYLON.Camera.RIG_MODE_VR:
  47499. if (camLeft.rotationQuaternion) {
  47500. camLeft.rotationQuaternion.copyFrom(this.rotationQuaternion);
  47501. camRight.rotationQuaternion.copyFrom(this.rotationQuaternion);
  47502. }
  47503. else {
  47504. camLeft.rotation.copyFrom(this.rotation);
  47505. camRight.rotation.copyFrom(this.rotation);
  47506. }
  47507. camLeft.position.copyFrom(this.position);
  47508. camRight.position.copyFrom(this.position);
  47509. break;
  47510. }
  47511. _super.prototype._updateRigCameras.call(this);
  47512. };
  47513. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  47514. if (!this._rigCamTransformMatrix) {
  47515. this._rigCamTransformMatrix = new BABYLON.Matrix();
  47516. }
  47517. var target = this.getTarget();
  47518. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  47519. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  47520. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  47521. };
  47522. TargetCamera.prototype.getClassName = function () {
  47523. return "TargetCamera";
  47524. };
  47525. __decorate([
  47526. BABYLON.serializeAsVector3()
  47527. ], TargetCamera.prototype, "rotation", void 0);
  47528. __decorate([
  47529. BABYLON.serialize()
  47530. ], TargetCamera.prototype, "speed", void 0);
  47531. __decorate([
  47532. BABYLON.serializeAsMeshReference("lockedTargetId")
  47533. ], TargetCamera.prototype, "lockedTarget", void 0);
  47534. return TargetCamera;
  47535. }(BABYLON.Camera));
  47536. BABYLON.TargetCamera = TargetCamera;
  47537. })(BABYLON || (BABYLON = {}));
  47538. //# sourceMappingURL=babylon.targetCamera.js.map
  47539. var BABYLON;
  47540. (function (BABYLON) {
  47541. var FreeCameraMouseInput = /** @class */ (function () {
  47542. function FreeCameraMouseInput(touchEnabled) {
  47543. if (touchEnabled === void 0) { touchEnabled = true; }
  47544. this.touchEnabled = touchEnabled;
  47545. this.buttons = [0, 1, 2];
  47546. this.angularSensibility = 2000.0;
  47547. this.previousPosition = null;
  47548. }
  47549. FreeCameraMouseInput.prototype.attachControl = function (element, noPreventDefault) {
  47550. var _this = this;
  47551. var engine = this.camera.getEngine();
  47552. if (!this._pointerInput) {
  47553. this._pointerInput = function (p, s) {
  47554. var evt = p.event;
  47555. if (engine.isInVRExclusivePointerMode) {
  47556. return;
  47557. }
  47558. if (!_this.touchEnabled && evt.pointerType === "touch") {
  47559. return;
  47560. }
  47561. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  47562. return;
  47563. }
  47564. var srcElement = (evt.srcElement || evt.target);
  47565. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  47566. try {
  47567. srcElement.setPointerCapture(evt.pointerId);
  47568. }
  47569. catch (e) {
  47570. //Nothing to do with the error. Execution will continue.
  47571. }
  47572. _this.previousPosition = {
  47573. x: evt.clientX,
  47574. y: evt.clientY
  47575. };
  47576. if (!noPreventDefault) {
  47577. evt.preventDefault();
  47578. element.focus();
  47579. }
  47580. }
  47581. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  47582. try {
  47583. srcElement.releasePointerCapture(evt.pointerId);
  47584. }
  47585. catch (e) {
  47586. //Nothing to do with the error.
  47587. }
  47588. _this.previousPosition = null;
  47589. if (!noPreventDefault) {
  47590. evt.preventDefault();
  47591. }
  47592. }
  47593. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  47594. if (!_this.previousPosition || engine.isPointerLock) {
  47595. return;
  47596. }
  47597. var offsetX = evt.clientX - _this.previousPosition.x;
  47598. if (_this.camera.getScene().useRightHandedSystem)
  47599. offsetX *= -1;
  47600. if (_this.camera.parent && _this.camera.parent._getWorldMatrixDeterminant() < 0)
  47601. offsetX *= -1;
  47602. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  47603. var offsetY = evt.clientY - _this.previousPosition.y;
  47604. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  47605. _this.previousPosition = {
  47606. x: evt.clientX,
  47607. y: evt.clientY
  47608. };
  47609. if (!noPreventDefault) {
  47610. evt.preventDefault();
  47611. }
  47612. }
  47613. };
  47614. }
  47615. this._onMouseMove = function (evt) {
  47616. if (!engine.isPointerLock) {
  47617. return;
  47618. }
  47619. if (engine.isInVRExclusivePointerMode) {
  47620. return;
  47621. }
  47622. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  47623. if (_this.camera.getScene().useRightHandedSystem)
  47624. offsetX *= -1;
  47625. if (_this.camera.parent && _this.camera.parent._getWorldMatrixDeterminant() < 0)
  47626. offsetX *= -1;
  47627. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  47628. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  47629. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  47630. _this.previousPosition = null;
  47631. if (!noPreventDefault) {
  47632. evt.preventDefault();
  47633. }
  47634. };
  47635. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  47636. element.addEventListener("mousemove", this._onMouseMove, false);
  47637. };
  47638. FreeCameraMouseInput.prototype.detachControl = function (element) {
  47639. if (this._observer && element) {
  47640. this.camera.getScene().onPointerObservable.remove(this._observer);
  47641. if (this._onMouseMove) {
  47642. element.removeEventListener("mousemove", this._onMouseMove);
  47643. }
  47644. this._observer = null;
  47645. this._onMouseMove = null;
  47646. this.previousPosition = null;
  47647. }
  47648. };
  47649. FreeCameraMouseInput.prototype.getClassName = function () {
  47650. return "FreeCameraMouseInput";
  47651. };
  47652. FreeCameraMouseInput.prototype.getSimpleName = function () {
  47653. return "mouse";
  47654. };
  47655. __decorate([
  47656. BABYLON.serialize()
  47657. ], FreeCameraMouseInput.prototype, "buttons", void 0);
  47658. __decorate([
  47659. BABYLON.serialize()
  47660. ], FreeCameraMouseInput.prototype, "angularSensibility", void 0);
  47661. return FreeCameraMouseInput;
  47662. }());
  47663. BABYLON.FreeCameraMouseInput = FreeCameraMouseInput;
  47664. BABYLON.CameraInputTypes["FreeCameraMouseInput"] = FreeCameraMouseInput;
  47665. })(BABYLON || (BABYLON = {}));
  47666. //# sourceMappingURL=babylon.freeCameraMouseInput.js.map
  47667. var BABYLON;
  47668. (function (BABYLON) {
  47669. var FreeCameraKeyboardMoveInput = /** @class */ (function () {
  47670. function FreeCameraKeyboardMoveInput() {
  47671. this._keys = new Array();
  47672. this.keysUp = [38];
  47673. this.keysDown = [40];
  47674. this.keysLeft = [37];
  47675. this.keysRight = [39];
  47676. }
  47677. FreeCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  47678. var _this = this;
  47679. if (this._onCanvasBlurObserver) {
  47680. return;
  47681. }
  47682. this._scene = this.camera.getScene();
  47683. this._engine = this._scene.getEngine();
  47684. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  47685. _this._keys = [];
  47686. });
  47687. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  47688. var evt = info.event;
  47689. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  47690. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  47691. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  47692. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  47693. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  47694. var index = _this._keys.indexOf(evt.keyCode);
  47695. if (index === -1) {
  47696. _this._keys.push(evt.keyCode);
  47697. }
  47698. if (!noPreventDefault) {
  47699. evt.preventDefault();
  47700. }
  47701. }
  47702. }
  47703. else {
  47704. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  47705. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  47706. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  47707. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  47708. var index = _this._keys.indexOf(evt.keyCode);
  47709. if (index >= 0) {
  47710. _this._keys.splice(index, 1);
  47711. }
  47712. if (!noPreventDefault) {
  47713. evt.preventDefault();
  47714. }
  47715. }
  47716. }
  47717. });
  47718. };
  47719. FreeCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  47720. if (this._scene) {
  47721. if (this._onKeyboardObserver) {
  47722. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  47723. }
  47724. if (this._onCanvasBlurObserver) {
  47725. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  47726. }
  47727. this._onKeyboardObserver = null;
  47728. this._onCanvasBlurObserver = null;
  47729. }
  47730. this._keys = [];
  47731. };
  47732. FreeCameraKeyboardMoveInput.prototype.checkInputs = function () {
  47733. if (this._onKeyboardObserver) {
  47734. var camera = this.camera;
  47735. // Keyboard
  47736. for (var index = 0; index < this._keys.length; index++) {
  47737. var keyCode = this._keys[index];
  47738. var speed = camera._computeLocalCameraSpeed();
  47739. if (this.keysLeft.indexOf(keyCode) !== -1) {
  47740. camera._localDirection.copyFromFloats(-speed, 0, 0);
  47741. }
  47742. else if (this.keysUp.indexOf(keyCode) !== -1) {
  47743. camera._localDirection.copyFromFloats(0, 0, speed);
  47744. }
  47745. else if (this.keysRight.indexOf(keyCode) !== -1) {
  47746. camera._localDirection.copyFromFloats(speed, 0, 0);
  47747. }
  47748. else if (this.keysDown.indexOf(keyCode) !== -1) {
  47749. camera._localDirection.copyFromFloats(0, 0, -speed);
  47750. }
  47751. if (camera.getScene().useRightHandedSystem) {
  47752. camera._localDirection.z *= -1;
  47753. }
  47754. camera.getViewMatrix().invertToRef(camera._cameraTransformMatrix);
  47755. BABYLON.Vector3.TransformNormalToRef(camera._localDirection, camera._cameraTransformMatrix, camera._transformedDirection);
  47756. camera.cameraDirection.addInPlace(camera._transformedDirection);
  47757. }
  47758. }
  47759. };
  47760. FreeCameraKeyboardMoveInput.prototype.getClassName = function () {
  47761. return "FreeCameraKeyboardMoveInput";
  47762. };
  47763. FreeCameraKeyboardMoveInput.prototype._onLostFocus = function (e) {
  47764. this._keys = [];
  47765. };
  47766. FreeCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  47767. return "keyboard";
  47768. };
  47769. __decorate([
  47770. BABYLON.serialize()
  47771. ], FreeCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  47772. __decorate([
  47773. BABYLON.serialize()
  47774. ], FreeCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  47775. __decorate([
  47776. BABYLON.serialize()
  47777. ], FreeCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  47778. __decorate([
  47779. BABYLON.serialize()
  47780. ], FreeCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  47781. return FreeCameraKeyboardMoveInput;
  47782. }());
  47783. BABYLON.FreeCameraKeyboardMoveInput = FreeCameraKeyboardMoveInput;
  47784. BABYLON.CameraInputTypes["FreeCameraKeyboardMoveInput"] = FreeCameraKeyboardMoveInput;
  47785. })(BABYLON || (BABYLON = {}));
  47786. //# sourceMappingURL=babylon.freeCameraKeyboardMoveInput.js.map
  47787. var BABYLON;
  47788. (function (BABYLON) {
  47789. var FreeCameraInputsManager = /** @class */ (function (_super) {
  47790. __extends(FreeCameraInputsManager, _super);
  47791. function FreeCameraInputsManager(camera) {
  47792. return _super.call(this, camera) || this;
  47793. }
  47794. FreeCameraInputsManager.prototype.addKeyboard = function () {
  47795. this.add(new BABYLON.FreeCameraKeyboardMoveInput());
  47796. return this;
  47797. };
  47798. FreeCameraInputsManager.prototype.addMouse = function (touchEnabled) {
  47799. if (touchEnabled === void 0) { touchEnabled = true; }
  47800. this.add(new BABYLON.FreeCameraMouseInput(touchEnabled));
  47801. return this;
  47802. };
  47803. FreeCameraInputsManager.prototype.addGamepad = function () {
  47804. this.add(new BABYLON.FreeCameraGamepadInput());
  47805. return this;
  47806. };
  47807. FreeCameraInputsManager.prototype.addDeviceOrientation = function () {
  47808. this.add(new BABYLON.FreeCameraDeviceOrientationInput());
  47809. return this;
  47810. };
  47811. FreeCameraInputsManager.prototype.addTouch = function () {
  47812. this.add(new BABYLON.FreeCameraTouchInput());
  47813. return this;
  47814. };
  47815. FreeCameraInputsManager.prototype.addVirtualJoystick = function () {
  47816. this.add(new BABYLON.FreeCameraVirtualJoystickInput());
  47817. return this;
  47818. };
  47819. return FreeCameraInputsManager;
  47820. }(BABYLON.CameraInputsManager));
  47821. BABYLON.FreeCameraInputsManager = FreeCameraInputsManager;
  47822. })(BABYLON || (BABYLON = {}));
  47823. //# sourceMappingURL=babylon.freeCameraInputsManager.js.map
  47824. var BABYLON;
  47825. (function (BABYLON) {
  47826. var FreeCamera = /** @class */ (function (_super) {
  47827. __extends(FreeCamera, _super);
  47828. function FreeCamera(name, position, scene, setActiveOnSceneIfNoneActive) {
  47829. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  47830. var _this = _super.call(this, name, position, scene, setActiveOnSceneIfNoneActive) || this;
  47831. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  47832. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  47833. _this.checkCollisions = false;
  47834. _this.applyGravity = false;
  47835. _this._needMoveForGravity = false;
  47836. _this._oldPosition = BABYLON.Vector3.Zero();
  47837. _this._diffPosition = BABYLON.Vector3.Zero();
  47838. _this._newPosition = BABYLON.Vector3.Zero();
  47839. // Collisions
  47840. _this._collisionMask = -1;
  47841. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  47842. if (collidedMesh === void 0) { collidedMesh = null; }
  47843. //TODO move this to the collision coordinator!
  47844. if (_this.getScene().workerCollisions)
  47845. newPosition.multiplyInPlace(_this._collider._radius);
  47846. var updatePosition = function (newPos) {
  47847. _this._newPosition.copyFrom(newPos);
  47848. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  47849. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  47850. _this.position.addInPlace(_this._diffPosition);
  47851. if (_this.onCollide && collidedMesh) {
  47852. _this.onCollide(collidedMesh);
  47853. }
  47854. }
  47855. };
  47856. updatePosition(newPosition);
  47857. };
  47858. _this.inputs = new BABYLON.FreeCameraInputsManager(_this);
  47859. _this.inputs.addKeyboard().addMouse();
  47860. return _this;
  47861. }
  47862. Object.defineProperty(FreeCamera.prototype, "angularSensibility", {
  47863. //-- begin properties for backward compatibility for inputs
  47864. /**
  47865. * Gets the input sensibility for a mouse input. (default is 2000.0)
  47866. * Higher values reduce sensitivity.
  47867. */
  47868. get: function () {
  47869. var mouse = this.inputs.attached["mouse"];
  47870. if (mouse)
  47871. return mouse.angularSensibility;
  47872. return 0;
  47873. },
  47874. /**
  47875. * Sets the input sensibility for a mouse input. (default is 2000.0)
  47876. * Higher values reduce sensitivity.
  47877. */
  47878. set: function (value) {
  47879. var mouse = this.inputs.attached["mouse"];
  47880. if (mouse)
  47881. mouse.angularSensibility = value;
  47882. },
  47883. enumerable: true,
  47884. configurable: true
  47885. });
  47886. Object.defineProperty(FreeCamera.prototype, "keysUp", {
  47887. get: function () {
  47888. var keyboard = this.inputs.attached["keyboard"];
  47889. if (keyboard)
  47890. return keyboard.keysUp;
  47891. return [];
  47892. },
  47893. set: function (value) {
  47894. var keyboard = this.inputs.attached["keyboard"];
  47895. if (keyboard)
  47896. keyboard.keysUp = value;
  47897. },
  47898. enumerable: true,
  47899. configurable: true
  47900. });
  47901. Object.defineProperty(FreeCamera.prototype, "keysDown", {
  47902. get: function () {
  47903. var keyboard = this.inputs.attached["keyboard"];
  47904. if (keyboard)
  47905. return keyboard.keysDown;
  47906. return [];
  47907. },
  47908. set: function (value) {
  47909. var keyboard = this.inputs.attached["keyboard"];
  47910. if (keyboard)
  47911. keyboard.keysDown = value;
  47912. },
  47913. enumerable: true,
  47914. configurable: true
  47915. });
  47916. Object.defineProperty(FreeCamera.prototype, "keysLeft", {
  47917. get: function () {
  47918. var keyboard = this.inputs.attached["keyboard"];
  47919. if (keyboard)
  47920. return keyboard.keysLeft;
  47921. return [];
  47922. },
  47923. set: function (value) {
  47924. var keyboard = this.inputs.attached["keyboard"];
  47925. if (keyboard)
  47926. keyboard.keysLeft = value;
  47927. },
  47928. enumerable: true,
  47929. configurable: true
  47930. });
  47931. Object.defineProperty(FreeCamera.prototype, "keysRight", {
  47932. get: function () {
  47933. var keyboard = this.inputs.attached["keyboard"];
  47934. if (keyboard)
  47935. return keyboard.keysRight;
  47936. return [];
  47937. },
  47938. set: function (value) {
  47939. var keyboard = this.inputs.attached["keyboard"];
  47940. if (keyboard)
  47941. keyboard.keysRight = value;
  47942. },
  47943. enumerable: true,
  47944. configurable: true
  47945. });
  47946. // Controls
  47947. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  47948. this.inputs.attachElement(element, noPreventDefault);
  47949. };
  47950. FreeCamera.prototype.detachControl = function (element) {
  47951. this.inputs.detachElement(element);
  47952. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  47953. this.cameraRotation = new BABYLON.Vector2(0, 0);
  47954. };
  47955. Object.defineProperty(FreeCamera.prototype, "collisionMask", {
  47956. get: function () {
  47957. return this._collisionMask;
  47958. },
  47959. set: function (mask) {
  47960. this._collisionMask = !isNaN(mask) ? mask : -1;
  47961. },
  47962. enumerable: true,
  47963. configurable: true
  47964. });
  47965. FreeCamera.prototype._collideWithWorld = function (displacement) {
  47966. var globalPosition;
  47967. if (this.parent) {
  47968. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  47969. }
  47970. else {
  47971. globalPosition = this.position;
  47972. }
  47973. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  47974. this._oldPosition.addInPlace(this.ellipsoidOffset);
  47975. if (!this._collider) {
  47976. this._collider = new BABYLON.Collider();
  47977. }
  47978. this._collider._radius = this.ellipsoid;
  47979. this._collider.collisionMask = this._collisionMask;
  47980. //no need for clone, as long as gravity is not on.
  47981. var actualDisplacement = displacement;
  47982. //add gravity to the direction to prevent the dual-collision checking
  47983. if (this.applyGravity) {
  47984. //this prevents mending with cameraDirection, a global variable of the free camera class.
  47985. actualDisplacement = displacement.add(this.getScene().gravity);
  47986. }
  47987. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualDisplacement, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  47988. };
  47989. FreeCamera.prototype._checkInputs = function () {
  47990. if (!this._localDirection) {
  47991. this._localDirection = BABYLON.Vector3.Zero();
  47992. this._transformedDirection = BABYLON.Vector3.Zero();
  47993. }
  47994. this.inputs.checkInputs();
  47995. _super.prototype._checkInputs.call(this);
  47996. };
  47997. FreeCamera.prototype._decideIfNeedsToMove = function () {
  47998. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  47999. };
  48000. FreeCamera.prototype._updatePosition = function () {
  48001. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  48002. this._collideWithWorld(this.cameraDirection);
  48003. }
  48004. else {
  48005. _super.prototype._updatePosition.call(this);
  48006. }
  48007. };
  48008. FreeCamera.prototype.dispose = function () {
  48009. this.inputs.clear();
  48010. _super.prototype.dispose.call(this);
  48011. };
  48012. FreeCamera.prototype.getClassName = function () {
  48013. return "FreeCamera";
  48014. };
  48015. __decorate([
  48016. BABYLON.serializeAsVector3()
  48017. ], FreeCamera.prototype, "ellipsoid", void 0);
  48018. __decorate([
  48019. BABYLON.serializeAsVector3()
  48020. ], FreeCamera.prototype, "ellipsoidOffset", void 0);
  48021. __decorate([
  48022. BABYLON.serialize()
  48023. ], FreeCamera.prototype, "checkCollisions", void 0);
  48024. __decorate([
  48025. BABYLON.serialize()
  48026. ], FreeCamera.prototype, "applyGravity", void 0);
  48027. return FreeCamera;
  48028. }(BABYLON.TargetCamera));
  48029. BABYLON.FreeCamera = FreeCamera;
  48030. })(BABYLON || (BABYLON = {}));
  48031. //# sourceMappingURL=babylon.freeCamera.js.map
  48032. var BABYLON;
  48033. (function (BABYLON) {
  48034. var ArcRotateCameraKeyboardMoveInput = /** @class */ (function () {
  48035. function ArcRotateCameraKeyboardMoveInput() {
  48036. this._keys = new Array();
  48037. this.keysUp = [38];
  48038. this.keysDown = [40];
  48039. this.keysLeft = [37];
  48040. this.keysRight = [39];
  48041. this.keysReset = [220];
  48042. this.panningSensibility = 50.0;
  48043. this.zoomingSensibility = 25.0;
  48044. this.useAltToZoom = true;
  48045. }
  48046. ArcRotateCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  48047. var _this = this;
  48048. if (this._onCanvasBlurObserver) {
  48049. return;
  48050. }
  48051. this._scene = this.camera.getScene();
  48052. this._engine = this._scene.getEngine();
  48053. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  48054. _this._keys = [];
  48055. });
  48056. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  48057. var evt = info.event;
  48058. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  48059. _this._ctrlPressed = evt.ctrlKey;
  48060. _this._altPressed = evt.altKey;
  48061. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  48062. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  48063. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  48064. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  48065. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  48066. var index = _this._keys.indexOf(evt.keyCode);
  48067. if (index === -1) {
  48068. _this._keys.push(evt.keyCode);
  48069. }
  48070. if (evt.preventDefault) {
  48071. if (!noPreventDefault) {
  48072. evt.preventDefault();
  48073. }
  48074. }
  48075. }
  48076. }
  48077. else {
  48078. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  48079. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  48080. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  48081. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  48082. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  48083. var index = _this._keys.indexOf(evt.keyCode);
  48084. if (index >= 0) {
  48085. _this._keys.splice(index, 1);
  48086. }
  48087. if (evt.preventDefault) {
  48088. if (!noPreventDefault) {
  48089. evt.preventDefault();
  48090. }
  48091. }
  48092. }
  48093. }
  48094. });
  48095. };
  48096. ArcRotateCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  48097. if (this._scene) {
  48098. if (this._onKeyboardObserver) {
  48099. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  48100. }
  48101. if (this._onCanvasBlurObserver) {
  48102. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  48103. }
  48104. this._onKeyboardObserver = null;
  48105. this._onCanvasBlurObserver = null;
  48106. }
  48107. this._keys = [];
  48108. };
  48109. ArcRotateCameraKeyboardMoveInput.prototype.checkInputs = function () {
  48110. if (this._onKeyboardObserver) {
  48111. var camera = this.camera;
  48112. for (var index = 0; index < this._keys.length; index++) {
  48113. var keyCode = this._keys[index];
  48114. if (this.keysLeft.indexOf(keyCode) !== -1) {
  48115. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  48116. camera.inertialPanningX -= 1 / this.panningSensibility;
  48117. }
  48118. else {
  48119. camera.inertialAlphaOffset -= 0.01;
  48120. }
  48121. }
  48122. else if (this.keysUp.indexOf(keyCode) !== -1) {
  48123. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  48124. camera.inertialPanningY += 1 / this.panningSensibility;
  48125. }
  48126. else if (this._altPressed && this.useAltToZoom) {
  48127. camera.inertialRadiusOffset += 1 / this.zoomingSensibility;
  48128. }
  48129. else {
  48130. camera.inertialBetaOffset -= 0.01;
  48131. }
  48132. }
  48133. else if (this.keysRight.indexOf(keyCode) !== -1) {
  48134. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  48135. camera.inertialPanningX += 1 / this.panningSensibility;
  48136. }
  48137. else {
  48138. camera.inertialAlphaOffset += 0.01;
  48139. }
  48140. }
  48141. else if (this.keysDown.indexOf(keyCode) !== -1) {
  48142. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  48143. camera.inertialPanningY -= 1 / this.panningSensibility;
  48144. }
  48145. else if (this._altPressed && this.useAltToZoom) {
  48146. camera.inertialRadiusOffset -= 1 / this.zoomingSensibility;
  48147. }
  48148. else {
  48149. camera.inertialBetaOffset += 0.01;
  48150. }
  48151. }
  48152. else if (this.keysReset.indexOf(keyCode) !== -1) {
  48153. camera.restoreState();
  48154. }
  48155. }
  48156. }
  48157. };
  48158. ArcRotateCameraKeyboardMoveInput.prototype.getClassName = function () {
  48159. return "ArcRotateCameraKeyboardMoveInput";
  48160. };
  48161. ArcRotateCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  48162. return "keyboard";
  48163. };
  48164. __decorate([
  48165. BABYLON.serialize()
  48166. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  48167. __decorate([
  48168. BABYLON.serialize()
  48169. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  48170. __decorate([
  48171. BABYLON.serialize()
  48172. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  48173. __decorate([
  48174. BABYLON.serialize()
  48175. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  48176. __decorate([
  48177. BABYLON.serialize()
  48178. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysReset", void 0);
  48179. __decorate([
  48180. BABYLON.serialize()
  48181. ], ArcRotateCameraKeyboardMoveInput.prototype, "panningSensibility", void 0);
  48182. __decorate([
  48183. BABYLON.serialize()
  48184. ], ArcRotateCameraKeyboardMoveInput.prototype, "zoomingSensibility", void 0);
  48185. __decorate([
  48186. BABYLON.serialize()
  48187. ], ArcRotateCameraKeyboardMoveInput.prototype, "useAltToZoom", void 0);
  48188. return ArcRotateCameraKeyboardMoveInput;
  48189. }());
  48190. BABYLON.ArcRotateCameraKeyboardMoveInput = ArcRotateCameraKeyboardMoveInput;
  48191. BABYLON.CameraInputTypes["ArcRotateCameraKeyboardMoveInput"] = ArcRotateCameraKeyboardMoveInput;
  48192. })(BABYLON || (BABYLON = {}));
  48193. //# sourceMappingURL=babylon.arcRotateCameraKeyboardMoveInput.js.map
  48194. var BABYLON;
  48195. (function (BABYLON) {
  48196. var ArcRotateCameraMouseWheelInput = /** @class */ (function () {
  48197. function ArcRotateCameraMouseWheelInput() {
  48198. this.wheelPrecision = 3.0;
  48199. /**
  48200. * wheelDeltaPercentage will be used instead of wheelPrecision if different from 0.
  48201. * It defines the percentage of current camera.radius to use as delta when wheel is used.
  48202. */
  48203. this.wheelDeltaPercentage = 0;
  48204. }
  48205. ArcRotateCameraMouseWheelInput.prototype.attachControl = function (element, noPreventDefault) {
  48206. var _this = this;
  48207. this._wheel = function (p, s) {
  48208. //sanity check - this should be a PointerWheel event.
  48209. if (p.type !== BABYLON.PointerEventTypes.POINTERWHEEL)
  48210. return;
  48211. var event = p.event;
  48212. var delta = 0;
  48213. if (event.wheelDelta) {
  48214. if (_this.wheelDeltaPercentage) {
  48215. var wheelDelta = (event.wheelDelta * 0.01 * _this.wheelDeltaPercentage) * _this.camera.radius;
  48216. if (event.wheelDelta > 0) {
  48217. delta = wheelDelta / (1.0 + _this.wheelDeltaPercentage);
  48218. }
  48219. else {
  48220. delta = wheelDelta * (1.0 + _this.wheelDeltaPercentage);
  48221. }
  48222. }
  48223. else {
  48224. delta = event.wheelDelta / (_this.wheelPrecision * 40);
  48225. }
  48226. }
  48227. else if (event.detail) {
  48228. delta = -event.detail / _this.wheelPrecision;
  48229. }
  48230. if (delta)
  48231. _this.camera.inertialRadiusOffset += delta;
  48232. if (event.preventDefault) {
  48233. if (!noPreventDefault) {
  48234. event.preventDefault();
  48235. }
  48236. }
  48237. };
  48238. this._observer = this.camera.getScene().onPointerObservable.add(this._wheel, BABYLON.PointerEventTypes.POINTERWHEEL);
  48239. };
  48240. ArcRotateCameraMouseWheelInput.prototype.detachControl = function (element) {
  48241. if (this._observer && element) {
  48242. this.camera.getScene().onPointerObservable.remove(this._observer);
  48243. this._observer = null;
  48244. this._wheel = null;
  48245. }
  48246. };
  48247. ArcRotateCameraMouseWheelInput.prototype.getClassName = function () {
  48248. return "ArcRotateCameraMouseWheelInput";
  48249. };
  48250. ArcRotateCameraMouseWheelInput.prototype.getSimpleName = function () {
  48251. return "mousewheel";
  48252. };
  48253. __decorate([
  48254. BABYLON.serialize()
  48255. ], ArcRotateCameraMouseWheelInput.prototype, "wheelPrecision", void 0);
  48256. __decorate([
  48257. BABYLON.serialize()
  48258. ], ArcRotateCameraMouseWheelInput.prototype, "wheelDeltaPercentage", void 0);
  48259. return ArcRotateCameraMouseWheelInput;
  48260. }());
  48261. BABYLON.ArcRotateCameraMouseWheelInput = ArcRotateCameraMouseWheelInput;
  48262. BABYLON.CameraInputTypes["ArcRotateCameraMouseWheelInput"] = ArcRotateCameraMouseWheelInput;
  48263. })(BABYLON || (BABYLON = {}));
  48264. //# sourceMappingURL=babylon.arcRotateCameraMouseWheelInput.js.map
  48265. var BABYLON;
  48266. (function (BABYLON) {
  48267. var ArcRotateCameraPointersInput = /** @class */ (function () {
  48268. function ArcRotateCameraPointersInput() {
  48269. this.buttons = [0, 1, 2];
  48270. this.angularSensibilityX = 1000.0;
  48271. this.angularSensibilityY = 1000.0;
  48272. this.pinchPrecision = 12.0;
  48273. /**
  48274. * pinchDeltaPercentage will be used instead of pinchPrecision if different from 0.
  48275. * It defines the percentage of current camera.radius to use as delta when pinch zoom is used.
  48276. */
  48277. this.pinchDeltaPercentage = 0;
  48278. this.panningSensibility = 1000.0;
  48279. this.multiTouchPanning = true;
  48280. this.multiTouchPanAndZoom = true;
  48281. this._isPanClick = false;
  48282. this.pinchInwards = true;
  48283. }
  48284. ArcRotateCameraPointersInput.prototype.attachControl = function (element, noPreventDefault) {
  48285. var _this = this;
  48286. var engine = this.camera.getEngine();
  48287. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  48288. var pointA = null;
  48289. var pointB = null;
  48290. var previousPinchSquaredDistance = 0;
  48291. var initialDistance = 0;
  48292. var twoFingerActivityCount = 0;
  48293. var previousMultiTouchPanPosition = { x: 0, y: 0, isPaning: false, isPinching: false };
  48294. this._pointerInput = function (p, s) {
  48295. var evt = p.event;
  48296. var isTouch = p.event.pointerType === "touch";
  48297. if (engine.isInVRExclusivePointerMode) {
  48298. return;
  48299. }
  48300. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  48301. return;
  48302. }
  48303. var srcElement = (evt.srcElement || evt.target);
  48304. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  48305. try {
  48306. srcElement.setPointerCapture(evt.pointerId);
  48307. }
  48308. catch (e) {
  48309. //Nothing to do with the error. Execution will continue.
  48310. }
  48311. // Manage panning with pan button click
  48312. _this._isPanClick = evt.button === _this.camera._panningMouseButton;
  48313. // manage pointers
  48314. cacheSoloPointer = { x: evt.clientX, y: evt.clientY, pointerId: evt.pointerId, type: evt.pointerType };
  48315. if (pointA === null) {
  48316. pointA = cacheSoloPointer;
  48317. }
  48318. else if (pointB === null) {
  48319. pointB = cacheSoloPointer;
  48320. }
  48321. if (!noPreventDefault) {
  48322. evt.preventDefault();
  48323. element.focus();
  48324. }
  48325. }
  48326. else if (p.type === BABYLON.PointerEventTypes.POINTERDOUBLETAP) {
  48327. _this.camera.restoreState();
  48328. }
  48329. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  48330. try {
  48331. srcElement.releasePointerCapture(evt.pointerId);
  48332. }
  48333. catch (e) {
  48334. //Nothing to do with the error.
  48335. }
  48336. cacheSoloPointer = null;
  48337. previousPinchSquaredDistance = 0;
  48338. previousMultiTouchPanPosition.isPaning = false;
  48339. previousMultiTouchPanPosition.isPinching = false;
  48340. twoFingerActivityCount = 0;
  48341. initialDistance = 0;
  48342. if (!isTouch) {
  48343. pointB = null; // Mouse and pen are mono pointer
  48344. }
  48345. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  48346. //but emptying completly pointers collection is required to fix a bug on iPhone :
  48347. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  48348. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  48349. if (engine._badOS) {
  48350. pointA = pointB = null;
  48351. }
  48352. else {
  48353. //only remove the impacted pointer in case of multitouch allowing on most
  48354. //platforms switching from rotate to zoom and pan seamlessly.
  48355. if (pointB && pointA && pointA.pointerId == evt.pointerId) {
  48356. pointA = pointB;
  48357. pointB = null;
  48358. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  48359. }
  48360. else if (pointA && pointB && pointB.pointerId == evt.pointerId) {
  48361. pointB = null;
  48362. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  48363. }
  48364. else {
  48365. pointA = pointB = null;
  48366. }
  48367. }
  48368. if (!noPreventDefault) {
  48369. evt.preventDefault();
  48370. }
  48371. }
  48372. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  48373. if (!noPreventDefault) {
  48374. evt.preventDefault();
  48375. }
  48376. // One button down
  48377. if (pointA && pointB === null && cacheSoloPointer) {
  48378. if (_this.panningSensibility !== 0 &&
  48379. ((evt.ctrlKey && _this.camera._useCtrlForPanning) || _this._isPanClick)) {
  48380. _this.camera.inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  48381. _this.camera.inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  48382. }
  48383. else {
  48384. var offsetX = evt.clientX - cacheSoloPointer.x;
  48385. var offsetY = evt.clientY - cacheSoloPointer.y;
  48386. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  48387. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  48388. }
  48389. cacheSoloPointer.x = evt.clientX;
  48390. cacheSoloPointer.y = evt.clientY;
  48391. }
  48392. // Two buttons down: pinch/pan
  48393. else if (pointA && pointB) {
  48394. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be useful to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  48395. var ed = (pointA.pointerId === evt.pointerId) ? pointA : pointB;
  48396. ed.x = evt.clientX;
  48397. ed.y = evt.clientY;
  48398. var direction = _this.pinchInwards ? 1 : -1;
  48399. var distX = pointA.x - pointB.x;
  48400. var distY = pointA.y - pointB.y;
  48401. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  48402. var pinchDistance = Math.sqrt(pinchSquaredDistance);
  48403. if (previousPinchSquaredDistance === 0) {
  48404. initialDistance = pinchDistance;
  48405. previousPinchSquaredDistance = pinchSquaredDistance;
  48406. previousMultiTouchPanPosition.x = (pointA.x + pointB.x) / 2;
  48407. previousMultiTouchPanPosition.y = (pointA.y + pointB.y) / 2;
  48408. return;
  48409. }
  48410. if (_this.multiTouchPanAndZoom) {
  48411. if (_this.pinchDeltaPercentage) {
  48412. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  48413. }
  48414. else {
  48415. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  48416. (_this.pinchPrecision *
  48417. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  48418. direction);
  48419. }
  48420. if (_this.panningSensibility !== 0) {
  48421. var pointersCenterX = (pointA.x + pointB.x) / 2;
  48422. var pointersCenterY = (pointA.y + pointB.y) / 2;
  48423. var pointersCenterDistX = pointersCenterX - previousMultiTouchPanPosition.x;
  48424. var pointersCenterDistY = pointersCenterY - previousMultiTouchPanPosition.y;
  48425. previousMultiTouchPanPosition.x = pointersCenterX;
  48426. previousMultiTouchPanPosition.y = pointersCenterY;
  48427. _this.camera.inertialPanningX += -(pointersCenterDistX) / (_this.panningSensibility);
  48428. _this.camera.inertialPanningY += (pointersCenterDistY) / (_this.panningSensibility);
  48429. }
  48430. }
  48431. else {
  48432. twoFingerActivityCount++;
  48433. if (previousMultiTouchPanPosition.isPinching || (twoFingerActivityCount < 20 && Math.abs(pinchDistance - initialDistance) > _this.camera.pinchToPanMaxDistance)) {
  48434. if (_this.pinchDeltaPercentage) {
  48435. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  48436. }
  48437. else {
  48438. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  48439. (_this.pinchPrecision *
  48440. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  48441. direction);
  48442. }
  48443. previousMultiTouchPanPosition.isPaning = false;
  48444. previousMultiTouchPanPosition.isPinching = true;
  48445. }
  48446. else {
  48447. if (cacheSoloPointer && cacheSoloPointer.pointerId === ed.pointerId && _this.panningSensibility !== 0 && _this.multiTouchPanning) {
  48448. if (!previousMultiTouchPanPosition.isPaning) {
  48449. previousMultiTouchPanPosition.isPaning = true;
  48450. previousMultiTouchPanPosition.isPinching = false;
  48451. previousMultiTouchPanPosition.x = ed.x;
  48452. previousMultiTouchPanPosition.y = ed.y;
  48453. return;
  48454. }
  48455. _this.camera.inertialPanningX += -(ed.x - previousMultiTouchPanPosition.x) / (_this.panningSensibility);
  48456. _this.camera.inertialPanningY += (ed.y - previousMultiTouchPanPosition.y) / (_this.panningSensibility);
  48457. }
  48458. }
  48459. if (cacheSoloPointer && cacheSoloPointer.pointerId === evt.pointerId) {
  48460. previousMultiTouchPanPosition.x = ed.x;
  48461. previousMultiTouchPanPosition.y = ed.y;
  48462. }
  48463. }
  48464. previousPinchSquaredDistance = pinchSquaredDistance;
  48465. }
  48466. }
  48467. };
  48468. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE | BABYLON.PointerEventTypes._POINTERDOUBLETAP);
  48469. this._onContextMenu = function (evt) {
  48470. evt.preventDefault();
  48471. };
  48472. if (!this.camera._useCtrlForPanning) {
  48473. element.addEventListener("contextmenu", this._onContextMenu, false);
  48474. }
  48475. this._onLostFocus = function () {
  48476. //this._keys = [];
  48477. pointA = pointB = null;
  48478. previousPinchSquaredDistance = 0;
  48479. previousMultiTouchPanPosition.isPaning = false;
  48480. previousMultiTouchPanPosition.isPinching = false;
  48481. twoFingerActivityCount = 0;
  48482. cacheSoloPointer = null;
  48483. initialDistance = 0;
  48484. };
  48485. this._onMouseMove = function (evt) {
  48486. if (!engine.isPointerLock) {
  48487. return;
  48488. }
  48489. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  48490. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  48491. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  48492. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  48493. if (!noPreventDefault) {
  48494. evt.preventDefault();
  48495. }
  48496. };
  48497. this._onGestureStart = function (e) {
  48498. if (window.MSGesture === undefined) {
  48499. return;
  48500. }
  48501. if (!_this._MSGestureHandler) {
  48502. _this._MSGestureHandler = new MSGesture();
  48503. _this._MSGestureHandler.target = element;
  48504. }
  48505. _this._MSGestureHandler.addPointer(e.pointerId);
  48506. };
  48507. this._onGesture = function (e) {
  48508. _this.camera.radius *= e.scale;
  48509. if (e.preventDefault) {
  48510. if (!noPreventDefault) {
  48511. e.stopPropagation();
  48512. e.preventDefault();
  48513. }
  48514. }
  48515. };
  48516. element.addEventListener("mousemove", this._onMouseMove, false);
  48517. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  48518. element.addEventListener("MSGestureChange", this._onGesture, false);
  48519. BABYLON.Tools.RegisterTopRootEvents([
  48520. { name: "blur", handler: this._onLostFocus }
  48521. ]);
  48522. };
  48523. ArcRotateCameraPointersInput.prototype.detachControl = function (element) {
  48524. if (this._onLostFocus) {
  48525. BABYLON.Tools.UnregisterTopRootEvents([
  48526. { name: "blur", handler: this._onLostFocus }
  48527. ]);
  48528. }
  48529. if (element && this._observer) {
  48530. this.camera.getScene().onPointerObservable.remove(this._observer);
  48531. this._observer = null;
  48532. if (this._onContextMenu) {
  48533. element.removeEventListener("contextmenu", this._onContextMenu);
  48534. }
  48535. if (this._onMouseMove) {
  48536. element.removeEventListener("mousemove", this._onMouseMove);
  48537. }
  48538. if (this._onGestureStart) {
  48539. element.removeEventListener("MSPointerDown", this._onGestureStart);
  48540. }
  48541. if (this._onGesture) {
  48542. element.removeEventListener("MSGestureChange", this._onGesture);
  48543. }
  48544. this._isPanClick = false;
  48545. this.pinchInwards = true;
  48546. this._onMouseMove = null;
  48547. this._onGestureStart = null;
  48548. this._onGesture = null;
  48549. this._MSGestureHandler = null;
  48550. this._onLostFocus = null;
  48551. this._onContextMenu = null;
  48552. }
  48553. };
  48554. ArcRotateCameraPointersInput.prototype.getClassName = function () {
  48555. return "ArcRotateCameraPointersInput";
  48556. };
  48557. ArcRotateCameraPointersInput.prototype.getSimpleName = function () {
  48558. return "pointers";
  48559. };
  48560. __decorate([
  48561. BABYLON.serialize()
  48562. ], ArcRotateCameraPointersInput.prototype, "buttons", void 0);
  48563. __decorate([
  48564. BABYLON.serialize()
  48565. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityX", void 0);
  48566. __decorate([
  48567. BABYLON.serialize()
  48568. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityY", void 0);
  48569. __decorate([
  48570. BABYLON.serialize()
  48571. ], ArcRotateCameraPointersInput.prototype, "pinchPrecision", void 0);
  48572. __decorate([
  48573. BABYLON.serialize()
  48574. ], ArcRotateCameraPointersInput.prototype, "pinchDeltaPercentage", void 0);
  48575. __decorate([
  48576. BABYLON.serialize()
  48577. ], ArcRotateCameraPointersInput.prototype, "panningSensibility", void 0);
  48578. __decorate([
  48579. BABYLON.serialize()
  48580. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanning", void 0);
  48581. __decorate([
  48582. BABYLON.serialize()
  48583. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanAndZoom", void 0);
  48584. return ArcRotateCameraPointersInput;
  48585. }());
  48586. BABYLON.ArcRotateCameraPointersInput = ArcRotateCameraPointersInput;
  48587. BABYLON.CameraInputTypes["ArcRotateCameraPointersInput"] = ArcRotateCameraPointersInput;
  48588. })(BABYLON || (BABYLON = {}));
  48589. //# sourceMappingURL=babylon.arcRotateCameraPointersInput.js.map
  48590. var BABYLON;
  48591. (function (BABYLON) {
  48592. var ArcRotateCameraInputsManager = /** @class */ (function (_super) {
  48593. __extends(ArcRotateCameraInputsManager, _super);
  48594. function ArcRotateCameraInputsManager(camera) {
  48595. return _super.call(this, camera) || this;
  48596. }
  48597. ArcRotateCameraInputsManager.prototype.addMouseWheel = function () {
  48598. this.add(new BABYLON.ArcRotateCameraMouseWheelInput());
  48599. return this;
  48600. };
  48601. ArcRotateCameraInputsManager.prototype.addPointers = function () {
  48602. this.add(new BABYLON.ArcRotateCameraPointersInput());
  48603. return this;
  48604. };
  48605. ArcRotateCameraInputsManager.prototype.addKeyboard = function () {
  48606. this.add(new BABYLON.ArcRotateCameraKeyboardMoveInput());
  48607. return this;
  48608. };
  48609. ArcRotateCameraInputsManager.prototype.addGamepad = function () {
  48610. this.add(new BABYLON.ArcRotateCameraGamepadInput());
  48611. return this;
  48612. };
  48613. ArcRotateCameraInputsManager.prototype.addVRDeviceOrientation = function () {
  48614. this.add(new BABYLON.ArcRotateCameraVRDeviceOrientationInput());
  48615. return this;
  48616. };
  48617. return ArcRotateCameraInputsManager;
  48618. }(BABYLON.CameraInputsManager));
  48619. BABYLON.ArcRotateCameraInputsManager = ArcRotateCameraInputsManager;
  48620. })(BABYLON || (BABYLON = {}));
  48621. //# sourceMappingURL=babylon.arcRotateCameraInputsManager.js.map
  48622. var BABYLON;
  48623. (function (BABYLON) {
  48624. var ArcRotateCamera = /** @class */ (function (_super) {
  48625. __extends(ArcRotateCamera, _super);
  48626. function ArcRotateCamera(name, alpha, beta, radius, target, scene, setActiveOnSceneIfNoneActive) {
  48627. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  48628. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene, setActiveOnSceneIfNoneActive) || this;
  48629. _this.inertialAlphaOffset = 0;
  48630. _this.inertialBetaOffset = 0;
  48631. _this.inertialRadiusOffset = 0;
  48632. _this.lowerAlphaLimit = null;
  48633. _this.upperAlphaLimit = null;
  48634. _this.lowerBetaLimit = 0.01;
  48635. _this.upperBetaLimit = Math.PI;
  48636. _this.lowerRadiusLimit = null;
  48637. _this.upperRadiusLimit = null;
  48638. _this.inertialPanningX = 0;
  48639. _this.inertialPanningY = 0;
  48640. _this.pinchToPanMaxDistance = 20;
  48641. _this.panningDistanceLimit = null;
  48642. _this.panningOriginTarget = BABYLON.Vector3.Zero();
  48643. _this.panningInertia = 0.9;
  48644. //-- end properties for backward compatibility for inputs
  48645. _this.zoomOnFactor = 1;
  48646. _this.targetScreenOffset = BABYLON.Vector2.Zero();
  48647. _this.allowUpsideDown = true;
  48648. _this._viewMatrix = new BABYLON.Matrix();
  48649. // Panning
  48650. _this.panningAxis = new BABYLON.Vector3(1, 1, 0);
  48651. _this.onMeshTargetChangedObservable = new BABYLON.Observable();
  48652. _this.checkCollisions = false;
  48653. _this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  48654. _this._previousPosition = BABYLON.Vector3.Zero();
  48655. _this._collisionVelocity = BABYLON.Vector3.Zero();
  48656. _this._newPosition = BABYLON.Vector3.Zero();
  48657. _this._computationVector = BABYLON.Vector3.Zero();
  48658. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  48659. if (collidedMesh === void 0) { collidedMesh = null; }
  48660. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  48661. newPosition.multiplyInPlace(_this._collider._radius);
  48662. }
  48663. if (!collidedMesh) {
  48664. _this._previousPosition.copyFrom(_this.position);
  48665. }
  48666. else {
  48667. _this.setPosition(newPosition);
  48668. if (_this.onCollide) {
  48669. _this.onCollide(collidedMesh);
  48670. }
  48671. }
  48672. // Recompute because of constraints
  48673. var cosa = Math.cos(_this.alpha);
  48674. var sina = Math.sin(_this.alpha);
  48675. var cosb = Math.cos(_this.beta);
  48676. var sinb = Math.sin(_this.beta);
  48677. if (sinb === 0) {
  48678. sinb = 0.0001;
  48679. }
  48680. var target = _this._getTargetPosition();
  48681. _this._computationVector.copyFromFloats(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb);
  48682. target.addToRef(_this._computationVector, _this._newPosition);
  48683. _this.position.copyFrom(_this._newPosition);
  48684. var up = _this.upVector;
  48685. if (_this.allowUpsideDown && _this.beta < 0) {
  48686. up = up.clone();
  48687. up = up.negate();
  48688. }
  48689. _this._computeViewMatrix(_this.position, target, up);
  48690. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  48691. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  48692. _this._collisionTriggered = false;
  48693. };
  48694. _this._target = BABYLON.Vector3.Zero();
  48695. if (target) {
  48696. _this.setTarget(target);
  48697. }
  48698. _this.alpha = alpha;
  48699. _this.beta = beta;
  48700. _this.radius = radius;
  48701. _this.getViewMatrix();
  48702. _this.inputs = new BABYLON.ArcRotateCameraInputsManager(_this);
  48703. _this.inputs.addKeyboard().addMouseWheel().addPointers();
  48704. return _this;
  48705. }
  48706. Object.defineProperty(ArcRotateCamera.prototype, "target", {
  48707. get: function () {
  48708. return this._target;
  48709. },
  48710. set: function (value) {
  48711. this.setTarget(value);
  48712. },
  48713. enumerable: true,
  48714. configurable: true
  48715. });
  48716. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityX", {
  48717. //-- begin properties for backward compatibility for inputs
  48718. get: function () {
  48719. var pointers = this.inputs.attached["pointers"];
  48720. if (pointers)
  48721. return pointers.angularSensibilityX;
  48722. return 0;
  48723. },
  48724. set: function (value) {
  48725. var pointers = this.inputs.attached["pointers"];
  48726. if (pointers) {
  48727. pointers.angularSensibilityX = value;
  48728. }
  48729. },
  48730. enumerable: true,
  48731. configurable: true
  48732. });
  48733. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityY", {
  48734. get: function () {
  48735. var pointers = this.inputs.attached["pointers"];
  48736. if (pointers)
  48737. return pointers.angularSensibilityY;
  48738. return 0;
  48739. },
  48740. set: function (value) {
  48741. var pointers = this.inputs.attached["pointers"];
  48742. if (pointers) {
  48743. pointers.angularSensibilityY = value;
  48744. }
  48745. },
  48746. enumerable: true,
  48747. configurable: true
  48748. });
  48749. Object.defineProperty(ArcRotateCamera.prototype, "pinchPrecision", {
  48750. get: function () {
  48751. var pointers = this.inputs.attached["pointers"];
  48752. if (pointers)
  48753. return pointers.pinchPrecision;
  48754. return 0;
  48755. },
  48756. set: function (value) {
  48757. var pointers = this.inputs.attached["pointers"];
  48758. if (pointers) {
  48759. pointers.pinchPrecision = value;
  48760. }
  48761. },
  48762. enumerable: true,
  48763. configurable: true
  48764. });
  48765. Object.defineProperty(ArcRotateCamera.prototype, "pinchDeltaPercentage", {
  48766. get: function () {
  48767. var pointers = this.inputs.attached["pointers"];
  48768. if (pointers)
  48769. return pointers.pinchDeltaPercentage;
  48770. return 0;
  48771. },
  48772. set: function (value) {
  48773. var pointers = this.inputs.attached["pointers"];
  48774. if (pointers) {
  48775. pointers.pinchDeltaPercentage = value;
  48776. }
  48777. },
  48778. enumerable: true,
  48779. configurable: true
  48780. });
  48781. Object.defineProperty(ArcRotateCamera.prototype, "panningSensibility", {
  48782. get: function () {
  48783. var pointers = this.inputs.attached["pointers"];
  48784. if (pointers)
  48785. return pointers.panningSensibility;
  48786. return 0;
  48787. },
  48788. set: function (value) {
  48789. var pointers = this.inputs.attached["pointers"];
  48790. if (pointers) {
  48791. pointers.panningSensibility = value;
  48792. }
  48793. },
  48794. enumerable: true,
  48795. configurable: true
  48796. });
  48797. Object.defineProperty(ArcRotateCamera.prototype, "keysUp", {
  48798. get: function () {
  48799. var keyboard = this.inputs.attached["keyboard"];
  48800. if (keyboard)
  48801. return keyboard.keysUp;
  48802. return [];
  48803. },
  48804. set: function (value) {
  48805. var keyboard = this.inputs.attached["keyboard"];
  48806. if (keyboard)
  48807. keyboard.keysUp = value;
  48808. },
  48809. enumerable: true,
  48810. configurable: true
  48811. });
  48812. Object.defineProperty(ArcRotateCamera.prototype, "keysDown", {
  48813. get: function () {
  48814. var keyboard = this.inputs.attached["keyboard"];
  48815. if (keyboard)
  48816. return keyboard.keysDown;
  48817. return [];
  48818. },
  48819. set: function (value) {
  48820. var keyboard = this.inputs.attached["keyboard"];
  48821. if (keyboard)
  48822. keyboard.keysDown = value;
  48823. },
  48824. enumerable: true,
  48825. configurable: true
  48826. });
  48827. Object.defineProperty(ArcRotateCamera.prototype, "keysLeft", {
  48828. get: function () {
  48829. var keyboard = this.inputs.attached["keyboard"];
  48830. if (keyboard)
  48831. return keyboard.keysLeft;
  48832. return [];
  48833. },
  48834. set: function (value) {
  48835. var keyboard = this.inputs.attached["keyboard"];
  48836. if (keyboard)
  48837. keyboard.keysLeft = value;
  48838. },
  48839. enumerable: true,
  48840. configurable: true
  48841. });
  48842. Object.defineProperty(ArcRotateCamera.prototype, "keysRight", {
  48843. get: function () {
  48844. var keyboard = this.inputs.attached["keyboard"];
  48845. if (keyboard)
  48846. return keyboard.keysRight;
  48847. return [];
  48848. },
  48849. set: function (value) {
  48850. var keyboard = this.inputs.attached["keyboard"];
  48851. if (keyboard)
  48852. keyboard.keysRight = value;
  48853. },
  48854. enumerable: true,
  48855. configurable: true
  48856. });
  48857. Object.defineProperty(ArcRotateCamera.prototype, "wheelPrecision", {
  48858. get: function () {
  48859. var mousewheel = this.inputs.attached["mousewheel"];
  48860. if (mousewheel)
  48861. return mousewheel.wheelPrecision;
  48862. return 0;
  48863. },
  48864. set: function (value) {
  48865. var mousewheel = this.inputs.attached["mousewheel"];
  48866. if (mousewheel)
  48867. mousewheel.wheelPrecision = value;
  48868. },
  48869. enumerable: true,
  48870. configurable: true
  48871. });
  48872. Object.defineProperty(ArcRotateCamera.prototype, "wheelDeltaPercentage", {
  48873. get: function () {
  48874. var mousewheel = this.inputs.attached["mousewheel"];
  48875. if (mousewheel)
  48876. return mousewheel.wheelDeltaPercentage;
  48877. return 0;
  48878. },
  48879. set: function (value) {
  48880. var mousewheel = this.inputs.attached["mousewheel"];
  48881. if (mousewheel)
  48882. mousewheel.wheelDeltaPercentage = value;
  48883. },
  48884. enumerable: true,
  48885. configurable: true
  48886. });
  48887. Object.defineProperty(ArcRotateCamera.prototype, "bouncingBehavior", {
  48888. get: function () {
  48889. return this._bouncingBehavior;
  48890. },
  48891. enumerable: true,
  48892. configurable: true
  48893. });
  48894. Object.defineProperty(ArcRotateCamera.prototype, "useBouncingBehavior", {
  48895. get: function () {
  48896. return this._bouncingBehavior != null;
  48897. },
  48898. set: function (value) {
  48899. if (value === this.useBouncingBehavior) {
  48900. return;
  48901. }
  48902. if (value) {
  48903. this._bouncingBehavior = new BABYLON.BouncingBehavior();
  48904. this.addBehavior(this._bouncingBehavior);
  48905. }
  48906. else if (this._bouncingBehavior) {
  48907. this.removeBehavior(this._bouncingBehavior);
  48908. this._bouncingBehavior = null;
  48909. }
  48910. },
  48911. enumerable: true,
  48912. configurable: true
  48913. });
  48914. Object.defineProperty(ArcRotateCamera.prototype, "framingBehavior", {
  48915. get: function () {
  48916. return this._framingBehavior;
  48917. },
  48918. enumerable: true,
  48919. configurable: true
  48920. });
  48921. Object.defineProperty(ArcRotateCamera.prototype, "useFramingBehavior", {
  48922. get: function () {
  48923. return this._framingBehavior != null;
  48924. },
  48925. set: function (value) {
  48926. if (value === this.useFramingBehavior) {
  48927. return;
  48928. }
  48929. if (value) {
  48930. this._framingBehavior = new BABYLON.FramingBehavior();
  48931. this.addBehavior(this._framingBehavior);
  48932. }
  48933. else if (this._framingBehavior) {
  48934. this.removeBehavior(this._framingBehavior);
  48935. this._framingBehavior = null;
  48936. }
  48937. },
  48938. enumerable: true,
  48939. configurable: true
  48940. });
  48941. Object.defineProperty(ArcRotateCamera.prototype, "autoRotationBehavior", {
  48942. get: function () {
  48943. return this._autoRotationBehavior;
  48944. },
  48945. enumerable: true,
  48946. configurable: true
  48947. });
  48948. Object.defineProperty(ArcRotateCamera.prototype, "useAutoRotationBehavior", {
  48949. get: function () {
  48950. return this._autoRotationBehavior != null;
  48951. },
  48952. set: function (value) {
  48953. if (value === this.useAutoRotationBehavior) {
  48954. return;
  48955. }
  48956. if (value) {
  48957. this._autoRotationBehavior = new BABYLON.AutoRotationBehavior();
  48958. this.addBehavior(this._autoRotationBehavior);
  48959. }
  48960. else if (this._autoRotationBehavior) {
  48961. this.removeBehavior(this._autoRotationBehavior);
  48962. this._autoRotationBehavior = null;
  48963. }
  48964. },
  48965. enumerable: true,
  48966. configurable: true
  48967. });
  48968. // Cache
  48969. ArcRotateCamera.prototype._initCache = function () {
  48970. _super.prototype._initCache.call(this);
  48971. this._cache._target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  48972. this._cache.alpha = undefined;
  48973. this._cache.beta = undefined;
  48974. this._cache.radius = undefined;
  48975. this._cache.targetScreenOffset = BABYLON.Vector2.Zero();
  48976. };
  48977. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  48978. if (!ignoreParentClass) {
  48979. _super.prototype._updateCache.call(this);
  48980. }
  48981. this._cache._target.copyFrom(this._getTargetPosition());
  48982. this._cache.alpha = this.alpha;
  48983. this._cache.beta = this.beta;
  48984. this._cache.radius = this.radius;
  48985. this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
  48986. };
  48987. ArcRotateCamera.prototype._getTargetPosition = function () {
  48988. if (this._targetHost && this._targetHost.getAbsolutePosition) {
  48989. var pos = this._targetHost.getAbsolutePosition();
  48990. if (this._targetBoundingCenter) {
  48991. pos.addToRef(this._targetBoundingCenter, this._target);
  48992. }
  48993. else {
  48994. this._target.copyFrom(pos);
  48995. }
  48996. }
  48997. var lockedTargetPosition = this._getLockedTargetPosition();
  48998. if (lockedTargetPosition) {
  48999. return lockedTargetPosition;
  49000. }
  49001. return this._target;
  49002. };
  49003. ArcRotateCamera.prototype.storeState = function () {
  49004. this._storedAlpha = this.alpha;
  49005. this._storedBeta = this.beta;
  49006. this._storedRadius = this.radius;
  49007. this._storedTarget = this._getTargetPosition().clone();
  49008. return _super.prototype.storeState.call(this);
  49009. };
  49010. /**
  49011. * Restored camera state. You must call storeState() first
  49012. */
  49013. ArcRotateCamera.prototype._restoreStateValues = function () {
  49014. if (!_super.prototype._restoreStateValues.call(this)) {
  49015. return false;
  49016. }
  49017. this.alpha = this._storedAlpha;
  49018. this.beta = this._storedBeta;
  49019. this.radius = this._storedRadius;
  49020. this.setTarget(this._storedTarget.clone());
  49021. this.inertialAlphaOffset = 0;
  49022. this.inertialBetaOffset = 0;
  49023. this.inertialRadiusOffset = 0;
  49024. this.inertialPanningX = 0;
  49025. this.inertialPanningY = 0;
  49026. return true;
  49027. };
  49028. // Synchronized
  49029. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  49030. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  49031. return false;
  49032. return this._cache._target.equals(this._getTargetPosition())
  49033. && this._cache.alpha === this.alpha
  49034. && this._cache.beta === this.beta
  49035. && this._cache.radius === this.radius
  49036. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  49037. };
  49038. // Methods
  49039. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning, panningMouseButton) {
  49040. var _this = this;
  49041. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  49042. if (panningMouseButton === void 0) { panningMouseButton = 2; }
  49043. this._useCtrlForPanning = useCtrlForPanning;
  49044. this._panningMouseButton = panningMouseButton;
  49045. this.inputs.attachElement(element, noPreventDefault);
  49046. this._reset = function () {
  49047. _this.inertialAlphaOffset = 0;
  49048. _this.inertialBetaOffset = 0;
  49049. _this.inertialRadiusOffset = 0;
  49050. _this.inertialPanningX = 0;
  49051. _this.inertialPanningY = 0;
  49052. };
  49053. };
  49054. ArcRotateCamera.prototype.detachControl = function (element) {
  49055. this.inputs.detachElement(element);
  49056. if (this._reset) {
  49057. this._reset();
  49058. }
  49059. };
  49060. ArcRotateCamera.prototype._checkInputs = function () {
  49061. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  49062. if (this._collisionTriggered) {
  49063. return;
  49064. }
  49065. this.inputs.checkInputs();
  49066. // Inertia
  49067. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) {
  49068. var inertialAlphaOffset = this.inertialAlphaOffset;
  49069. if (this.beta <= 0)
  49070. inertialAlphaOffset *= -1;
  49071. if (this.getScene().useRightHandedSystem)
  49072. inertialAlphaOffset *= -1;
  49073. if (this.parent && this.parent._getWorldMatrixDeterminant() < 0)
  49074. inertialAlphaOffset *= -1;
  49075. this.alpha += inertialAlphaOffset;
  49076. this.beta += this.inertialBetaOffset;
  49077. this.radius -= this.inertialRadiusOffset;
  49078. this.inertialAlphaOffset *= this.inertia;
  49079. this.inertialBetaOffset *= this.inertia;
  49080. this.inertialRadiusOffset *= this.inertia;
  49081. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Epsilon)
  49082. this.inertialAlphaOffset = 0;
  49083. if (Math.abs(this.inertialBetaOffset) < BABYLON.Epsilon)
  49084. this.inertialBetaOffset = 0;
  49085. if (Math.abs(this.inertialRadiusOffset) < this.speed * BABYLON.Epsilon)
  49086. this.inertialRadiusOffset = 0;
  49087. }
  49088. // Panning inertia
  49089. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  49090. if (!this._localDirection) {
  49091. this._localDirection = BABYLON.Vector3.Zero();
  49092. this._transformedDirection = BABYLON.Vector3.Zero();
  49093. }
  49094. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, this.inertialPanningY);
  49095. this._localDirection.multiplyInPlace(this.panningAxis);
  49096. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  49097. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  49098. //Eliminate y if map panning is enabled (panningAxis == 1,0,1)
  49099. if (!this.panningAxis.y) {
  49100. this._transformedDirection.y = 0;
  49101. }
  49102. if (!this._targetHost) {
  49103. if (this.panningDistanceLimit) {
  49104. this._transformedDirection.addInPlace(this._target);
  49105. var distanceSquared = BABYLON.Vector3.DistanceSquared(this._transformedDirection, this.panningOriginTarget);
  49106. if (distanceSquared <= (this.panningDistanceLimit * this.panningDistanceLimit)) {
  49107. this._target.copyFrom(this._transformedDirection);
  49108. }
  49109. }
  49110. else {
  49111. this._target.addInPlace(this._transformedDirection);
  49112. }
  49113. }
  49114. this.inertialPanningX *= this.panningInertia;
  49115. this.inertialPanningY *= this.panningInertia;
  49116. if (Math.abs(this.inertialPanningX) < this.speed * BABYLON.Epsilon)
  49117. this.inertialPanningX = 0;
  49118. if (Math.abs(this.inertialPanningY) < this.speed * BABYLON.Epsilon)
  49119. this.inertialPanningY = 0;
  49120. }
  49121. // Limits
  49122. this._checkLimits();
  49123. _super.prototype._checkInputs.call(this);
  49124. };
  49125. ArcRotateCamera.prototype._checkLimits = function () {
  49126. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  49127. if (this.allowUpsideDown && this.beta > Math.PI) {
  49128. this.beta = this.beta - (2 * Math.PI);
  49129. }
  49130. }
  49131. else {
  49132. if (this.beta < this.lowerBetaLimit) {
  49133. this.beta = this.lowerBetaLimit;
  49134. }
  49135. }
  49136. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  49137. if (this.allowUpsideDown && this.beta < -Math.PI) {
  49138. this.beta = this.beta + (2 * Math.PI);
  49139. }
  49140. }
  49141. else {
  49142. if (this.beta > this.upperBetaLimit) {
  49143. this.beta = this.upperBetaLimit;
  49144. }
  49145. }
  49146. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  49147. this.alpha = this.lowerAlphaLimit;
  49148. }
  49149. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  49150. this.alpha = this.upperAlphaLimit;
  49151. }
  49152. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  49153. this.radius = this.lowerRadiusLimit;
  49154. }
  49155. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  49156. this.radius = this.upperRadiusLimit;
  49157. }
  49158. };
  49159. ArcRotateCamera.prototype.rebuildAnglesAndRadius = function () {
  49160. this.position.subtractToRef(this._getTargetPosition(), this._computationVector);
  49161. this.radius = this._computationVector.length();
  49162. if (this.radius === 0) {
  49163. this.radius = 0.0001; // Just to avoid division by zero
  49164. }
  49165. // Alpha
  49166. this.alpha = Math.acos(this._computationVector.x / Math.sqrt(Math.pow(this._computationVector.x, 2) + Math.pow(this._computationVector.z, 2)));
  49167. if (this._computationVector.z < 0) {
  49168. this.alpha = 2 * Math.PI - this.alpha;
  49169. }
  49170. // Beta
  49171. this.beta = Math.acos(this._computationVector.y / this.radius);
  49172. this._checkLimits();
  49173. };
  49174. ArcRotateCamera.prototype.setPosition = function (position) {
  49175. if (this.position.equals(position)) {
  49176. return;
  49177. }
  49178. this.position.copyFrom(position);
  49179. this.rebuildAnglesAndRadius();
  49180. };
  49181. ArcRotateCamera.prototype.setTarget = function (target, toBoundingCenter, allowSamePosition) {
  49182. if (toBoundingCenter === void 0) { toBoundingCenter = false; }
  49183. if (allowSamePosition === void 0) { allowSamePosition = false; }
  49184. if (target.getBoundingInfo) {
  49185. if (toBoundingCenter) {
  49186. this._targetBoundingCenter = target.getBoundingInfo().boundingBox.centerWorld.clone();
  49187. }
  49188. else {
  49189. this._targetBoundingCenter = null;
  49190. }
  49191. this._targetHost = target;
  49192. this._target = this._getTargetPosition();
  49193. this.onMeshTargetChangedObservable.notifyObservers(this._targetHost);
  49194. }
  49195. else {
  49196. var newTarget = target;
  49197. var currentTarget = this._getTargetPosition();
  49198. if (currentTarget && !allowSamePosition && currentTarget.equals(newTarget)) {
  49199. return;
  49200. }
  49201. this._targetHost = null;
  49202. this._target = newTarget;
  49203. this._targetBoundingCenter = null;
  49204. this.onMeshTargetChangedObservable.notifyObservers(null);
  49205. }
  49206. this.rebuildAnglesAndRadius();
  49207. };
  49208. ArcRotateCamera.prototype._getViewMatrix = function () {
  49209. // Compute
  49210. var cosa = Math.cos(this.alpha);
  49211. var sina = Math.sin(this.alpha);
  49212. var cosb = Math.cos(this.beta);
  49213. var sinb = Math.sin(this.beta);
  49214. if (sinb === 0) {
  49215. sinb = 0.0001;
  49216. }
  49217. var target = this._getTargetPosition();
  49218. this._computationVector.copyFromFloats(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb);
  49219. target.addToRef(this._computationVector, this._newPosition);
  49220. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  49221. if (!this._collider) {
  49222. this._collider = new BABYLON.Collider();
  49223. }
  49224. this._collider._radius = this.collisionRadius;
  49225. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  49226. this._collisionTriggered = true;
  49227. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  49228. }
  49229. else {
  49230. this.position.copyFrom(this._newPosition);
  49231. var up = this.upVector;
  49232. if (this.allowUpsideDown && sinb < 0) {
  49233. up = up.clone();
  49234. up = up.negate();
  49235. }
  49236. this._computeViewMatrix(this.position, target, up);
  49237. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  49238. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  49239. }
  49240. this._currentTarget = target;
  49241. return this._viewMatrix;
  49242. };
  49243. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  49244. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  49245. meshes = meshes || this.getScene().meshes;
  49246. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  49247. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  49248. this.radius = distance * this.zoomOnFactor;
  49249. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  49250. };
  49251. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  49252. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  49253. var meshesOrMinMaxVector;
  49254. var distance;
  49255. if (meshesOrMinMaxVectorAndDistance.min === undefined) { // meshes
  49256. var meshes = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  49257. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshes);
  49258. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  49259. }
  49260. else { //minMaxVector and distance
  49261. var minMaxVectorAndDistance = meshesOrMinMaxVectorAndDistance;
  49262. meshesOrMinMaxVector = minMaxVectorAndDistance;
  49263. distance = minMaxVectorAndDistance.distance;
  49264. }
  49265. this._target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  49266. if (!doNotUpdateMaxZ) {
  49267. this.maxZ = distance * 2;
  49268. }
  49269. };
  49270. /**
  49271. * @override
  49272. * Override Camera.createRigCamera
  49273. */
  49274. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  49275. var alphaShift = 0;
  49276. switch (this.cameraRigMode) {
  49277. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  49278. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  49279. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  49280. case BABYLON.Camera.RIG_MODE_VR:
  49281. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  49282. break;
  49283. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  49284. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? -1 : 1);
  49285. break;
  49286. }
  49287. var rigCam = new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this._target, this.getScene());
  49288. rigCam._cameraRigParams = {};
  49289. return rigCam;
  49290. };
  49291. /**
  49292. * @override
  49293. * Override Camera._updateRigCameras
  49294. */
  49295. ArcRotateCamera.prototype._updateRigCameras = function () {
  49296. var camLeft = this._rigCameras[0];
  49297. var camRight = this._rigCameras[1];
  49298. camLeft.beta = camRight.beta = this.beta;
  49299. camLeft.radius = camRight.radius = this.radius;
  49300. switch (this.cameraRigMode) {
  49301. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  49302. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  49303. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  49304. case BABYLON.Camera.RIG_MODE_VR:
  49305. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  49306. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  49307. break;
  49308. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  49309. camLeft.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  49310. camRight.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  49311. break;
  49312. }
  49313. _super.prototype._updateRigCameras.call(this);
  49314. };
  49315. ArcRotateCamera.prototype.dispose = function () {
  49316. this.inputs.clear();
  49317. _super.prototype.dispose.call(this);
  49318. };
  49319. ArcRotateCamera.prototype.getClassName = function () {
  49320. return "ArcRotateCamera";
  49321. };
  49322. __decorate([
  49323. BABYLON.serialize()
  49324. ], ArcRotateCamera.prototype, "alpha", void 0);
  49325. __decorate([
  49326. BABYLON.serialize()
  49327. ], ArcRotateCamera.prototype, "beta", void 0);
  49328. __decorate([
  49329. BABYLON.serialize()
  49330. ], ArcRotateCamera.prototype, "radius", void 0);
  49331. __decorate([
  49332. BABYLON.serializeAsVector3("target")
  49333. ], ArcRotateCamera.prototype, "_target", void 0);
  49334. __decorate([
  49335. BABYLON.serialize()
  49336. ], ArcRotateCamera.prototype, "inertialAlphaOffset", void 0);
  49337. __decorate([
  49338. BABYLON.serialize()
  49339. ], ArcRotateCamera.prototype, "inertialBetaOffset", void 0);
  49340. __decorate([
  49341. BABYLON.serialize()
  49342. ], ArcRotateCamera.prototype, "inertialRadiusOffset", void 0);
  49343. __decorate([
  49344. BABYLON.serialize()
  49345. ], ArcRotateCamera.prototype, "lowerAlphaLimit", void 0);
  49346. __decorate([
  49347. BABYLON.serialize()
  49348. ], ArcRotateCamera.prototype, "upperAlphaLimit", void 0);
  49349. __decorate([
  49350. BABYLON.serialize()
  49351. ], ArcRotateCamera.prototype, "lowerBetaLimit", void 0);
  49352. __decorate([
  49353. BABYLON.serialize()
  49354. ], ArcRotateCamera.prototype, "upperBetaLimit", void 0);
  49355. __decorate([
  49356. BABYLON.serialize()
  49357. ], ArcRotateCamera.prototype, "lowerRadiusLimit", void 0);
  49358. __decorate([
  49359. BABYLON.serialize()
  49360. ], ArcRotateCamera.prototype, "upperRadiusLimit", void 0);
  49361. __decorate([
  49362. BABYLON.serialize()
  49363. ], ArcRotateCamera.prototype, "inertialPanningX", void 0);
  49364. __decorate([
  49365. BABYLON.serialize()
  49366. ], ArcRotateCamera.prototype, "inertialPanningY", void 0);
  49367. __decorate([
  49368. BABYLON.serialize()
  49369. ], ArcRotateCamera.prototype, "pinchToPanMaxDistance", void 0);
  49370. __decorate([
  49371. BABYLON.serialize()
  49372. ], ArcRotateCamera.prototype, "panningDistanceLimit", void 0);
  49373. __decorate([
  49374. BABYLON.serializeAsVector3()
  49375. ], ArcRotateCamera.prototype, "panningOriginTarget", void 0);
  49376. __decorate([
  49377. BABYLON.serialize()
  49378. ], ArcRotateCamera.prototype, "panningInertia", void 0);
  49379. __decorate([
  49380. BABYLON.serialize()
  49381. ], ArcRotateCamera.prototype, "zoomOnFactor", void 0);
  49382. __decorate([
  49383. BABYLON.serialize()
  49384. ], ArcRotateCamera.prototype, "allowUpsideDown", void 0);
  49385. return ArcRotateCamera;
  49386. }(BABYLON.TargetCamera));
  49387. BABYLON.ArcRotateCamera = ArcRotateCamera;
  49388. })(BABYLON || (BABYLON = {}));
  49389. //# sourceMappingURL=babylon.arcRotateCamera.js.map
  49390. var BABYLON;
  49391. (function (BABYLON) {
  49392. /**
  49393. * The HemisphericLight simulates the ambient environment light,
  49394. * so the passed direction is the light reflection direction, not the incoming direction.
  49395. */
  49396. var HemisphericLight = /** @class */ (function (_super) {
  49397. __extends(HemisphericLight, _super);
  49398. /**
  49399. * Creates a HemisphericLight object in the scene according to the passed direction (Vector3).
  49400. * The HemisphericLight simulates the ambient environment light, so the passed direction is the light reflection direction, not the incoming direction.
  49401. * The HemisphericLight can't cast shadows.
  49402. * Documentation : http://doc.babylonjs.com/tutorials/lights
  49403. * @param name The friendly name of the light
  49404. * @param direction The direction of the light reflection
  49405. * @param scene The scene the light belongs to
  49406. */
  49407. function HemisphericLight(name, direction, scene) {
  49408. var _this = _super.call(this, name, scene) || this;
  49409. /**
  49410. * The groundColor is the light in the opposite direction to the one specified during creation.
  49411. * 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.
  49412. */
  49413. _this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  49414. _this.direction = direction || BABYLON.Vector3.Up();
  49415. return _this;
  49416. }
  49417. HemisphericLight.prototype._buildUniformLayout = function () {
  49418. this._uniformBuffer.addUniform("vLightData", 4);
  49419. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  49420. this._uniformBuffer.addUniform("vLightSpecular", 3);
  49421. this._uniformBuffer.addUniform("vLightGround", 3);
  49422. this._uniformBuffer.addUniform("shadowsInfo", 3);
  49423. this._uniformBuffer.addUniform("depthValues", 2);
  49424. this._uniformBuffer.create();
  49425. };
  49426. /**
  49427. * Returns the string "HemisphericLight".
  49428. * @return The class name
  49429. */
  49430. HemisphericLight.prototype.getClassName = function () {
  49431. return "HemisphericLight";
  49432. };
  49433. /**
  49434. * Sets the HemisphericLight direction towards the passed target (Vector3).
  49435. * Returns the updated direction.
  49436. * @param target The target the direction should point to
  49437. * @return The computed direction
  49438. */
  49439. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  49440. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  49441. return this.direction;
  49442. };
  49443. /**
  49444. * Returns the shadow generator associated to the light.
  49445. * @returns Always null for hemispheric lights because it does not support shadows.
  49446. */
  49447. HemisphericLight.prototype.getShadowGenerator = function () {
  49448. return null;
  49449. };
  49450. /**
  49451. * Sets the passed Effect object with the HemisphericLight normalized direction and color and the passed name (string).
  49452. * @param effect The effect to update
  49453. * @param lightIndex The index of the light in the effect to update
  49454. * @returns The hemispheric light
  49455. */
  49456. HemisphericLight.prototype.transferToEffect = function (effect, lightIndex) {
  49457. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  49458. this._uniformBuffer.updateFloat4("vLightData", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0.0, lightIndex);
  49459. this._uniformBuffer.updateColor3("vLightGround", this.groundColor.scale(this.intensity), lightIndex);
  49460. return this;
  49461. };
  49462. /**
  49463. * @hidden internal use only.
  49464. */
  49465. HemisphericLight.prototype._getWorldMatrix = function () {
  49466. if (!this._worldMatrix) {
  49467. this._worldMatrix = BABYLON.Matrix.Identity();
  49468. }
  49469. return this._worldMatrix;
  49470. };
  49471. /**
  49472. * Returns the integer 3.
  49473. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  49474. */
  49475. HemisphericLight.prototype.getTypeID = function () {
  49476. return BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT;
  49477. };
  49478. __decorate([
  49479. BABYLON.serializeAsColor3()
  49480. ], HemisphericLight.prototype, "groundColor", void 0);
  49481. __decorate([
  49482. BABYLON.serializeAsVector3()
  49483. ], HemisphericLight.prototype, "direction", void 0);
  49484. return HemisphericLight;
  49485. }(BABYLON.Light));
  49486. BABYLON.HemisphericLight = HemisphericLight;
  49487. })(BABYLON || (BABYLON = {}));
  49488. //# sourceMappingURL=babylon.hemisphericLight.js.map
  49489. var BABYLON;
  49490. (function (BABYLON) {
  49491. /**
  49492. * Base implementation IShadowLight
  49493. * It groups all the common behaviour in order to reduce dupplication and better follow the DRY pattern.
  49494. */
  49495. var ShadowLight = /** @class */ (function (_super) {
  49496. __extends(ShadowLight, _super);
  49497. function ShadowLight() {
  49498. var _this = _super !== null && _super.apply(this, arguments) || this;
  49499. _this._needProjectionMatrixCompute = true;
  49500. return _this;
  49501. }
  49502. ShadowLight.prototype._setPosition = function (value) {
  49503. this._position = value;
  49504. };
  49505. Object.defineProperty(ShadowLight.prototype, "position", {
  49506. /**
  49507. * Sets the position the shadow will be casted from. Also use as the light position for both
  49508. * point and spot lights.
  49509. */
  49510. get: function () {
  49511. return this._position;
  49512. },
  49513. /**
  49514. * Sets the position the shadow will be casted from. Also use as the light position for both
  49515. * point and spot lights.
  49516. */
  49517. set: function (value) {
  49518. this._setPosition(value);
  49519. },
  49520. enumerable: true,
  49521. configurable: true
  49522. });
  49523. ShadowLight.prototype._setDirection = function (value) {
  49524. this._direction = value;
  49525. };
  49526. Object.defineProperty(ShadowLight.prototype, "direction", {
  49527. /**
  49528. * In 2d mode (needCube being false), gets the direction used to cast the shadow.
  49529. * Also use as the light direction on spot and directional lights.
  49530. */
  49531. get: function () {
  49532. return this._direction;
  49533. },
  49534. /**
  49535. * In 2d mode (needCube being false), sets the direction used to cast the shadow.
  49536. * Also use as the light direction on spot and directional lights.
  49537. */
  49538. set: function (value) {
  49539. this._setDirection(value);
  49540. },
  49541. enumerable: true,
  49542. configurable: true
  49543. });
  49544. Object.defineProperty(ShadowLight.prototype, "shadowMinZ", {
  49545. /**
  49546. * Gets the shadow projection clipping minimum z value.
  49547. */
  49548. get: function () {
  49549. return this._shadowMinZ;
  49550. },
  49551. /**
  49552. * Sets the shadow projection clipping minimum z value.
  49553. */
  49554. set: function (value) {
  49555. this._shadowMinZ = value;
  49556. this.forceProjectionMatrixCompute();
  49557. },
  49558. enumerable: true,
  49559. configurable: true
  49560. });
  49561. Object.defineProperty(ShadowLight.prototype, "shadowMaxZ", {
  49562. /**
  49563. * Sets the shadow projection clipping maximum z value.
  49564. */
  49565. get: function () {
  49566. return this._shadowMaxZ;
  49567. },
  49568. /**
  49569. * Gets the shadow projection clipping maximum z value.
  49570. */
  49571. set: function (value) {
  49572. this._shadowMaxZ = value;
  49573. this.forceProjectionMatrixCompute();
  49574. },
  49575. enumerable: true,
  49576. configurable: true
  49577. });
  49578. /**
  49579. * Computes the transformed information (transformedPosition and transformedDirection in World space) of the current light
  49580. * @returns true if the information has been computed, false if it does not need to (no parenting)
  49581. */
  49582. ShadowLight.prototype.computeTransformedInformation = function () {
  49583. if (this.parent && this.parent.getWorldMatrix) {
  49584. if (!this.transformedPosition) {
  49585. this.transformedPosition = BABYLON.Vector3.Zero();
  49586. }
  49587. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  49588. // In case the direction is present.
  49589. if (this.direction) {
  49590. if (!this.transformedDirection) {
  49591. this.transformedDirection = BABYLON.Vector3.Zero();
  49592. }
  49593. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this.transformedDirection);
  49594. }
  49595. return true;
  49596. }
  49597. return false;
  49598. };
  49599. /**
  49600. * Return the depth scale used for the shadow map.
  49601. * @returns the depth scale.
  49602. */
  49603. ShadowLight.prototype.getDepthScale = function () {
  49604. return 50.0;
  49605. };
  49606. /**
  49607. * Get the direction to use to render the shadow map. In case of cube texture, the face index can be passed.
  49608. * @param faceIndex The index of the face we are computed the direction to generate shadow
  49609. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  49610. */
  49611. ShadowLight.prototype.getShadowDirection = function (faceIndex) {
  49612. return this.transformedDirection ? this.transformedDirection : this.direction;
  49613. };
  49614. /**
  49615. * Returns the ShadowLight absolute position in the World.
  49616. * @returns the position vector in world space
  49617. */
  49618. ShadowLight.prototype.getAbsolutePosition = function () {
  49619. return this.transformedPosition ? this.transformedPosition : this.position;
  49620. };
  49621. /**
  49622. * Sets the ShadowLight direction toward the passed target.
  49623. * @param target The point tot target in local space
  49624. * @returns the updated ShadowLight direction
  49625. */
  49626. ShadowLight.prototype.setDirectionToTarget = function (target) {
  49627. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  49628. return this.direction;
  49629. };
  49630. /**
  49631. * Returns the light rotation in euler definition.
  49632. * @returns the x y z rotation in local space.
  49633. */
  49634. ShadowLight.prototype.getRotation = function () {
  49635. this.direction.normalize();
  49636. var xaxis = BABYLON.Vector3.Cross(this.direction, BABYLON.Axis.Y);
  49637. var yaxis = BABYLON.Vector3.Cross(xaxis, this.direction);
  49638. return BABYLON.Vector3.RotationFromAxis(xaxis, yaxis, this.direction);
  49639. };
  49640. /**
  49641. * Returns whether or not the shadow generation require a cube texture or a 2d texture.
  49642. * @returns true if a cube texture needs to be use
  49643. */
  49644. ShadowLight.prototype.needCube = function () {
  49645. return false;
  49646. };
  49647. /**
  49648. * Detects if the projection matrix requires to be recomputed this frame.
  49649. * @returns true if it requires to be recomputed otherwise, false.
  49650. */
  49651. ShadowLight.prototype.needProjectionMatrixCompute = function () {
  49652. return this._needProjectionMatrixCompute;
  49653. };
  49654. /**
  49655. * Forces the shadow generator to recompute the projection matrix even if position and direction did not changed.
  49656. */
  49657. ShadowLight.prototype.forceProjectionMatrixCompute = function () {
  49658. this._needProjectionMatrixCompute = true;
  49659. };
  49660. /**
  49661. * Get the world matrix of the sahdow lights.
  49662. * @hidden Internal Use Only
  49663. */
  49664. ShadowLight.prototype._getWorldMatrix = function () {
  49665. if (!this._worldMatrix) {
  49666. this._worldMatrix = BABYLON.Matrix.Identity();
  49667. }
  49668. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  49669. return this._worldMatrix;
  49670. };
  49671. /**
  49672. * Gets the minZ used for shadow according to both the scene and the light.
  49673. * @param activeCamera The camera we are returning the min for
  49674. * @returns the depth min z
  49675. */
  49676. ShadowLight.prototype.getDepthMinZ = function (activeCamera) {
  49677. return this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ;
  49678. };
  49679. /**
  49680. * Gets the maxZ used for shadow according to both the scene and the light.
  49681. * @param activeCamera The camera we are returning the max for
  49682. * @returns the depth max z
  49683. */
  49684. ShadowLight.prototype.getDepthMaxZ = function (activeCamera) {
  49685. return this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ;
  49686. };
  49687. /**
  49688. * Sets the shadow projection matrix in parameter to the generated projection matrix.
  49689. * @param matrix The materix to updated with the projection information
  49690. * @param viewMatrix The transform matrix of the light
  49691. * @param renderList The list of mesh to render in the map
  49692. * @returns The current light
  49693. */
  49694. ShadowLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  49695. if (this.customProjectionMatrixBuilder) {
  49696. this.customProjectionMatrixBuilder(viewMatrix, renderList, matrix);
  49697. }
  49698. else {
  49699. this._setDefaultShadowProjectionMatrix(matrix, viewMatrix, renderList);
  49700. }
  49701. return this;
  49702. };
  49703. __decorate([
  49704. BABYLON.serializeAsVector3()
  49705. ], ShadowLight.prototype, "position", null);
  49706. __decorate([
  49707. BABYLON.serializeAsVector3()
  49708. ], ShadowLight.prototype, "direction", null);
  49709. __decorate([
  49710. BABYLON.serialize()
  49711. ], ShadowLight.prototype, "shadowMinZ", null);
  49712. __decorate([
  49713. BABYLON.serialize()
  49714. ], ShadowLight.prototype, "shadowMaxZ", null);
  49715. return ShadowLight;
  49716. }(BABYLON.Light));
  49717. BABYLON.ShadowLight = ShadowLight;
  49718. })(BABYLON || (BABYLON = {}));
  49719. //# sourceMappingURL=babylon.shadowLight.js.map
  49720. var BABYLON;
  49721. (function (BABYLON) {
  49722. /**
  49723. * A point light is a light defined by an unique point in world space.
  49724. * The light is emitted in every direction from this point.
  49725. * A good example of a point light is a standard light bulb.
  49726. * Documentation: https://doc.babylonjs.com/babylon101/lights
  49727. */
  49728. var PointLight = /** @class */ (function (_super) {
  49729. __extends(PointLight, _super);
  49730. /**
  49731. * Creates a PointLight object from the passed name and position (Vector3) and adds it in the scene.
  49732. * A PointLight emits the light in every direction.
  49733. * It can cast shadows.
  49734. * If the scene camera is already defined and you want to set your PointLight at the camera position, just set it :
  49735. * ```javascript
  49736. * var pointLight = new BABYLON.PointLight("pl", camera.position, scene);
  49737. * ```
  49738. * Documentation : http://doc.babylonjs.com/tutorials/lights
  49739. * @param name The light friendly name
  49740. * @param position The position of the point light in the scene
  49741. * @param scene The scene the lights belongs to
  49742. */
  49743. function PointLight(name, position, scene) {
  49744. var _this = _super.call(this, name, scene) || this;
  49745. _this._shadowAngle = Math.PI / 2;
  49746. _this.position = position;
  49747. return _this;
  49748. }
  49749. Object.defineProperty(PointLight.prototype, "shadowAngle", {
  49750. /**
  49751. * Getter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  49752. * This specifies what angle the shadow will use to be created.
  49753. *
  49754. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  49755. */
  49756. get: function () {
  49757. return this._shadowAngle;
  49758. },
  49759. /**
  49760. * Setter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  49761. * This specifies what angle the shadow will use to be created.
  49762. *
  49763. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  49764. */
  49765. set: function (value) {
  49766. this._shadowAngle = value;
  49767. this.forceProjectionMatrixCompute();
  49768. },
  49769. enumerable: true,
  49770. configurable: true
  49771. });
  49772. Object.defineProperty(PointLight.prototype, "direction", {
  49773. /**
  49774. * Gets the direction if it has been set.
  49775. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  49776. */
  49777. get: function () {
  49778. return this._direction;
  49779. },
  49780. /**
  49781. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  49782. */
  49783. set: function (value) {
  49784. var previousNeedCube = this.needCube();
  49785. this._direction = value;
  49786. if (this.needCube() !== previousNeedCube && this._shadowGenerator) {
  49787. this._shadowGenerator.recreateShadowMap();
  49788. }
  49789. },
  49790. enumerable: true,
  49791. configurable: true
  49792. });
  49793. /**
  49794. * Returns the string "PointLight"
  49795. * @returns the class name
  49796. */
  49797. PointLight.prototype.getClassName = function () {
  49798. return "PointLight";
  49799. };
  49800. /**
  49801. * Returns the integer 0.
  49802. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  49803. */
  49804. PointLight.prototype.getTypeID = function () {
  49805. return BABYLON.Light.LIGHTTYPEID_POINTLIGHT;
  49806. };
  49807. /**
  49808. * Specifies wether or not the shadowmap should be a cube texture.
  49809. * @returns true if the shadowmap needs to be a cube texture.
  49810. */
  49811. PointLight.prototype.needCube = function () {
  49812. return !this.direction;
  49813. };
  49814. /**
  49815. * Returns a new Vector3 aligned with the PointLight cube system according to the passed cube face index (integer).
  49816. * @param faceIndex The index of the face we are computed the direction to generate shadow
  49817. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  49818. */
  49819. PointLight.prototype.getShadowDirection = function (faceIndex) {
  49820. if (this.direction) {
  49821. return _super.prototype.getShadowDirection.call(this, faceIndex);
  49822. }
  49823. else {
  49824. switch (faceIndex) {
  49825. case 0:
  49826. return new BABYLON.Vector3(1.0, 0.0, 0.0);
  49827. case 1:
  49828. return new BABYLON.Vector3(-1.0, 0.0, 0.0);
  49829. case 2:
  49830. return new BABYLON.Vector3(0.0, -1.0, 0.0);
  49831. case 3:
  49832. return new BABYLON.Vector3(0.0, 1.0, 0.0);
  49833. case 4:
  49834. return new BABYLON.Vector3(0.0, 0.0, 1.0);
  49835. case 5:
  49836. return new BABYLON.Vector3(0.0, 0.0, -1.0);
  49837. }
  49838. }
  49839. return BABYLON.Vector3.Zero();
  49840. };
  49841. /**
  49842. * Sets the passed matrix "matrix" as a left-handed perspective projection matrix with the following settings :
  49843. * - fov = PI / 2
  49844. * - aspect ratio : 1.0
  49845. * - z-near and far equal to the active camera minZ and maxZ.
  49846. * Returns the PointLight.
  49847. */
  49848. PointLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  49849. var activeCamera = this.getScene().activeCamera;
  49850. if (!activeCamera) {
  49851. return;
  49852. }
  49853. BABYLON.Matrix.PerspectiveFovLHToRef(this.shadowAngle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  49854. };
  49855. PointLight.prototype._buildUniformLayout = function () {
  49856. this._uniformBuffer.addUniform("vLightData", 4);
  49857. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  49858. this._uniformBuffer.addUniform("vLightSpecular", 3);
  49859. this._uniformBuffer.addUniform("shadowsInfo", 3);
  49860. this._uniformBuffer.addUniform("depthValues", 2);
  49861. this._uniformBuffer.create();
  49862. };
  49863. /**
  49864. * Sets the passed Effect "effect" with the PointLight transformed position (or position, if none) and passed name (string).
  49865. * @param effect The effect to update
  49866. * @param lightIndex The index of the light in the effect to update
  49867. * @returns The point light
  49868. */
  49869. PointLight.prototype.transferToEffect = function (effect, lightIndex) {
  49870. if (this.computeTransformedInformation()) {
  49871. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0.0, lightIndex);
  49872. return this;
  49873. }
  49874. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, 0, lightIndex);
  49875. return this;
  49876. };
  49877. __decorate([
  49878. BABYLON.serialize()
  49879. ], PointLight.prototype, "shadowAngle", null);
  49880. return PointLight;
  49881. }(BABYLON.ShadowLight));
  49882. BABYLON.PointLight = PointLight;
  49883. })(BABYLON || (BABYLON = {}));
  49884. //# sourceMappingURL=babylon.pointLight.js.map
  49885. var BABYLON;
  49886. (function (BABYLON) {
  49887. /**
  49888. * A directional light is defined by a direction (what a surprise!).
  49889. * The light is emitted from everywhere in the specified direction, and has an infinite range.
  49890. * 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.
  49891. * Documentation: https://doc.babylonjs.com/babylon101/lights
  49892. */
  49893. var DirectionalLight = /** @class */ (function (_super) {
  49894. __extends(DirectionalLight, _super);
  49895. /**
  49896. * Creates a DirectionalLight object in the scene, oriented towards the passed direction (Vector3).
  49897. * The directional light is emitted from everywhere in the given direction.
  49898. * It can cast shawdows.
  49899. * Documentation : http://doc.babylonjs.com/tutorials/lights
  49900. * @param name The friendly name of the light
  49901. * @param direction The direction of the light
  49902. * @param scene The scene the light belongs to
  49903. */
  49904. function DirectionalLight(name, direction, scene) {
  49905. var _this = _super.call(this, name, scene) || this;
  49906. _this._shadowFrustumSize = 0;
  49907. _this._shadowOrthoScale = 0.1;
  49908. /**
  49909. * Automatically compute the projection matrix to best fit (including all the casters)
  49910. * on each frame.
  49911. */
  49912. _this.autoUpdateExtends = true;
  49913. // Cache
  49914. _this._orthoLeft = Number.MAX_VALUE;
  49915. _this._orthoRight = Number.MIN_VALUE;
  49916. _this._orthoTop = Number.MIN_VALUE;
  49917. _this._orthoBottom = Number.MAX_VALUE;
  49918. _this.position = direction.scale(-1.0);
  49919. _this.direction = direction;
  49920. return _this;
  49921. }
  49922. Object.defineProperty(DirectionalLight.prototype, "shadowFrustumSize", {
  49923. /**
  49924. * Fix frustum size for the shadow generation. This is disabled if the value is 0.
  49925. */
  49926. get: function () {
  49927. return this._shadowFrustumSize;
  49928. },
  49929. /**
  49930. * Specifies a fix frustum size for the shadow generation.
  49931. */
  49932. set: function (value) {
  49933. this._shadowFrustumSize = value;
  49934. this.forceProjectionMatrixCompute();
  49935. },
  49936. enumerable: true,
  49937. configurable: true
  49938. });
  49939. Object.defineProperty(DirectionalLight.prototype, "shadowOrthoScale", {
  49940. /**
  49941. * Gets the shadow projection scale against the optimal computed one.
  49942. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  49943. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  49944. */
  49945. get: function () {
  49946. return this._shadowOrthoScale;
  49947. },
  49948. /**
  49949. * Sets the shadow projection scale against the optimal computed one.
  49950. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  49951. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  49952. */
  49953. set: function (value) {
  49954. this._shadowOrthoScale = value;
  49955. this.forceProjectionMatrixCompute();
  49956. },
  49957. enumerable: true,
  49958. configurable: true
  49959. });
  49960. /**
  49961. * Returns the string "DirectionalLight".
  49962. * @return The class name
  49963. */
  49964. DirectionalLight.prototype.getClassName = function () {
  49965. return "DirectionalLight";
  49966. };
  49967. /**
  49968. * Returns the integer 1.
  49969. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  49970. */
  49971. DirectionalLight.prototype.getTypeID = function () {
  49972. return BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT;
  49973. };
  49974. /**
  49975. * Sets the passed matrix "matrix" as projection matrix for the shadows cast by the light according to the passed view matrix.
  49976. * Returns the DirectionalLight Shadow projection matrix.
  49977. */
  49978. DirectionalLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  49979. if (this.shadowFrustumSize > 0) {
  49980. this._setDefaultFixedFrustumShadowProjectionMatrix(matrix, viewMatrix);
  49981. }
  49982. else {
  49983. this._setDefaultAutoExtendShadowProjectionMatrix(matrix, viewMatrix, renderList);
  49984. }
  49985. };
  49986. /**
  49987. * Sets the passed matrix "matrix" as fixed frustum projection matrix for the shadows cast by the light according to the passed view matrix.
  49988. * Returns the DirectionalLight Shadow projection matrix.
  49989. */
  49990. DirectionalLight.prototype._setDefaultFixedFrustumShadowProjectionMatrix = function (matrix, viewMatrix) {
  49991. var activeCamera = this.getScene().activeCamera;
  49992. if (!activeCamera) {
  49993. return;
  49994. }
  49995. BABYLON.Matrix.OrthoLHToRef(this.shadowFrustumSize, this.shadowFrustumSize, this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ, this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ, matrix);
  49996. };
  49997. /**
  49998. * Sets the passed matrix "matrix" as auto extend projection matrix for the shadows cast by the light according to the passed view matrix.
  49999. * Returns the DirectionalLight Shadow projection matrix.
  50000. */
  50001. DirectionalLight.prototype._setDefaultAutoExtendShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  50002. var activeCamera = this.getScene().activeCamera;
  50003. if (!activeCamera) {
  50004. return;
  50005. }
  50006. // Check extends
  50007. if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
  50008. var tempVector3 = BABYLON.Vector3.Zero();
  50009. this._orthoLeft = Number.MAX_VALUE;
  50010. this._orthoRight = Number.MIN_VALUE;
  50011. this._orthoTop = Number.MIN_VALUE;
  50012. this._orthoBottom = Number.MAX_VALUE;
  50013. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  50014. var mesh = renderList[meshIndex];
  50015. if (!mesh) {
  50016. continue;
  50017. }
  50018. var boundingInfo = mesh.getBoundingInfo();
  50019. var boundingBox = boundingInfo.boundingBox;
  50020. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  50021. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  50022. if (tempVector3.x < this._orthoLeft)
  50023. this._orthoLeft = tempVector3.x;
  50024. if (tempVector3.y < this._orthoBottom)
  50025. this._orthoBottom = tempVector3.y;
  50026. if (tempVector3.x > this._orthoRight)
  50027. this._orthoRight = tempVector3.x;
  50028. if (tempVector3.y > this._orthoTop)
  50029. this._orthoTop = tempVector3.y;
  50030. }
  50031. }
  50032. }
  50033. var xOffset = this._orthoRight - this._orthoLeft;
  50034. var yOffset = this._orthoTop - this._orthoBottom;
  50035. 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);
  50036. };
  50037. DirectionalLight.prototype._buildUniformLayout = function () {
  50038. this._uniformBuffer.addUniform("vLightData", 4);
  50039. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  50040. this._uniformBuffer.addUniform("vLightSpecular", 3);
  50041. this._uniformBuffer.addUniform("shadowsInfo", 3);
  50042. this._uniformBuffer.addUniform("depthValues", 2);
  50043. this._uniformBuffer.create();
  50044. };
  50045. /**
  50046. * Sets the passed Effect object with the DirectionalLight transformed position (or position if not parented) and the passed name.
  50047. * @param effect The effect to update
  50048. * @param lightIndex The index of the light in the effect to update
  50049. * @returns The directional light
  50050. */
  50051. DirectionalLight.prototype.transferToEffect = function (effect, lightIndex) {
  50052. if (this.computeTransformedInformation()) {
  50053. this._uniformBuffer.updateFloat4("vLightData", this.transformedDirection.x, this.transformedDirection.y, this.transformedDirection.z, 1, lightIndex);
  50054. return this;
  50055. }
  50056. this._uniformBuffer.updateFloat4("vLightData", this.direction.x, this.direction.y, this.direction.z, 1, lightIndex);
  50057. return this;
  50058. };
  50059. /**
  50060. * Gets the minZ used for shadow according to both the scene and the light.
  50061. *
  50062. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  50063. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  50064. * @param activeCamera The camera we are returning the min for
  50065. * @returns the depth min z
  50066. */
  50067. DirectionalLight.prototype.getDepthMinZ = function (activeCamera) {
  50068. return 1;
  50069. };
  50070. /**
  50071. * Gets the maxZ used for shadow according to both the scene and the light.
  50072. *
  50073. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  50074. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  50075. * @param activeCamera The camera we are returning the max for
  50076. * @returns the depth max z
  50077. */
  50078. DirectionalLight.prototype.getDepthMaxZ = function (activeCamera) {
  50079. return 1;
  50080. };
  50081. __decorate([
  50082. BABYLON.serialize()
  50083. ], DirectionalLight.prototype, "shadowFrustumSize", null);
  50084. __decorate([
  50085. BABYLON.serialize()
  50086. ], DirectionalLight.prototype, "shadowOrthoScale", null);
  50087. __decorate([
  50088. BABYLON.serialize()
  50089. ], DirectionalLight.prototype, "autoUpdateExtends", void 0);
  50090. return DirectionalLight;
  50091. }(BABYLON.ShadowLight));
  50092. BABYLON.DirectionalLight = DirectionalLight;
  50093. })(BABYLON || (BABYLON = {}));
  50094. //# sourceMappingURL=babylon.directionalLight.js.map
  50095. var BABYLON;
  50096. (function (BABYLON) {
  50097. /**
  50098. * A spot light is defined by a position, a direction, an angle, and an exponent.
  50099. * These values define a cone of light starting from the position, emitting toward the direction.
  50100. * The angle, in radians, defines the size (field of illumination) of the spotlight's conical beam,
  50101. * and the exponent defines the speed of the decay of the light with distance (reach).
  50102. * Documentation: https://doc.babylonjs.com/babylon101/lights
  50103. */
  50104. var SpotLight = /** @class */ (function (_super) {
  50105. __extends(SpotLight, _super);
  50106. /**
  50107. * Creates a SpotLight object in the scene. A spot light is a simply light oriented cone.
  50108. * It can cast shadows.
  50109. * Documentation : http://doc.babylonjs.com/tutorials/lights
  50110. * @param name The light friendly name
  50111. * @param position The position of the spot light in the scene
  50112. * @param direction The direction of the light in the scene
  50113. * @param angle The cone angle of the light in Radians
  50114. * @param exponent The light decay speed with the distance from the emission spot
  50115. * @param scene The scene the lights belongs to
  50116. */
  50117. function SpotLight(name, position, direction, angle, exponent, scene) {
  50118. var _this = _super.call(this, name, scene) || this;
  50119. _this._projectionTextureMatrix = BABYLON.Matrix.Zero();
  50120. _this._projectionTextureLightNear = 1e-6;
  50121. _this._projectionTextureLightFar = 1000.0;
  50122. _this._projectionTextureUpDirection = BABYLON.Vector3.Up();
  50123. _this._projectionTextureViewLightDirty = true;
  50124. _this._projectionTextureProjectionLightDirty = true;
  50125. _this._projectionTextureDirty = true;
  50126. _this._projectionTextureViewTargetVector = BABYLON.Vector3.Zero();
  50127. _this._projectionTextureViewLightMatrix = BABYLON.Matrix.Zero();
  50128. _this._projectionTextureProjectionLightMatrix = BABYLON.Matrix.Zero();
  50129. _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);
  50130. _this.position = position;
  50131. _this.direction = direction;
  50132. _this.angle = angle;
  50133. _this.exponent = exponent;
  50134. return _this;
  50135. }
  50136. Object.defineProperty(SpotLight.prototype, "angle", {
  50137. /**
  50138. * Gets the cone angle of the spot light in Radians.
  50139. */
  50140. get: function () {
  50141. return this._angle;
  50142. },
  50143. /**
  50144. * Sets the cone angle of the spot light in Radians.
  50145. */
  50146. set: function (value) {
  50147. this._angle = value;
  50148. this._projectionTextureProjectionLightDirty = true;
  50149. this.forceProjectionMatrixCompute();
  50150. },
  50151. enumerable: true,
  50152. configurable: true
  50153. });
  50154. Object.defineProperty(SpotLight.prototype, "shadowAngleScale", {
  50155. /**
  50156. * Allows scaling the angle of the light for shadow generation only.
  50157. */
  50158. get: function () {
  50159. return this._shadowAngleScale;
  50160. },
  50161. /**
  50162. * Allows scaling the angle of the light for shadow generation only.
  50163. */
  50164. set: function (value) {
  50165. this._shadowAngleScale = value;
  50166. this.forceProjectionMatrixCompute();
  50167. },
  50168. enumerable: true,
  50169. configurable: true
  50170. });
  50171. Object.defineProperty(SpotLight.prototype, "projectionTextureMatrix", {
  50172. /**
  50173. * Allows reading the projecton texture
  50174. */
  50175. get: function () {
  50176. return this._projectionTextureMatrix;
  50177. },
  50178. enumerable: true,
  50179. configurable: true
  50180. });
  50181. Object.defineProperty(SpotLight.prototype, "projectionTextureLightNear", {
  50182. /**
  50183. * Gets the near clip of the Spotlight for texture projection.
  50184. */
  50185. get: function () {
  50186. return this._projectionTextureLightNear;
  50187. },
  50188. /**
  50189. * Sets the near clip of the Spotlight for texture projection.
  50190. */
  50191. set: function (value) {
  50192. this._projectionTextureLightNear = value;
  50193. this._projectionTextureProjectionLightDirty = true;
  50194. },
  50195. enumerable: true,
  50196. configurable: true
  50197. });
  50198. Object.defineProperty(SpotLight.prototype, "projectionTextureLightFar", {
  50199. /**
  50200. * Gets the far clip of the Spotlight for texture projection.
  50201. */
  50202. get: function () {
  50203. return this._projectionTextureLightFar;
  50204. },
  50205. /**
  50206. * Sets the far clip of the Spotlight for texture projection.
  50207. */
  50208. set: function (value) {
  50209. this._projectionTextureLightFar = value;
  50210. this._projectionTextureProjectionLightDirty = true;
  50211. },
  50212. enumerable: true,
  50213. configurable: true
  50214. });
  50215. Object.defineProperty(SpotLight.prototype, "projectionTextureUpDirection", {
  50216. /**
  50217. * Gets the Up vector of the Spotlight for texture projection.
  50218. */
  50219. get: function () {
  50220. return this._projectionTextureUpDirection;
  50221. },
  50222. /**
  50223. * Sets the Up vector of the Spotlight for texture projection.
  50224. */
  50225. set: function (value) {
  50226. this._projectionTextureUpDirection = value;
  50227. this._projectionTextureProjectionLightDirty = true;
  50228. },
  50229. enumerable: true,
  50230. configurable: true
  50231. });
  50232. Object.defineProperty(SpotLight.prototype, "projectionTexture", {
  50233. /**
  50234. * Gets the projection texture of the light.
  50235. */
  50236. get: function () {
  50237. return this._projectionTexture;
  50238. },
  50239. /**
  50240. * Sets the projection texture of the light.
  50241. */
  50242. set: function (value) {
  50243. this._projectionTexture = value;
  50244. this._projectionTextureDirty = true;
  50245. },
  50246. enumerable: true,
  50247. configurable: true
  50248. });
  50249. /**
  50250. * Returns the string "SpotLight".
  50251. * @returns the class name
  50252. */
  50253. SpotLight.prototype.getClassName = function () {
  50254. return "SpotLight";
  50255. };
  50256. /**
  50257. * Returns the integer 2.
  50258. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  50259. */
  50260. SpotLight.prototype.getTypeID = function () {
  50261. return BABYLON.Light.LIGHTTYPEID_SPOTLIGHT;
  50262. };
  50263. /**
  50264. * Overrides the direction setter to recompute the projection texture view light Matrix.
  50265. */
  50266. SpotLight.prototype._setDirection = function (value) {
  50267. _super.prototype._setDirection.call(this, value);
  50268. this._projectionTextureViewLightDirty = true;
  50269. };
  50270. /**
  50271. * Overrides the position setter to recompute the projection texture view light Matrix.
  50272. */
  50273. SpotLight.prototype._setPosition = function (value) {
  50274. _super.prototype._setPosition.call(this, value);
  50275. this._projectionTextureViewLightDirty = true;
  50276. };
  50277. /**
  50278. * 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.
  50279. * Returns the SpotLight.
  50280. */
  50281. SpotLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  50282. var activeCamera = this.getScene().activeCamera;
  50283. if (!activeCamera) {
  50284. return;
  50285. }
  50286. this._shadowAngleScale = this._shadowAngleScale || 1;
  50287. var angle = this._shadowAngleScale * this._angle;
  50288. BABYLON.Matrix.PerspectiveFovLHToRef(angle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  50289. };
  50290. SpotLight.prototype._computeProjectionTextureViewLightMatrix = function () {
  50291. this._projectionTextureViewLightDirty = false;
  50292. this._projectionTextureDirty = true;
  50293. this.position.addToRef(this.direction, this._projectionTextureViewTargetVector);
  50294. BABYLON.Matrix.LookAtLHToRef(this.position, this._projectionTextureViewTargetVector, this._projectionTextureUpDirection, this._projectionTextureViewLightMatrix);
  50295. };
  50296. SpotLight.prototype._computeProjectionTextureProjectionLightMatrix = function () {
  50297. this._projectionTextureProjectionLightDirty = false;
  50298. this._projectionTextureDirty = true;
  50299. var light_far = this.projectionTextureLightFar;
  50300. var light_near = this.projectionTextureLightNear;
  50301. var P = light_far / (light_far - light_near);
  50302. var Q = -P * light_near;
  50303. var S = 1.0 / Math.tan(this._angle / 2.0);
  50304. var A = 1.0;
  50305. 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);
  50306. };
  50307. /**
  50308. * Main function for light texture projection matrix computing.
  50309. */
  50310. SpotLight.prototype._computeProjectionTextureMatrix = function () {
  50311. this._projectionTextureDirty = false;
  50312. this._projectionTextureViewLightMatrix.multiplyToRef(this._projectionTextureProjectionLightMatrix, this._projectionTextureMatrix);
  50313. this._projectionTextureMatrix.multiplyToRef(this._projectionTextureScalingMatrix, this._projectionTextureMatrix);
  50314. };
  50315. SpotLight.prototype._buildUniformLayout = function () {
  50316. this._uniformBuffer.addUniform("vLightData", 4);
  50317. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  50318. this._uniformBuffer.addUniform("vLightSpecular", 3);
  50319. this._uniformBuffer.addUniform("vLightDirection", 3);
  50320. this._uniformBuffer.addUniform("shadowsInfo", 3);
  50321. this._uniformBuffer.addUniform("depthValues", 2);
  50322. this._uniformBuffer.create();
  50323. };
  50324. /**
  50325. * Sets the passed Effect object with the SpotLight transfomed position (or position if not parented) and normalized direction.
  50326. * @param effect The effect to update
  50327. * @param lightIndex The index of the light in the effect to update
  50328. * @returns The spot light
  50329. */
  50330. SpotLight.prototype.transferToEffect = function (effect, lightIndex) {
  50331. var normalizeDirection;
  50332. if (this.computeTransformedInformation()) {
  50333. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent, lightIndex);
  50334. normalizeDirection = BABYLON.Vector3.Normalize(this.transformedDirection);
  50335. }
  50336. else {
  50337. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, this.exponent, lightIndex);
  50338. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  50339. }
  50340. this._uniformBuffer.updateFloat4("vLightDirection", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5), lightIndex);
  50341. if (this.projectionTexture && this.projectionTexture.isReady()) {
  50342. if (this._projectionTextureViewLightDirty) {
  50343. this._computeProjectionTextureViewLightMatrix();
  50344. }
  50345. if (this._projectionTextureProjectionLightDirty) {
  50346. this._computeProjectionTextureProjectionLightMatrix();
  50347. }
  50348. if (this._projectionTextureDirty) {
  50349. this._computeProjectionTextureMatrix();
  50350. }
  50351. effect.setMatrix("textureProjectionMatrix" + lightIndex, this._projectionTextureMatrix);
  50352. effect.setTexture("projectionLightSampler" + lightIndex, this.projectionTexture);
  50353. }
  50354. return this;
  50355. };
  50356. /**
  50357. * Disposes the light and the associated resources.
  50358. */
  50359. SpotLight.prototype.dispose = function () {
  50360. _super.prototype.dispose.call(this);
  50361. if (this._projectionTexture) {
  50362. this._projectionTexture.dispose();
  50363. }
  50364. };
  50365. __decorate([
  50366. BABYLON.serialize()
  50367. ], SpotLight.prototype, "angle", null);
  50368. __decorate([
  50369. BABYLON.serialize()
  50370. ], SpotLight.prototype, "shadowAngleScale", null);
  50371. __decorate([
  50372. BABYLON.serialize()
  50373. ], SpotLight.prototype, "exponent", void 0);
  50374. __decorate([
  50375. BABYLON.serialize()
  50376. ], SpotLight.prototype, "projectionTextureLightNear", null);
  50377. __decorate([
  50378. BABYLON.serialize()
  50379. ], SpotLight.prototype, "projectionTextureLightFar", null);
  50380. __decorate([
  50381. BABYLON.serialize()
  50382. ], SpotLight.prototype, "projectionTextureUpDirection", null);
  50383. __decorate([
  50384. BABYLON.serializeAsTexture("projectedLightTexture")
  50385. ], SpotLight.prototype, "_projectionTexture", void 0);
  50386. return SpotLight;
  50387. }(BABYLON.ShadowLight));
  50388. BABYLON.SpotLight = SpotLight;
  50389. })(BABYLON || (BABYLON = {}));
  50390. //# sourceMappingURL=babylon.spotLight.js.map
  50391. var BABYLON;
  50392. (function (BABYLON) {
  50393. /**
  50394. * Class used to override all child animations of a given target
  50395. */
  50396. var AnimationPropertiesOverride = /** @class */ (function () {
  50397. function AnimationPropertiesOverride() {
  50398. /**
  50399. * Gets or sets a value indicating if animation blending must be used
  50400. */
  50401. this.enableBlending = false;
  50402. /**
  50403. * Gets or sets the blending speed to use when enableBlending is true
  50404. */
  50405. this.blendingSpeed = 0.01;
  50406. /**
  50407. * Gets or sets the default loop mode to use
  50408. */
  50409. this.loopMode = BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE;
  50410. }
  50411. return AnimationPropertiesOverride;
  50412. }());
  50413. BABYLON.AnimationPropertiesOverride = AnimationPropertiesOverride;
  50414. })(BABYLON || (BABYLON = {}));
  50415. //# sourceMappingURL=babylon.animationPropertiesOverride.js.map
  50416. var BABYLON;
  50417. (function (BABYLON) {
  50418. /**
  50419. * Represents the range of an animation
  50420. */
  50421. var AnimationRange = /** @class */ (function () {
  50422. /**
  50423. * Initializes the range of an animation
  50424. * @param name The name of the animation range
  50425. * @param from The starting frame of the animation
  50426. * @param to The ending frame of the animation
  50427. */
  50428. function AnimationRange(
  50429. /**The name of the animation range**/
  50430. name,
  50431. /**The starting frame of the animation */
  50432. from,
  50433. /**The ending frame of the animation*/
  50434. to) {
  50435. this.name = name;
  50436. this.from = from;
  50437. this.to = to;
  50438. }
  50439. /**
  50440. * Makes a copy of the animation range
  50441. * @returns A copy of the animation range
  50442. */
  50443. AnimationRange.prototype.clone = function () {
  50444. return new AnimationRange(this.name, this.from, this.to);
  50445. };
  50446. return AnimationRange;
  50447. }());
  50448. BABYLON.AnimationRange = AnimationRange;
  50449. /**
  50450. * Composed of a frame, and an action function
  50451. */
  50452. var AnimationEvent = /** @class */ (function () {
  50453. /**
  50454. * Initializes the animation event
  50455. * @param frame The frame for which the event is triggered
  50456. * @param action The event to perform when triggered
  50457. * @param onlyOnce Specifies if the event should be triggered only once
  50458. */
  50459. function AnimationEvent(
  50460. /** The frame for which the event is triggered **/
  50461. frame,
  50462. /** The event to perform when triggered **/
  50463. action,
  50464. /** Specifies if the event should be triggered only once**/
  50465. onlyOnce) {
  50466. this.frame = frame;
  50467. this.action = action;
  50468. this.onlyOnce = onlyOnce;
  50469. /**
  50470. * Specifies if the animation event is done
  50471. */
  50472. this.isDone = false;
  50473. }
  50474. /** @hidden */
  50475. AnimationEvent.prototype._clone = function () {
  50476. return new AnimationEvent(this.frame, this.action, this.onlyOnce);
  50477. };
  50478. return AnimationEvent;
  50479. }());
  50480. BABYLON.AnimationEvent = AnimationEvent;
  50481. /**
  50482. * A cursor which tracks a point on a path
  50483. */
  50484. var PathCursor = /** @class */ (function () {
  50485. /**
  50486. * Initializes the path cursor
  50487. * @param path The path to track
  50488. */
  50489. function PathCursor(path) {
  50490. this.path = path;
  50491. /**
  50492. * Stores path cursor callbacks for when an onchange event is triggered
  50493. */
  50494. this._onchange = new Array();
  50495. /**
  50496. * The value of the path cursor
  50497. */
  50498. this.value = 0;
  50499. /**
  50500. * The animation array of the path cursor
  50501. */
  50502. this.animations = new Array();
  50503. }
  50504. /**
  50505. * Gets the cursor point on the path
  50506. * @returns A point on the path cursor at the cursor location
  50507. */
  50508. PathCursor.prototype.getPoint = function () {
  50509. var point = this.path.getPointAtLengthPosition(this.value);
  50510. return new BABYLON.Vector3(point.x, 0, point.y);
  50511. };
  50512. /**
  50513. * Moves the cursor ahead by the step amount
  50514. * @param step The amount to move the cursor forward
  50515. * @returns This path cursor
  50516. */
  50517. PathCursor.prototype.moveAhead = function (step) {
  50518. if (step === void 0) { step = 0.002; }
  50519. this.move(step);
  50520. return this;
  50521. };
  50522. /**
  50523. * Moves the cursor behind by the step amount
  50524. * @param step The amount to move the cursor back
  50525. * @returns This path cursor
  50526. */
  50527. PathCursor.prototype.moveBack = function (step) {
  50528. if (step === void 0) { step = 0.002; }
  50529. this.move(-step);
  50530. return this;
  50531. };
  50532. /**
  50533. * Moves the cursor by the step amount
  50534. * If the step amount is greater than one, an exception is thrown
  50535. * @param step The amount to move the cursor
  50536. * @returns This path cursor
  50537. */
  50538. PathCursor.prototype.move = function (step) {
  50539. if (Math.abs(step) > 1) {
  50540. throw "step size should be less than 1.";
  50541. }
  50542. this.value += step;
  50543. this.ensureLimits();
  50544. this.raiseOnChange();
  50545. return this;
  50546. };
  50547. /**
  50548. * Ensures that the value is limited between zero and one
  50549. * @returns This path cursor
  50550. */
  50551. PathCursor.prototype.ensureLimits = function () {
  50552. while (this.value > 1) {
  50553. this.value -= 1;
  50554. }
  50555. while (this.value < 0) {
  50556. this.value += 1;
  50557. }
  50558. return this;
  50559. };
  50560. /**
  50561. * Runs onchange callbacks on change (used by the animation engine)
  50562. * @returns This path cursor
  50563. */
  50564. PathCursor.prototype.raiseOnChange = function () {
  50565. var _this = this;
  50566. this._onchange.forEach(function (f) { return f(_this); });
  50567. return this;
  50568. };
  50569. /**
  50570. * Executes a function on change
  50571. * @param f A path cursor onchange callback
  50572. * @returns This path cursor
  50573. */
  50574. PathCursor.prototype.onchange = function (f) {
  50575. this._onchange.push(f);
  50576. return this;
  50577. };
  50578. return PathCursor;
  50579. }());
  50580. BABYLON.PathCursor = PathCursor;
  50581. /**
  50582. * Enum for the animation key frame interpolation type
  50583. */
  50584. var AnimationKeyInterpolation;
  50585. (function (AnimationKeyInterpolation) {
  50586. /**
  50587. * Do not interpolate between keys and use the start key value only. Tangents are ignored
  50588. */
  50589. AnimationKeyInterpolation[AnimationKeyInterpolation["STEP"] = 1] = "STEP";
  50590. })(AnimationKeyInterpolation = BABYLON.AnimationKeyInterpolation || (BABYLON.AnimationKeyInterpolation = {}));
  50591. /**
  50592. * Class used to store any kind of animation
  50593. */
  50594. var Animation = /** @class */ (function () {
  50595. /**
  50596. * Initializes the animation
  50597. * @param name Name of the animation
  50598. * @param targetProperty Property to animate
  50599. * @param framePerSecond The frames per second of the animation
  50600. * @param dataType The data type of the animation
  50601. * @param loopMode The loop mode of the animation
  50602. * @param enableBlendings Specifies if blending should be enabled
  50603. */
  50604. function Animation(
  50605. /**Name of the animation */
  50606. name,
  50607. /**Property to animate */
  50608. targetProperty,
  50609. /**The frames per second of the animation */
  50610. framePerSecond,
  50611. /**The data type of the animation */
  50612. dataType,
  50613. /**The loop mode of the animation */
  50614. loopMode,
  50615. /**Specifies if blending should be enabled */
  50616. enableBlending) {
  50617. this.name = name;
  50618. this.targetProperty = targetProperty;
  50619. this.framePerSecond = framePerSecond;
  50620. this.dataType = dataType;
  50621. this.loopMode = loopMode;
  50622. this.enableBlending = enableBlending;
  50623. /**
  50624. * @hidden Internal use only
  50625. */
  50626. this._runtimeAnimations = new Array();
  50627. /**
  50628. * The set of event that will be linked to this animation
  50629. */
  50630. this._events = new Array();
  50631. /**
  50632. * Stores the blending speed of the animation
  50633. */
  50634. this.blendingSpeed = 0.01;
  50635. /**
  50636. * Stores the animation ranges for the animation
  50637. */
  50638. this._ranges = {};
  50639. this.targetPropertyPath = targetProperty.split(".");
  50640. this.dataType = dataType;
  50641. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  50642. }
  50643. /**
  50644. * @hidden Internal use
  50645. */
  50646. Animation._PrepareAnimation = function (name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
  50647. var dataType = undefined;
  50648. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  50649. dataType = Animation.ANIMATIONTYPE_FLOAT;
  50650. }
  50651. else if (from instanceof BABYLON.Quaternion) {
  50652. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  50653. }
  50654. else if (from instanceof BABYLON.Vector3) {
  50655. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  50656. }
  50657. else if (from instanceof BABYLON.Vector2) {
  50658. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  50659. }
  50660. else if (from instanceof BABYLON.Color3) {
  50661. dataType = Animation.ANIMATIONTYPE_COLOR3;
  50662. }
  50663. else if (from instanceof BABYLON.Size) {
  50664. dataType = Animation.ANIMATIONTYPE_SIZE;
  50665. }
  50666. if (dataType == undefined) {
  50667. return null;
  50668. }
  50669. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  50670. var keys = [{ frame: 0, value: from }, { frame: totalFrame, value: to }];
  50671. animation.setKeys(keys);
  50672. if (easingFunction !== undefined) {
  50673. animation.setEasingFunction(easingFunction);
  50674. }
  50675. return animation;
  50676. };
  50677. /**
  50678. * Sets up an animation
  50679. * @param property The property to animate
  50680. * @param animationType The animation type to apply
  50681. * @param framePerSecond The frames per second of the animation
  50682. * @param easingFunction The easing function used in the animation
  50683. * @returns The created animation
  50684. */
  50685. Animation.CreateAnimation = function (property, animationType, framePerSecond, easingFunction) {
  50686. var animation = new Animation(property + "Animation", property, framePerSecond, animationType, Animation.ANIMATIONLOOPMODE_CONSTANT);
  50687. animation.setEasingFunction(easingFunction);
  50688. return animation;
  50689. };
  50690. /**
  50691. * Create and start an animation on a node
  50692. * @param name defines the name of the global animation that will be run on all nodes
  50693. * @param node defines the root node where the animation will take place
  50694. * @param targetProperty defines property to animate
  50695. * @param framePerSecond defines the number of frame per second yo use
  50696. * @param totalFrame defines the number of frames in total
  50697. * @param from defines the initial value
  50698. * @param to defines the final value
  50699. * @param loopMode defines which loop mode you want to use (off by default)
  50700. * @param easingFunction defines the easing function to use (linear by default)
  50701. * @param onAnimationEnd defines the callback to call when animation end
  50702. * @returns the animatable created for this animation
  50703. */
  50704. Animation.CreateAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  50705. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  50706. if (!animation) {
  50707. return null;
  50708. }
  50709. return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  50710. };
  50711. /**
  50712. * Create and start an animation on a node and its descendants
  50713. * @param name defines the name of the global animation that will be run on all nodes
  50714. * @param node defines the root node where the animation will take place
  50715. * @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
  50716. * @param targetProperty defines property to animate
  50717. * @param framePerSecond defines the number of frame per second to use
  50718. * @param totalFrame defines the number of frames in total
  50719. * @param from defines the initial value
  50720. * @param to defines the final value
  50721. * @param loopMode defines which loop mode you want to use (off by default)
  50722. * @param easingFunction defines the easing function to use (linear by default)
  50723. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  50724. * @returns the list of animatables created for all nodes
  50725. * @example https://www.babylonjs-playground.com/#MH0VLI
  50726. */
  50727. Animation.CreateAndStartHierarchyAnimation = function (name, node, directDescendantsOnly, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  50728. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  50729. if (!animation) {
  50730. return null;
  50731. }
  50732. var scene = node.getScene();
  50733. return scene.beginDirectHierarchyAnimation(node, directDescendantsOnly, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  50734. };
  50735. /**
  50736. * Creates a new animation, merges it with the existing animations and starts it
  50737. * @param name Name of the animation
  50738. * @param node Node which contains the scene that begins the animations
  50739. * @param targetProperty Specifies which property to animate
  50740. * @param framePerSecond The frames per second of the animation
  50741. * @param totalFrame The total number of frames
  50742. * @param from The frame at the beginning of the animation
  50743. * @param to The frame at the end of the animation
  50744. * @param loopMode Specifies the loop mode of the animation
  50745. * @param easingFunction (Optional) The easing function of the animation, which allow custom mathematical formulas for animations
  50746. * @param onAnimationEnd Callback to run once the animation is complete
  50747. * @returns Nullable animation
  50748. */
  50749. Animation.CreateMergeAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  50750. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  50751. if (!animation) {
  50752. return null;
  50753. }
  50754. node.animations.push(animation);
  50755. return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  50756. };
  50757. /**
  50758. * Transition property of an host to the target Value
  50759. * @param property The property to transition
  50760. * @param targetValue The target Value of the property
  50761. * @param host The object where the property to animate belongs
  50762. * @param scene Scene used to run the animation
  50763. * @param frameRate Framerate (in frame/s) to use
  50764. * @param transition The transition type we want to use
  50765. * @param duration The duration of the animation, in milliseconds
  50766. * @param onAnimationEnd Callback trigger at the end of the animation
  50767. * @returns Nullable animation
  50768. */
  50769. Animation.TransitionTo = function (property, targetValue, host, scene, frameRate, transition, duration, onAnimationEnd) {
  50770. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  50771. if (duration <= 0) {
  50772. host[property] = targetValue;
  50773. if (onAnimationEnd) {
  50774. onAnimationEnd();
  50775. }
  50776. return null;
  50777. }
  50778. var endFrame = frameRate * (duration / 1000);
  50779. transition.setKeys([{
  50780. frame: 0,
  50781. value: host[property].clone ? host[property].clone() : host[property]
  50782. },
  50783. {
  50784. frame: endFrame,
  50785. value: targetValue
  50786. }]);
  50787. if (!host.animations) {
  50788. host.animations = [];
  50789. }
  50790. host.animations.push(transition);
  50791. var animation = scene.beginAnimation(host, 0, endFrame, false);
  50792. animation.onAnimationEnd = onAnimationEnd;
  50793. return animation;
  50794. };
  50795. Object.defineProperty(Animation.prototype, "runtimeAnimations", {
  50796. /**
  50797. * Return the array of runtime animations currently using this animation
  50798. */
  50799. get: function () {
  50800. return this._runtimeAnimations;
  50801. },
  50802. enumerable: true,
  50803. configurable: true
  50804. });
  50805. Object.defineProperty(Animation.prototype, "hasRunningRuntimeAnimations", {
  50806. /**
  50807. * Specifies if any of the runtime animations are currently running
  50808. */
  50809. get: function () {
  50810. for (var _i = 0, _a = this._runtimeAnimations; _i < _a.length; _i++) {
  50811. var runtimeAnimation = _a[_i];
  50812. if (!runtimeAnimation.isStopped) {
  50813. return true;
  50814. }
  50815. }
  50816. return false;
  50817. },
  50818. enumerable: true,
  50819. configurable: true
  50820. });
  50821. // Methods
  50822. /**
  50823. * Converts the animation to a string
  50824. * @param fullDetails support for multiple levels of logging within scene loading
  50825. * @returns String form of the animation
  50826. */
  50827. Animation.prototype.toString = function (fullDetails) {
  50828. var ret = "Name: " + this.name + ", property: " + this.targetProperty;
  50829. ret += ", datatype: " + (["Float", "Vector3", "Quaternion", "Matrix", "Color3", "Vector2"])[this.dataType];
  50830. ret += ", nKeys: " + (this._keys ? this._keys.length : "none");
  50831. ret += ", nRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  50832. if (fullDetails) {
  50833. ret += ", Ranges: {";
  50834. var first = true;
  50835. for (var name in this._ranges) {
  50836. if (first) {
  50837. ret += ", ";
  50838. first = false;
  50839. }
  50840. ret += name;
  50841. }
  50842. ret += "}";
  50843. }
  50844. return ret;
  50845. };
  50846. /**
  50847. * Add an event to this animation
  50848. * @param event Event to add
  50849. */
  50850. Animation.prototype.addEvent = function (event) {
  50851. this._events.push(event);
  50852. };
  50853. /**
  50854. * Remove all events found at the given frame
  50855. * @param frame The frame to remove events from
  50856. */
  50857. Animation.prototype.removeEvents = function (frame) {
  50858. for (var index = 0; index < this._events.length; index++) {
  50859. if (this._events[index].frame === frame) {
  50860. this._events.splice(index, 1);
  50861. index--;
  50862. }
  50863. }
  50864. };
  50865. /**
  50866. * Retrieves all the events from the animation
  50867. * @returns Events from the animation
  50868. */
  50869. Animation.prototype.getEvents = function () {
  50870. return this._events;
  50871. };
  50872. /**
  50873. * Creates an animation range
  50874. * @param name Name of the animation range
  50875. * @param from Starting frame of the animation range
  50876. * @param to Ending frame of the animation
  50877. */
  50878. Animation.prototype.createRange = function (name, from, to) {
  50879. // check name not already in use; could happen for bones after serialized
  50880. if (!this._ranges[name]) {
  50881. this._ranges[name] = new AnimationRange(name, from, to);
  50882. }
  50883. };
  50884. /**
  50885. * Deletes an animation range by name
  50886. * @param name Name of the animation range to delete
  50887. * @param deleteFrames Specifies if the key frames for the range should also be deleted (true) or not (false)
  50888. */
  50889. Animation.prototype.deleteRange = function (name, deleteFrames) {
  50890. if (deleteFrames === void 0) { deleteFrames = true; }
  50891. var range = this._ranges[name];
  50892. if (!range) {
  50893. return;
  50894. }
  50895. if (deleteFrames) {
  50896. var from = range.from;
  50897. var to = range.to;
  50898. // this loop MUST go high to low for multiple splices to work
  50899. for (var key = this._keys.length - 1; key >= 0; key--) {
  50900. if (this._keys[key].frame >= from && this._keys[key].frame <= to) {
  50901. this._keys.splice(key, 1);
  50902. }
  50903. }
  50904. }
  50905. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  50906. };
  50907. /**
  50908. * Gets the animation range by name, or null if not defined
  50909. * @param name Name of the animation range
  50910. * @returns Nullable animation range
  50911. */
  50912. Animation.prototype.getRange = function (name) {
  50913. return this._ranges[name];
  50914. };
  50915. /**
  50916. * Gets the key frames from the animation
  50917. * @returns The key frames of the animation
  50918. */
  50919. Animation.prototype.getKeys = function () {
  50920. return this._keys;
  50921. };
  50922. /**
  50923. * Gets the highest frame rate of the animation
  50924. * @returns Highest frame rate of the animation
  50925. */
  50926. Animation.prototype.getHighestFrame = function () {
  50927. var ret = 0;
  50928. for (var key = 0, nKeys = this._keys.length; key < nKeys; key++) {
  50929. if (ret < this._keys[key].frame) {
  50930. ret = this._keys[key].frame;
  50931. }
  50932. }
  50933. return ret;
  50934. };
  50935. /**
  50936. * Gets the easing function of the animation
  50937. * @returns Easing function of the animation
  50938. */
  50939. Animation.prototype.getEasingFunction = function () {
  50940. return this._easingFunction;
  50941. };
  50942. /**
  50943. * Sets the easing function of the animation
  50944. * @param easingFunction A custom mathematical formula for animation
  50945. */
  50946. Animation.prototype.setEasingFunction = function (easingFunction) {
  50947. this._easingFunction = easingFunction;
  50948. };
  50949. /**
  50950. * Interpolates a scalar linearly
  50951. * @param startValue Start value of the animation curve
  50952. * @param endValue End value of the animation curve
  50953. * @param gradient Scalar amount to interpolate
  50954. * @returns Interpolated scalar value
  50955. */
  50956. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  50957. return BABYLON.Scalar.Lerp(startValue, endValue, gradient);
  50958. };
  50959. /**
  50960. * Interpolates a scalar cubically
  50961. * @param startValue Start value of the animation curve
  50962. * @param outTangent End tangent of the animation
  50963. * @param endValue End value of the animation curve
  50964. * @param inTangent Start tangent of the animation curve
  50965. * @param gradient Scalar amount to interpolate
  50966. * @returns Interpolated scalar value
  50967. */
  50968. Animation.prototype.floatInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  50969. return BABYLON.Scalar.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  50970. };
  50971. /**
  50972. * Interpolates a quaternion using a spherical linear interpolation
  50973. * @param startValue Start value of the animation curve
  50974. * @param endValue End value of the animation curve
  50975. * @param gradient Scalar amount to interpolate
  50976. * @returns Interpolated quaternion value
  50977. */
  50978. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  50979. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  50980. };
  50981. /**
  50982. * Interpolates a quaternion cubically
  50983. * @param startValue Start value of the animation curve
  50984. * @param outTangent End tangent of the animation curve
  50985. * @param endValue End value of the animation curve
  50986. * @param inTangent Start tangent of the animation curve
  50987. * @param gradient Scalar amount to interpolate
  50988. * @returns Interpolated quaternion value
  50989. */
  50990. Animation.prototype.quaternionInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  50991. return BABYLON.Quaternion.Hermite(startValue, outTangent, endValue, inTangent, gradient).normalize();
  50992. };
  50993. /**
  50994. * Interpolates a Vector3 linearl
  50995. * @param startValue Start value of the animation curve
  50996. * @param endValue End value of the animation curve
  50997. * @param gradient Scalar amount to interpolate
  50998. * @returns Interpolated scalar value
  50999. */
  51000. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  51001. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  51002. };
  51003. /**
  51004. * Interpolates a Vector3 cubically
  51005. * @param startValue Start value of the animation curve
  51006. * @param outTangent End tangent of the animation
  51007. * @param endValue End value of the animation curve
  51008. * @param inTangent Start tangent of the animation curve
  51009. * @param gradient Scalar amount to interpolate
  51010. * @returns InterpolatedVector3 value
  51011. */
  51012. Animation.prototype.vector3InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  51013. return BABYLON.Vector3.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  51014. };
  51015. /**
  51016. * Interpolates a Vector2 linearly
  51017. * @param startValue Start value of the animation curve
  51018. * @param endValue End value of the animation curve
  51019. * @param gradient Scalar amount to interpolate
  51020. * @returns Interpolated Vector2 value
  51021. */
  51022. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  51023. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  51024. };
  51025. /**
  51026. * Interpolates a Vector2 cubically
  51027. * @param startValue Start value of the animation curve
  51028. * @param outTangent End tangent of the animation
  51029. * @param endValue End value of the animation curve
  51030. * @param inTangent Start tangent of the animation curve
  51031. * @param gradient Scalar amount to interpolate
  51032. * @returns Interpolated Vector2 value
  51033. */
  51034. Animation.prototype.vector2InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  51035. return BABYLON.Vector2.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  51036. };
  51037. /**
  51038. * Interpolates a size linearly
  51039. * @param startValue Start value of the animation curve
  51040. * @param endValue End value of the animation curve
  51041. * @param gradient Scalar amount to interpolate
  51042. * @returns Interpolated Size value
  51043. */
  51044. Animation.prototype.sizeInterpolateFunction = function (startValue, endValue, gradient) {
  51045. return BABYLON.Size.Lerp(startValue, endValue, gradient);
  51046. };
  51047. /**
  51048. * Interpolates a Color3 linearly
  51049. * @param startValue Start value of the animation curve
  51050. * @param endValue End value of the animation curve
  51051. * @param gradient Scalar amount to interpolate
  51052. * @returns Interpolated Color3 value
  51053. */
  51054. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  51055. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  51056. };
  51057. /**
  51058. * @hidden Internal use only
  51059. */
  51060. Animation.prototype._getKeyValue = function (value) {
  51061. if (typeof value === "function") {
  51062. return value();
  51063. }
  51064. return value;
  51065. };
  51066. /**
  51067. * @hidden Internal use only
  51068. */
  51069. Animation.prototype._interpolate = function (currentFrame, repeatCount, workValue, loopMode, offsetValue, highLimitValue) {
  51070. if (loopMode === Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  51071. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  51072. }
  51073. var keys = this.getKeys();
  51074. // Try to get a hash to find the right key
  51075. 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));
  51076. if (keys[startKeyIndex].frame >= currentFrame) {
  51077. while (startKeyIndex - 1 >= 0 && keys[startKeyIndex].frame >= currentFrame) {
  51078. startKeyIndex--;
  51079. }
  51080. }
  51081. for (var key = startKeyIndex; key < keys.length; key++) {
  51082. var endKey = keys[key + 1];
  51083. if (endKey.frame >= currentFrame) {
  51084. var startKey = keys[key];
  51085. var startValue = this._getKeyValue(startKey.value);
  51086. if (startKey.interpolation === AnimationKeyInterpolation.STEP) {
  51087. return startValue;
  51088. }
  51089. var endValue = this._getKeyValue(endKey.value);
  51090. var useTangent = startKey.outTangent !== undefined && endKey.inTangent !== undefined;
  51091. var frameDelta = endKey.frame - startKey.frame;
  51092. // gradient : percent of currentFrame between the frame inf and the frame sup
  51093. var gradient = (currentFrame - startKey.frame) / frameDelta;
  51094. // check for easingFunction and correction of gradient
  51095. var easingFunction = this.getEasingFunction();
  51096. if (easingFunction != null) {
  51097. gradient = easingFunction.ease(gradient);
  51098. }
  51099. switch (this.dataType) {
  51100. // Float
  51101. case Animation.ANIMATIONTYPE_FLOAT:
  51102. var floatValue = useTangent ? this.floatInterpolateFunctionWithTangents(startValue, startKey.outTangent * frameDelta, endValue, endKey.inTangent * frameDelta, gradient) : this.floatInterpolateFunction(startValue, endValue, gradient);
  51103. switch (loopMode) {
  51104. case Animation.ANIMATIONLOOPMODE_CYCLE:
  51105. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  51106. return floatValue;
  51107. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  51108. return offsetValue * repeatCount + floatValue;
  51109. }
  51110. break;
  51111. // Quaternion
  51112. case Animation.ANIMATIONTYPE_QUATERNION:
  51113. var quatValue = useTangent ? this.quaternionInterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.quaternionInterpolateFunction(startValue, endValue, gradient);
  51114. switch (loopMode) {
  51115. case Animation.ANIMATIONLOOPMODE_CYCLE:
  51116. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  51117. return quatValue;
  51118. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  51119. return quatValue.addInPlace(offsetValue.scale(repeatCount));
  51120. }
  51121. return quatValue;
  51122. // Vector3
  51123. case Animation.ANIMATIONTYPE_VECTOR3:
  51124. var vec3Value = useTangent ? this.vector3InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.vector3InterpolateFunction(startValue, endValue, gradient);
  51125. switch (loopMode) {
  51126. case Animation.ANIMATIONLOOPMODE_CYCLE:
  51127. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  51128. return vec3Value;
  51129. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  51130. return vec3Value.add(offsetValue.scale(repeatCount));
  51131. }
  51132. // Vector2
  51133. case Animation.ANIMATIONTYPE_VECTOR2:
  51134. var vec2Value = useTangent ? this.vector2InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.vector2InterpolateFunction(startValue, endValue, gradient);
  51135. switch (loopMode) {
  51136. case Animation.ANIMATIONLOOPMODE_CYCLE:
  51137. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  51138. return vec2Value;
  51139. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  51140. return vec2Value.add(offsetValue.scale(repeatCount));
  51141. }
  51142. // Size
  51143. case Animation.ANIMATIONTYPE_SIZE:
  51144. switch (loopMode) {
  51145. case Animation.ANIMATIONLOOPMODE_CYCLE:
  51146. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  51147. return this.sizeInterpolateFunction(startValue, endValue, gradient);
  51148. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  51149. return this.sizeInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  51150. }
  51151. // Color3
  51152. case Animation.ANIMATIONTYPE_COLOR3:
  51153. switch (loopMode) {
  51154. case Animation.ANIMATIONLOOPMODE_CYCLE:
  51155. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  51156. return this.color3InterpolateFunction(startValue, endValue, gradient);
  51157. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  51158. return this.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  51159. }
  51160. // Matrix
  51161. case Animation.ANIMATIONTYPE_MATRIX:
  51162. switch (loopMode) {
  51163. case Animation.ANIMATIONLOOPMODE_CYCLE:
  51164. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  51165. if (Animation.AllowMatricesInterpolation) {
  51166. return this.matrixInterpolateFunction(startValue, endValue, gradient, workValue);
  51167. }
  51168. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  51169. return startValue;
  51170. }
  51171. default:
  51172. break;
  51173. }
  51174. break;
  51175. }
  51176. }
  51177. return this._getKeyValue(keys[keys.length - 1].value);
  51178. };
  51179. /**
  51180. * Defines the function to use to interpolate matrices
  51181. * @param startValue defines the start matrix
  51182. * @param endValue defines the end matrix
  51183. * @param gradient defines the gradient between both matrices
  51184. * @param result defines an optional target matrix where to store the interpolation
  51185. * @returns the interpolated matrix
  51186. */
  51187. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient, result) {
  51188. if (Animation.AllowMatrixDecomposeForInterpolation) {
  51189. if (result) {
  51190. BABYLON.Matrix.DecomposeLerpToRef(startValue, endValue, gradient, result);
  51191. return result;
  51192. }
  51193. return BABYLON.Matrix.DecomposeLerp(startValue, endValue, gradient);
  51194. }
  51195. if (result) {
  51196. BABYLON.Matrix.LerpToRef(startValue, endValue, gradient, result);
  51197. return result;
  51198. }
  51199. return BABYLON.Matrix.Lerp(startValue, endValue, gradient);
  51200. };
  51201. /**
  51202. * Makes a copy of the animation
  51203. * @returns Cloned animation
  51204. */
  51205. Animation.prototype.clone = function () {
  51206. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  51207. clone.enableBlending = this.enableBlending;
  51208. clone.blendingSpeed = this.blendingSpeed;
  51209. if (this._keys) {
  51210. clone.setKeys(this._keys);
  51211. }
  51212. if (this._ranges) {
  51213. clone._ranges = {};
  51214. for (var name in this._ranges) {
  51215. var range = this._ranges[name];
  51216. if (!range) {
  51217. continue;
  51218. }
  51219. clone._ranges[name] = range.clone();
  51220. }
  51221. }
  51222. return clone;
  51223. };
  51224. /**
  51225. * Sets the key frames of the animation
  51226. * @param values The animation key frames to set
  51227. */
  51228. Animation.prototype.setKeys = function (values) {
  51229. this._keys = values.slice(0);
  51230. };
  51231. /**
  51232. * Serializes the animation to an object
  51233. * @returns Serialized object
  51234. */
  51235. Animation.prototype.serialize = function () {
  51236. var serializationObject = {};
  51237. serializationObject.name = this.name;
  51238. serializationObject.property = this.targetProperty;
  51239. serializationObject.framePerSecond = this.framePerSecond;
  51240. serializationObject.dataType = this.dataType;
  51241. serializationObject.loopBehavior = this.loopMode;
  51242. serializationObject.enableBlending = this.enableBlending;
  51243. serializationObject.blendingSpeed = this.blendingSpeed;
  51244. var dataType = this.dataType;
  51245. serializationObject.keys = [];
  51246. var keys = this.getKeys();
  51247. for (var index = 0; index < keys.length; index++) {
  51248. var animationKey = keys[index];
  51249. var key = {};
  51250. key.frame = animationKey.frame;
  51251. switch (dataType) {
  51252. case Animation.ANIMATIONTYPE_FLOAT:
  51253. key.values = [animationKey.value];
  51254. break;
  51255. case Animation.ANIMATIONTYPE_QUATERNION:
  51256. case Animation.ANIMATIONTYPE_MATRIX:
  51257. case Animation.ANIMATIONTYPE_VECTOR3:
  51258. case Animation.ANIMATIONTYPE_COLOR3:
  51259. key.values = animationKey.value.asArray();
  51260. break;
  51261. }
  51262. serializationObject.keys.push(key);
  51263. }
  51264. serializationObject.ranges = [];
  51265. for (var name in this._ranges) {
  51266. var source = this._ranges[name];
  51267. if (!source) {
  51268. continue;
  51269. }
  51270. var range = {};
  51271. range.name = name;
  51272. range.from = source.from;
  51273. range.to = source.to;
  51274. serializationObject.ranges.push(range);
  51275. }
  51276. return serializationObject;
  51277. };
  51278. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  51279. /**
  51280. * Get the float animation type
  51281. */
  51282. get: function () {
  51283. return Animation._ANIMATIONTYPE_FLOAT;
  51284. },
  51285. enumerable: true,
  51286. configurable: true
  51287. });
  51288. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  51289. /**
  51290. * Get the Vector3 animation type
  51291. */
  51292. get: function () {
  51293. return Animation._ANIMATIONTYPE_VECTOR3;
  51294. },
  51295. enumerable: true,
  51296. configurable: true
  51297. });
  51298. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  51299. /**
  51300. * Get the Vectpr2 animation type
  51301. */
  51302. get: function () {
  51303. return Animation._ANIMATIONTYPE_VECTOR2;
  51304. },
  51305. enumerable: true,
  51306. configurable: true
  51307. });
  51308. Object.defineProperty(Animation, "ANIMATIONTYPE_SIZE", {
  51309. /**
  51310. * Get the Size animation type
  51311. */
  51312. get: function () {
  51313. return Animation._ANIMATIONTYPE_SIZE;
  51314. },
  51315. enumerable: true,
  51316. configurable: true
  51317. });
  51318. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  51319. /**
  51320. * Get the Quaternion animation type
  51321. */
  51322. get: function () {
  51323. return Animation._ANIMATIONTYPE_QUATERNION;
  51324. },
  51325. enumerable: true,
  51326. configurable: true
  51327. });
  51328. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  51329. /**
  51330. * Get the Matrix animation type
  51331. */
  51332. get: function () {
  51333. return Animation._ANIMATIONTYPE_MATRIX;
  51334. },
  51335. enumerable: true,
  51336. configurable: true
  51337. });
  51338. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  51339. /**
  51340. * Get the Color3 animation type
  51341. */
  51342. get: function () {
  51343. return Animation._ANIMATIONTYPE_COLOR3;
  51344. },
  51345. enumerable: true,
  51346. configurable: true
  51347. });
  51348. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  51349. /**
  51350. * Get the Relative Loop Mode
  51351. */
  51352. get: function () {
  51353. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  51354. },
  51355. enumerable: true,
  51356. configurable: true
  51357. });
  51358. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  51359. /**
  51360. * Get the Cycle Loop Mode
  51361. */
  51362. get: function () {
  51363. return Animation._ANIMATIONLOOPMODE_CYCLE;
  51364. },
  51365. enumerable: true,
  51366. configurable: true
  51367. });
  51368. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  51369. /**
  51370. * Get the Constant Loop Mode
  51371. */
  51372. get: function () {
  51373. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  51374. },
  51375. enumerable: true,
  51376. configurable: true
  51377. });
  51378. /** @hidden */
  51379. Animation._UniversalLerp = function (left, right, amount) {
  51380. var constructor = left.constructor;
  51381. if (constructor.Lerp) { // Lerp supported
  51382. return constructor.Lerp(left, right, amount);
  51383. }
  51384. else if (constructor.Slerp) { // Slerp supported
  51385. return constructor.Slerp(left, right, amount);
  51386. }
  51387. else if (left.toFixed) { // Number
  51388. return left * (1.0 - amount) + amount * right;
  51389. }
  51390. else { // Blending not supported
  51391. return right;
  51392. }
  51393. };
  51394. /**
  51395. * Parses an animation object and creates an animation
  51396. * @param parsedAnimation Parsed animation object
  51397. * @returns Animation object
  51398. */
  51399. Animation.Parse = function (parsedAnimation) {
  51400. var animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  51401. var dataType = parsedAnimation.dataType;
  51402. var keys = [];
  51403. var data;
  51404. var index;
  51405. if (parsedAnimation.enableBlending) {
  51406. animation.enableBlending = parsedAnimation.enableBlending;
  51407. }
  51408. if (parsedAnimation.blendingSpeed) {
  51409. animation.blendingSpeed = parsedAnimation.blendingSpeed;
  51410. }
  51411. for (index = 0; index < parsedAnimation.keys.length; index++) {
  51412. var key = parsedAnimation.keys[index];
  51413. var inTangent;
  51414. var outTangent;
  51415. switch (dataType) {
  51416. case Animation.ANIMATIONTYPE_FLOAT:
  51417. data = key.values[0];
  51418. if (key.values.length >= 1) {
  51419. inTangent = key.values[1];
  51420. }
  51421. if (key.values.length >= 2) {
  51422. outTangent = key.values[2];
  51423. }
  51424. break;
  51425. case Animation.ANIMATIONTYPE_QUATERNION:
  51426. data = BABYLON.Quaternion.FromArray(key.values);
  51427. if (key.values.length >= 8) {
  51428. var _inTangent = BABYLON.Quaternion.FromArray(key.values.slice(4, 8));
  51429. if (!_inTangent.equals(BABYLON.Quaternion.Zero())) {
  51430. inTangent = _inTangent;
  51431. }
  51432. }
  51433. if (key.values.length >= 12) {
  51434. var _outTangent = BABYLON.Quaternion.FromArray(key.values.slice(8, 12));
  51435. if (!_outTangent.equals(BABYLON.Quaternion.Zero())) {
  51436. outTangent = _outTangent;
  51437. }
  51438. }
  51439. break;
  51440. case Animation.ANIMATIONTYPE_MATRIX:
  51441. data = BABYLON.Matrix.FromArray(key.values);
  51442. break;
  51443. case Animation.ANIMATIONTYPE_COLOR3:
  51444. data = BABYLON.Color3.FromArray(key.values);
  51445. break;
  51446. case Animation.ANIMATIONTYPE_VECTOR3:
  51447. default:
  51448. data = BABYLON.Vector3.FromArray(key.values);
  51449. break;
  51450. }
  51451. var keyData = {};
  51452. keyData.frame = key.frame;
  51453. keyData.value = data;
  51454. if (inTangent != undefined) {
  51455. keyData.inTangent = inTangent;
  51456. }
  51457. if (outTangent != undefined) {
  51458. keyData.outTangent = outTangent;
  51459. }
  51460. keys.push(keyData);
  51461. }
  51462. animation.setKeys(keys);
  51463. if (parsedAnimation.ranges) {
  51464. for (index = 0; index < parsedAnimation.ranges.length; index++) {
  51465. data = parsedAnimation.ranges[index];
  51466. animation.createRange(data.name, data.from, data.to);
  51467. }
  51468. }
  51469. return animation;
  51470. };
  51471. /**
  51472. * Appends the serialized animations from the source animations
  51473. * @param source Source containing the animations
  51474. * @param destination Target to store the animations
  51475. */
  51476. Animation.AppendSerializedAnimations = function (source, destination) {
  51477. if (source.animations) {
  51478. destination.animations = [];
  51479. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  51480. var animation = source.animations[animationIndex];
  51481. destination.animations.push(animation.serialize());
  51482. }
  51483. }
  51484. };
  51485. /**
  51486. * Use matrix interpolation instead of using direct key value when animating matrices
  51487. */
  51488. Animation.AllowMatricesInterpolation = false;
  51489. /**
  51490. * When matrix interpolation is enabled, this boolean forces the system to use Matrix.DecomposeLerp instead of Matrix.Lerp. Interpolation is more precise but slower
  51491. */
  51492. Animation.AllowMatrixDecomposeForInterpolation = true;
  51493. // Statics
  51494. /**
  51495. * Float animation type
  51496. */
  51497. Animation._ANIMATIONTYPE_FLOAT = 0;
  51498. /**
  51499. * Vector3 animation type
  51500. */
  51501. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  51502. /**
  51503. * Quaternion animation type
  51504. */
  51505. Animation._ANIMATIONTYPE_QUATERNION = 2;
  51506. /**
  51507. * Matrix animation type
  51508. */
  51509. Animation._ANIMATIONTYPE_MATRIX = 3;
  51510. /**
  51511. * Color3 animation type
  51512. */
  51513. Animation._ANIMATIONTYPE_COLOR3 = 4;
  51514. /**
  51515. * Vector2 animation type
  51516. */
  51517. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  51518. /**
  51519. * Size animation type
  51520. */
  51521. Animation._ANIMATIONTYPE_SIZE = 6;
  51522. /**
  51523. * Relative Loop Mode
  51524. */
  51525. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  51526. /**
  51527. * Cycle Loop Mode
  51528. */
  51529. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  51530. /**
  51531. * Constant Loop Mode
  51532. */
  51533. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  51534. return Animation;
  51535. }());
  51536. BABYLON.Animation = Animation;
  51537. })(BABYLON || (BABYLON = {}));
  51538. //# sourceMappingURL=babylon.animation.js.map
  51539. var BABYLON;
  51540. (function (BABYLON) {
  51541. /**
  51542. * This class defines the direct association between an animation and a target
  51543. */
  51544. var TargetedAnimation = /** @class */ (function () {
  51545. function TargetedAnimation() {
  51546. }
  51547. return TargetedAnimation;
  51548. }());
  51549. BABYLON.TargetedAnimation = TargetedAnimation;
  51550. /**
  51551. * Use this class to create coordinated animations on multiple targets
  51552. */
  51553. var AnimationGroup = /** @class */ (function () {
  51554. function AnimationGroup(name, scene) {
  51555. if (scene === void 0) { scene = null; }
  51556. this.name = name;
  51557. this._targetedAnimations = new Array();
  51558. this._animatables = new Array();
  51559. this._from = Number.MAX_VALUE;
  51560. this._to = -Number.MAX_VALUE;
  51561. this._speedRatio = 1;
  51562. this.onAnimationEndObservable = new BABYLON.Observable();
  51563. /**
  51564. * This observable will notify when all animations have ended.
  51565. */
  51566. this.onAnimationGroupEndObservable = new BABYLON.Observable();
  51567. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  51568. this._scene.animationGroups.push(this);
  51569. }
  51570. Object.defineProperty(AnimationGroup.prototype, "from", {
  51571. /**
  51572. * Gets the first frame
  51573. */
  51574. get: function () {
  51575. return this._from;
  51576. },
  51577. enumerable: true,
  51578. configurable: true
  51579. });
  51580. Object.defineProperty(AnimationGroup.prototype, "to", {
  51581. /**
  51582. * Gets the last frame
  51583. */
  51584. get: function () {
  51585. return this._to;
  51586. },
  51587. enumerable: true,
  51588. configurable: true
  51589. });
  51590. Object.defineProperty(AnimationGroup.prototype, "isStarted", {
  51591. /**
  51592. * Define if the animations are started
  51593. */
  51594. get: function () {
  51595. return this._isStarted;
  51596. },
  51597. enumerable: true,
  51598. configurable: true
  51599. });
  51600. Object.defineProperty(AnimationGroup.prototype, "speedRatio", {
  51601. /**
  51602. * Gets or sets the speed ratio to use for all animations
  51603. */
  51604. get: function () {
  51605. return this._speedRatio;
  51606. },
  51607. /**
  51608. * Gets or sets the speed ratio to use for all animations
  51609. */
  51610. set: function (value) {
  51611. if (this._speedRatio === value) {
  51612. return;
  51613. }
  51614. this._speedRatio = value;
  51615. for (var index = 0; index < this._animatables.length; index++) {
  51616. var animatable = this._animatables[index];
  51617. animatable.speedRatio = this._speedRatio;
  51618. }
  51619. },
  51620. enumerable: true,
  51621. configurable: true
  51622. });
  51623. Object.defineProperty(AnimationGroup.prototype, "targetedAnimations", {
  51624. /**
  51625. * Gets the targeted animations for this animation group
  51626. */
  51627. get: function () {
  51628. return this._targetedAnimations;
  51629. },
  51630. enumerable: true,
  51631. configurable: true
  51632. });
  51633. Object.defineProperty(AnimationGroup.prototype, "animatables", {
  51634. /**
  51635. * returning the list of animatables controlled by this animation group.
  51636. */
  51637. get: function () {
  51638. return this._animatables;
  51639. },
  51640. enumerable: true,
  51641. configurable: true
  51642. });
  51643. /**
  51644. * Add an animation (with its target) in the group
  51645. * @param animation defines the animation we want to add
  51646. * @param target defines the target of the animation
  51647. * @returns the {BABYLON.TargetedAnimation} object
  51648. */
  51649. AnimationGroup.prototype.addTargetedAnimation = function (animation, target) {
  51650. var targetedAnimation = {
  51651. animation: animation,
  51652. target: target
  51653. };
  51654. var keys = animation.getKeys();
  51655. if (this._from > keys[0].frame) {
  51656. this._from = keys[0].frame;
  51657. }
  51658. if (this._to < keys[keys.length - 1].frame) {
  51659. this._to = keys[keys.length - 1].frame;
  51660. }
  51661. this._targetedAnimations.push(targetedAnimation);
  51662. return targetedAnimation;
  51663. };
  51664. /**
  51665. * This function will normalize every animation in the group to make sure they all go from beginFrame to endFrame
  51666. * It can add constant keys at begin or end
  51667. * @param beginFrame defines the new begin frame for all animations or the smallest begin frame of all animations if null (defaults to null)
  51668. * @param endFrame defines the new end frame for all animations or the largest end frame of all animations if null (defaults to null)
  51669. */
  51670. AnimationGroup.prototype.normalize = function (beginFrame, endFrame) {
  51671. if (beginFrame === void 0) { beginFrame = null; }
  51672. if (endFrame === void 0) { endFrame = null; }
  51673. if (beginFrame == null)
  51674. beginFrame = this._from;
  51675. if (endFrame == null)
  51676. endFrame = this._to;
  51677. for (var index = 0; index < this._targetedAnimations.length; index++) {
  51678. var targetedAnimation = this._targetedAnimations[index];
  51679. var keys = targetedAnimation.animation.getKeys();
  51680. var startKey = keys[0];
  51681. var endKey = keys[keys.length - 1];
  51682. if (startKey.frame > beginFrame) {
  51683. var newKey = {
  51684. frame: beginFrame,
  51685. value: startKey.value,
  51686. inTangent: startKey.inTangent,
  51687. outTangent: startKey.outTangent,
  51688. interpolation: startKey.interpolation
  51689. };
  51690. keys.splice(0, 0, newKey);
  51691. }
  51692. if (endKey.frame < endFrame) {
  51693. var newKey = {
  51694. frame: endFrame,
  51695. value: endKey.value,
  51696. inTangent: endKey.outTangent,
  51697. outTangent: endKey.outTangent,
  51698. interpolation: endKey.interpolation
  51699. };
  51700. keys.push(newKey);
  51701. }
  51702. }
  51703. this._from = beginFrame;
  51704. this._to = endFrame;
  51705. return this;
  51706. };
  51707. /**
  51708. * Start all animations on given targets
  51709. * @param loop defines if animations must loop
  51710. * @param speedRatio defines the ratio to apply to animation speed (1 by default)
  51711. * @param from defines the from key (optional)
  51712. * @param to defines the to key (optional)
  51713. * @returns the current animation group
  51714. */
  51715. AnimationGroup.prototype.start = function (loop, speedRatio, from, to) {
  51716. var _this = this;
  51717. if (loop === void 0) { loop = false; }
  51718. if (speedRatio === void 0) { speedRatio = 1; }
  51719. if (this._isStarted || this._targetedAnimations.length === 0) {
  51720. return this;
  51721. }
  51722. var _loop_1 = function (targetedAnimation) {
  51723. var animatable = this_1._scene.beginDirectAnimation(targetedAnimation.target, [targetedAnimation.animation], from !== undefined ? from : this_1._from, to !== undefined ? to : this_1._to, loop, speedRatio);
  51724. animatable.onAnimationEnd = function () {
  51725. _this.onAnimationEndObservable.notifyObservers(targetedAnimation);
  51726. _this._checkAnimationGroupEnded(animatable);
  51727. };
  51728. this_1._animatables.push(animatable);
  51729. };
  51730. var this_1 = this;
  51731. for (var _i = 0, _a = this._targetedAnimations; _i < _a.length; _i++) {
  51732. var targetedAnimation = _a[_i];
  51733. _loop_1(targetedAnimation);
  51734. }
  51735. this._speedRatio = speedRatio;
  51736. this._isStarted = true;
  51737. return this;
  51738. };
  51739. /**
  51740. * Pause all animations
  51741. */
  51742. AnimationGroup.prototype.pause = function () {
  51743. if (!this._isStarted) {
  51744. return this;
  51745. }
  51746. for (var index = 0; index < this._animatables.length; index++) {
  51747. var animatable = this._animatables[index];
  51748. animatable.pause();
  51749. }
  51750. return this;
  51751. };
  51752. /**
  51753. * Play all animations to initial state
  51754. * This function will start() the animations if they were not started or will restart() them if they were paused
  51755. * @param loop defines if animations must loop
  51756. */
  51757. AnimationGroup.prototype.play = function (loop) {
  51758. // only if all animatables are ready and exist
  51759. if (this.isStarted && this._animatables.length === this._targetedAnimations.length) {
  51760. if (loop !== undefined) {
  51761. for (var index = 0; index < this._animatables.length; index++) {
  51762. var animatable = this._animatables[index];
  51763. animatable.loopAnimation = loop;
  51764. }
  51765. }
  51766. this.restart();
  51767. }
  51768. else {
  51769. this.stop();
  51770. this.start(loop, this._speedRatio);
  51771. }
  51772. return this;
  51773. };
  51774. /**
  51775. * Reset all animations to initial state
  51776. */
  51777. AnimationGroup.prototype.reset = function () {
  51778. if (!this._isStarted) {
  51779. return this;
  51780. }
  51781. for (var index = 0; index < this._animatables.length; index++) {
  51782. var animatable = this._animatables[index];
  51783. animatable.reset();
  51784. }
  51785. return this;
  51786. };
  51787. /**
  51788. * Restart animations from key 0
  51789. */
  51790. AnimationGroup.prototype.restart = function () {
  51791. if (!this._isStarted) {
  51792. return this;
  51793. }
  51794. for (var index = 0; index < this._animatables.length; index++) {
  51795. var animatable = this._animatables[index];
  51796. animatable.restart();
  51797. }
  51798. return this;
  51799. };
  51800. /**
  51801. * Stop all animations
  51802. */
  51803. AnimationGroup.prototype.stop = function () {
  51804. if (!this._isStarted) {
  51805. return this;
  51806. }
  51807. for (var index = 0; index < this._animatables.length; index++) {
  51808. var animatable = this._animatables[index];
  51809. animatable.stop();
  51810. }
  51811. this._isStarted = false;
  51812. return this;
  51813. };
  51814. /**
  51815. * Set animation weight for all animatables
  51816. * @param weight defines the weight to use
  51817. * @return the animationGroup
  51818. * @see http://doc.babylonjs.com/babylon101/animations#animation-weights
  51819. */
  51820. AnimationGroup.prototype.setWeightForAllAnimatables = function (weight) {
  51821. for (var index = 0; index < this._animatables.length; index++) {
  51822. var animatable = this._animatables[index];
  51823. animatable.weight = weight;
  51824. }
  51825. return this;
  51826. };
  51827. /**
  51828. * Synchronize and normalize all animatables with a source animatable
  51829. * @param root defines the root animatable to synchronize with
  51830. * @return the animationGroup
  51831. * @see http://doc.babylonjs.com/babylon101/animations#animation-weights
  51832. */
  51833. AnimationGroup.prototype.syncAllAnimationsWith = function (root) {
  51834. for (var index = 0; index < this._animatables.length; index++) {
  51835. var animatable = this._animatables[index];
  51836. animatable.syncWith(root);
  51837. }
  51838. return this;
  51839. };
  51840. /**
  51841. * Goes to a specific frame in this animation group
  51842. * @param frame the frame number to go to
  51843. * @return the animationGroup
  51844. */
  51845. AnimationGroup.prototype.goToFrame = function (frame) {
  51846. if (!this._isStarted) {
  51847. return this;
  51848. }
  51849. for (var index = 0; index < this._animatables.length; index++) {
  51850. var animatable = this._animatables[index];
  51851. animatable.goToFrame(frame);
  51852. }
  51853. return this;
  51854. };
  51855. /**
  51856. * Dispose all associated resources
  51857. */
  51858. AnimationGroup.prototype.dispose = function () {
  51859. this._targetedAnimations = [];
  51860. this._animatables = [];
  51861. var index = this._scene.animationGroups.indexOf(this);
  51862. if (index > -1) {
  51863. this._scene.animationGroups.splice(index, 1);
  51864. }
  51865. };
  51866. AnimationGroup.prototype._checkAnimationGroupEnded = function (animatable) {
  51867. // animatable should be taken out of the array
  51868. var idx = this._animatables.indexOf(animatable);
  51869. if (idx > -1) {
  51870. this._animatables.splice(idx, 1);
  51871. }
  51872. // all animatables were removed? animation group ended!
  51873. if (this._animatables.length === 0) {
  51874. this._isStarted = false;
  51875. this.onAnimationGroupEndObservable.notifyObservers(this);
  51876. }
  51877. };
  51878. return AnimationGroup;
  51879. }());
  51880. BABYLON.AnimationGroup = AnimationGroup;
  51881. })(BABYLON || (BABYLON = {}));
  51882. //# sourceMappingURL=babylon.animationGroup.js.map
  51883. var BABYLON;
  51884. (function (BABYLON) {
  51885. /**
  51886. * Defines a runtime animation
  51887. */
  51888. var RuntimeAnimation = /** @class */ (function () {
  51889. /**
  51890. * Create a new RuntimeAnimation object
  51891. * @param target defines the target of the animation
  51892. * @param animation defines the source animation object
  51893. * @param scene defines the hosting scene
  51894. * @param host defines the initiating Animatable
  51895. */
  51896. function RuntimeAnimation(target, animation, scene, host) {
  51897. var _this = this;
  51898. this._events = new Array();
  51899. /**
  51900. * The current frame of the runtime animation
  51901. */
  51902. this._currentFrame = 0;
  51903. /**
  51904. * The original value of the runtime animation
  51905. */
  51906. this._originalValue = new Array();
  51907. /**
  51908. * The offsets cache of the runtime animation
  51909. */
  51910. this._offsetsCache = {};
  51911. /**
  51912. * The high limits cache of the runtime animation
  51913. */
  51914. this._highLimitsCache = {};
  51915. /**
  51916. * Specifies if the runtime animation has been stopped
  51917. */
  51918. this._stopped = false;
  51919. /**
  51920. * The blending factor of the runtime animation
  51921. */
  51922. this._blendingFactor = 0;
  51923. /**
  51924. * The target path of the runtime animation
  51925. */
  51926. this._targetPath = "";
  51927. /**
  51928. * The weight of the runtime animation
  51929. */
  51930. this._weight = 1.0;
  51931. /**
  51932. * The ratio offset of the runtime animation
  51933. */
  51934. this._ratioOffset = 0;
  51935. /**
  51936. * The previous delay of the runtime animation
  51937. */
  51938. this._previousDelay = 0;
  51939. /**
  51940. * The previous ratio of the runtime animation
  51941. */
  51942. this._previousRatio = 0;
  51943. this._animation = animation;
  51944. this._target = target;
  51945. this._scene = scene;
  51946. this._host = host;
  51947. animation._runtimeAnimations.push(this);
  51948. // Cloning events locally
  51949. var events = animation.getEvents();
  51950. if (events && events.length > 0) {
  51951. events.forEach(function (e) {
  51952. _this._events.push(e._clone());
  51953. });
  51954. }
  51955. }
  51956. Object.defineProperty(RuntimeAnimation.prototype, "currentFrame", {
  51957. /**
  51958. * Gets the current frame of the runtime animation
  51959. */
  51960. get: function () {
  51961. return this._currentFrame;
  51962. },
  51963. enumerable: true,
  51964. configurable: true
  51965. });
  51966. Object.defineProperty(RuntimeAnimation.prototype, "weight", {
  51967. /**
  51968. * Gets the weight of the runtime animation
  51969. */
  51970. get: function () {
  51971. return this._weight;
  51972. },
  51973. enumerable: true,
  51974. configurable: true
  51975. });
  51976. Object.defineProperty(RuntimeAnimation.prototype, "currentValue", {
  51977. /**
  51978. * Gets the current value of the runtime animation
  51979. */
  51980. get: function () {
  51981. return this._currentValue;
  51982. },
  51983. enumerable: true,
  51984. configurable: true
  51985. });
  51986. Object.defineProperty(RuntimeAnimation.prototype, "targetPath", {
  51987. /**
  51988. * Gets the target path of the runtime animation
  51989. */
  51990. get: function () {
  51991. return this._targetPath;
  51992. },
  51993. enumerable: true,
  51994. configurable: true
  51995. });
  51996. Object.defineProperty(RuntimeAnimation.prototype, "target", {
  51997. /**
  51998. * Gets the actual target of the runtime animation
  51999. */
  52000. get: function () {
  52001. return this._activeTarget;
  52002. },
  52003. enumerable: true,
  52004. configurable: true
  52005. });
  52006. Object.defineProperty(RuntimeAnimation.prototype, "animation", {
  52007. /**
  52008. * Gets the animation from the runtime animation
  52009. */
  52010. get: function () {
  52011. return this._animation;
  52012. },
  52013. enumerable: true,
  52014. configurable: true
  52015. });
  52016. /**
  52017. * Resets the runtime animation to the beginning
  52018. * @param restoreOriginal defines whether to restore the target property to the original value
  52019. */
  52020. RuntimeAnimation.prototype.reset = function (restoreOriginal) {
  52021. if (restoreOriginal === void 0) { restoreOriginal = false; }
  52022. if (restoreOriginal) {
  52023. if (this._target instanceof Array) {
  52024. var index = 0;
  52025. for (var _i = 0, _a = this._target; _i < _a.length; _i++) {
  52026. var target = _a[_i];
  52027. if (this._originalValue[index] !== undefined) {
  52028. this._setValue(target, this._originalValue[index], -1);
  52029. }
  52030. index++;
  52031. }
  52032. }
  52033. else {
  52034. if (this._originalValue[0] !== undefined) {
  52035. this._setValue(this._target, this._originalValue[0], -1);
  52036. }
  52037. }
  52038. }
  52039. this._offsetsCache = {};
  52040. this._highLimitsCache = {};
  52041. this._currentFrame = 0;
  52042. this._blendingFactor = 0;
  52043. this._originalValue = new Array();
  52044. // Events
  52045. for (var index = 0; index < this._events.length; index++) {
  52046. this._events[index].isDone = false;
  52047. }
  52048. };
  52049. /**
  52050. * Specifies if the runtime animation is stopped
  52051. * @returns Boolean specifying if the runtime animation is stopped
  52052. */
  52053. RuntimeAnimation.prototype.isStopped = function () {
  52054. return this._stopped;
  52055. };
  52056. /**
  52057. * Disposes of the runtime animation
  52058. */
  52059. RuntimeAnimation.prototype.dispose = function () {
  52060. var index = this._animation.runtimeAnimations.indexOf(this);
  52061. if (index > -1) {
  52062. this._animation.runtimeAnimations.splice(index, 1);
  52063. }
  52064. };
  52065. /**
  52066. * Interpolates the animation from the current frame
  52067. * @param currentFrame The frame to interpolate the animation to
  52068. * @param repeatCount The number of times that the animation should loop
  52069. * @param loopMode The type of looping mode to use
  52070. * @param offsetValue Animation offset value
  52071. * @param highLimitValue The high limit value
  52072. * @returns The interpolated value
  52073. */
  52074. RuntimeAnimation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  52075. this._currentFrame = currentFrame;
  52076. if (this._animation.dataType === BABYLON.Animation.ANIMATIONTYPE_MATRIX && !this._workValue) {
  52077. this._workValue = BABYLON.Matrix.Zero();
  52078. }
  52079. return this._animation._interpolate(currentFrame, repeatCount, this._workValue, loopMode, offsetValue, highLimitValue);
  52080. };
  52081. /**
  52082. * Apply the interpolated value to the target
  52083. * @param currentValue defines the value computed by the animation
  52084. * @param weight defines the weight to apply to this value (Defaults to 1.0)
  52085. */
  52086. RuntimeAnimation.prototype.setValue = function (currentValue, weight) {
  52087. if (weight === void 0) { weight = 1.0; }
  52088. if (this._target instanceof Array) {
  52089. var index = 0;
  52090. for (var _i = 0, _a = this._target; _i < _a.length; _i++) {
  52091. var target = _a[_i];
  52092. this._setValue(target, currentValue, weight, index);
  52093. index++;
  52094. }
  52095. }
  52096. else {
  52097. this._setValue(this._target, currentValue, weight);
  52098. }
  52099. };
  52100. RuntimeAnimation.prototype._setValue = function (target, currentValue, weight, targetIndex) {
  52101. if (targetIndex === void 0) { targetIndex = 0; }
  52102. // Set value
  52103. var path;
  52104. var destination;
  52105. var targetPropertyPath = this._animation.targetPropertyPath;
  52106. if (targetPropertyPath.length > 1) {
  52107. var property = target[targetPropertyPath[0]];
  52108. for (var index = 1; index < targetPropertyPath.length - 1; index++) {
  52109. property = property[targetPropertyPath[index]];
  52110. }
  52111. path = targetPropertyPath[targetPropertyPath.length - 1];
  52112. destination = property;
  52113. }
  52114. else {
  52115. path = targetPropertyPath[0];
  52116. destination = target;
  52117. }
  52118. this._targetPath = path;
  52119. this._activeTarget = destination;
  52120. this._weight = weight;
  52121. if (this._originalValue[targetIndex] === undefined) {
  52122. var originalValue = void 0;
  52123. if (destination.getRestPose && path === "_matrix") { // For bones
  52124. originalValue = destination.getRestPose();
  52125. }
  52126. else {
  52127. originalValue = destination[path];
  52128. }
  52129. if (originalValue && originalValue.clone) {
  52130. this._originalValue[targetIndex] = originalValue.clone();
  52131. }
  52132. else {
  52133. this._originalValue[targetIndex] = originalValue;
  52134. }
  52135. }
  52136. // Blending
  52137. var enableBlending = target && target.animationPropertiesOverride ? target.animationPropertiesOverride.enableBlending : this._animation.enableBlending;
  52138. if (enableBlending && this._blendingFactor <= 1.0) {
  52139. if (!this._originalBlendValue) {
  52140. var originalValue = destination[path];
  52141. if (originalValue.clone) {
  52142. this._originalBlendValue = originalValue.clone();
  52143. }
  52144. else {
  52145. this._originalBlendValue = originalValue;
  52146. }
  52147. }
  52148. if (this._originalBlendValue.m) { // Matrix
  52149. if (BABYLON.Animation.AllowMatrixDecomposeForInterpolation) {
  52150. if (this._currentValue) {
  52151. BABYLON.Matrix.DecomposeLerpToRef(this._originalBlendValue, currentValue, this._blendingFactor, this._currentValue);
  52152. }
  52153. else {
  52154. this._currentValue = BABYLON.Matrix.DecomposeLerp(this._originalBlendValue, currentValue, this._blendingFactor);
  52155. }
  52156. }
  52157. else {
  52158. if (this._currentValue) {
  52159. BABYLON.Matrix.LerpToRef(this._originalBlendValue, currentValue, this._blendingFactor, this._currentValue);
  52160. }
  52161. else {
  52162. this._currentValue = BABYLON.Matrix.Lerp(this._originalBlendValue, currentValue, this._blendingFactor);
  52163. }
  52164. }
  52165. }
  52166. else {
  52167. this._currentValue = BABYLON.Animation._UniversalLerp(this._originalBlendValue, currentValue, this._blendingFactor);
  52168. }
  52169. var blendingSpeed = target && target.animationPropertiesOverride ? target.animationPropertiesOverride.blendingSpeed : this._animation.blendingSpeed;
  52170. this._blendingFactor += blendingSpeed;
  52171. }
  52172. else {
  52173. this._currentValue = currentValue;
  52174. }
  52175. if (weight !== -1.0) {
  52176. this._scene._registerTargetForLateAnimationBinding(this, this._originalValue[targetIndex]);
  52177. }
  52178. else {
  52179. destination[path] = this._currentValue;
  52180. }
  52181. if (target.markAsDirty) {
  52182. target.markAsDirty(this._animation.targetProperty);
  52183. }
  52184. };
  52185. /**
  52186. * Gets the loop pmode of the runtime animation
  52187. * @returns Loop Mode
  52188. */
  52189. RuntimeAnimation.prototype._getCorrectLoopMode = function () {
  52190. if (this._target && this._target.animationPropertiesOverride) {
  52191. return this._target.animationPropertiesOverride.loopMode;
  52192. }
  52193. return this._animation.loopMode;
  52194. };
  52195. /**
  52196. * Move the current animation to a given frame
  52197. * @param frame defines the frame to move to
  52198. */
  52199. RuntimeAnimation.prototype.goToFrame = function (frame) {
  52200. var keys = this._animation.getKeys();
  52201. if (frame < keys[0].frame) {
  52202. frame = keys[0].frame;
  52203. }
  52204. else if (frame > keys[keys.length - 1].frame) {
  52205. frame = keys[keys.length - 1].frame;
  52206. }
  52207. var currentValue = this._interpolate(frame, 0, this._getCorrectLoopMode());
  52208. this.setValue(currentValue, -1);
  52209. };
  52210. /**
  52211. * @hidden Internal use only
  52212. */
  52213. RuntimeAnimation.prototype._prepareForSpeedRatioChange = function (newSpeedRatio) {
  52214. var newRatio = this._previousDelay * (this._animation.framePerSecond * newSpeedRatio) / 1000.0;
  52215. this._ratioOffset = this._previousRatio - newRatio;
  52216. };
  52217. /**
  52218. * Execute the current animation
  52219. * @param delay defines the delay to add to the current frame
  52220. * @param from defines the lower bound of the animation range
  52221. * @param to defines the upper bound of the animation range
  52222. * @param loop defines if the current animation must loop
  52223. * @param speedRatio defines the current speed ratio
  52224. * @param weight defines the weight of the animation (default is -1 so no weight)
  52225. * @returns a boolean indicating if the animation has ended
  52226. */
  52227. RuntimeAnimation.prototype.animate = function (delay, from, to, loop, speedRatio, weight) {
  52228. if (weight === void 0) { weight = -1.0; }
  52229. var targetPropertyPath = this._animation.targetPropertyPath;
  52230. if (!targetPropertyPath || targetPropertyPath.length < 1) {
  52231. this._stopped = true;
  52232. return false;
  52233. }
  52234. var returnValue = true;
  52235. var keys = this._animation.getKeys();
  52236. // Adding a start key at frame 0 if missing
  52237. if (keys[0].frame !== 0) {
  52238. var newKey = { frame: 0, value: keys[0].value };
  52239. keys.splice(0, 0, newKey);
  52240. }
  52241. // Check limits
  52242. if (from < keys[0].frame || from > keys[keys.length - 1].frame) {
  52243. from = keys[0].frame;
  52244. }
  52245. if (to < keys[0].frame || to > keys[keys.length - 1].frame) {
  52246. to = keys[keys.length - 1].frame;
  52247. }
  52248. //to and from cannot be the same key
  52249. if (from === to) {
  52250. if (from > keys[0].frame) {
  52251. from--;
  52252. }
  52253. else if (to < keys[keys.length - 1].frame) {
  52254. to++;
  52255. }
  52256. }
  52257. // Compute ratio
  52258. var range = to - from;
  52259. var offsetValue;
  52260. // ratio represents the frame delta between from and to
  52261. var ratio = (delay * (this._animation.framePerSecond * speedRatio) / 1000.0) + this._ratioOffset;
  52262. var highLimitValue = 0;
  52263. this._previousDelay = delay;
  52264. this._previousRatio = ratio;
  52265. if (((to > from && ratio >= range) || (from > to && ratio <= range)) && !loop) { // If we are out of range and not looping get back to caller
  52266. returnValue = false;
  52267. highLimitValue = this._animation._getKeyValue(keys[keys.length - 1].value);
  52268. }
  52269. else {
  52270. // Get max value if required
  52271. if (this._getCorrectLoopMode() !== BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE) {
  52272. var keyOffset = to.toString() + from.toString();
  52273. if (!this._offsetsCache[keyOffset]) {
  52274. var fromValue = this._interpolate(from, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  52275. var toValue = this._interpolate(to, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  52276. switch (this._animation.dataType) {
  52277. // Float
  52278. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  52279. this._offsetsCache[keyOffset] = toValue - fromValue;
  52280. break;
  52281. // Quaternion
  52282. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  52283. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  52284. break;
  52285. // Vector3
  52286. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  52287. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  52288. // Vector2
  52289. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  52290. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  52291. // Size
  52292. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  52293. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  52294. // Color3
  52295. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  52296. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  52297. default:
  52298. break;
  52299. }
  52300. this._highLimitsCache[keyOffset] = toValue;
  52301. }
  52302. highLimitValue = this._highLimitsCache[keyOffset];
  52303. offsetValue = this._offsetsCache[keyOffset];
  52304. }
  52305. }
  52306. if (offsetValue === undefined) {
  52307. switch (this._animation.dataType) {
  52308. // Float
  52309. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  52310. offsetValue = 0;
  52311. break;
  52312. // Quaternion
  52313. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  52314. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  52315. break;
  52316. // Vector3
  52317. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  52318. offsetValue = BABYLON.Vector3.Zero();
  52319. break;
  52320. // Vector2
  52321. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  52322. offsetValue = BABYLON.Vector2.Zero();
  52323. break;
  52324. // Size
  52325. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  52326. offsetValue = BABYLON.Size.Zero();
  52327. break;
  52328. // Color3
  52329. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  52330. offsetValue = BABYLON.Color3.Black();
  52331. }
  52332. }
  52333. // Compute value
  52334. var repeatCount = (ratio / range) >> 0;
  52335. var currentFrame = returnValue ? from + ratio % range : to;
  52336. // Need to normalize?
  52337. if (this._host && this._host.syncRoot) {
  52338. var syncRoot = this._host.syncRoot;
  52339. var hostNormalizedFrame = (syncRoot.masterFrame - syncRoot.fromFrame) / (syncRoot.toFrame - syncRoot.fromFrame);
  52340. currentFrame = from + (to - from) * hostNormalizedFrame;
  52341. }
  52342. // Reset events if looping
  52343. var events = this._events;
  52344. if (range > 0 && this.currentFrame > currentFrame ||
  52345. range < 0 && this.currentFrame < currentFrame) {
  52346. // Need to reset animation events
  52347. for (var index = 0; index < events.length; index++) {
  52348. if (!events[index].onlyOnce) {
  52349. // reset event, the animation is looping
  52350. events[index].isDone = false;
  52351. }
  52352. }
  52353. }
  52354. var currentValue = this._interpolate(currentFrame, repeatCount, this._getCorrectLoopMode(), offsetValue, highLimitValue);
  52355. // Set value
  52356. this.setValue(currentValue, weight);
  52357. // Check events
  52358. for (var index = 0; index < events.length; index++) {
  52359. // Make sure current frame has passed event frame and that event frame is within the current range
  52360. // Also, handle both forward and reverse animations
  52361. if ((range > 0 && currentFrame >= events[index].frame && events[index].frame >= from) ||
  52362. (range < 0 && currentFrame <= events[index].frame && events[index].frame <= from)) {
  52363. var event = events[index];
  52364. if (!event.isDone) {
  52365. // If event should be done only once, remove it.
  52366. if (event.onlyOnce) {
  52367. events.splice(index, 1);
  52368. index--;
  52369. }
  52370. event.isDone = true;
  52371. event.action();
  52372. } // Don't do anything if the event has already be done.
  52373. }
  52374. }
  52375. if (!returnValue) {
  52376. this._stopped = true;
  52377. }
  52378. return returnValue;
  52379. };
  52380. return RuntimeAnimation;
  52381. }());
  52382. BABYLON.RuntimeAnimation = RuntimeAnimation;
  52383. })(BABYLON || (BABYLON = {}));
  52384. //# sourceMappingURL=babylon.runtimeAnimation.js.map
  52385. var BABYLON;
  52386. (function (BABYLON) {
  52387. var Animatable = /** @class */ (function () {
  52388. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  52389. if (fromFrame === void 0) { fromFrame = 0; }
  52390. if (toFrame === void 0) { toFrame = 100; }
  52391. if (loopAnimation === void 0) { loopAnimation = false; }
  52392. if (speedRatio === void 0) { speedRatio = 1.0; }
  52393. this.target = target;
  52394. this.fromFrame = fromFrame;
  52395. this.toFrame = toFrame;
  52396. this.loopAnimation = loopAnimation;
  52397. this.onAnimationEnd = onAnimationEnd;
  52398. this._localDelayOffset = null;
  52399. this._pausedDelay = null;
  52400. this._runtimeAnimations = new Array();
  52401. this._paused = false;
  52402. this._speedRatio = 1;
  52403. this._weight = -1.0;
  52404. this.animationStarted = false;
  52405. /**
  52406. * Observer raised when the animation ends
  52407. */
  52408. this.onAnimationEndObservable = new BABYLON.Observable();
  52409. this._scene = scene;
  52410. if (animations) {
  52411. this.appendAnimations(target, animations);
  52412. }
  52413. this._speedRatio = speedRatio;
  52414. scene._activeAnimatables.push(this);
  52415. }
  52416. Object.defineProperty(Animatable.prototype, "syncRoot", {
  52417. /**
  52418. * Gets the root Animatable used to synchronize and normalize animations
  52419. */
  52420. get: function () {
  52421. return this._syncRoot;
  52422. },
  52423. enumerable: true,
  52424. configurable: true
  52425. });
  52426. Object.defineProperty(Animatable.prototype, "masterFrame", {
  52427. /**
  52428. * Gets the current frame of the first RuntimeAnimation
  52429. * Used to synchronize Animatables
  52430. */
  52431. get: function () {
  52432. if (this._runtimeAnimations.length === 0) {
  52433. return 0;
  52434. }
  52435. return this._runtimeAnimations[0].currentFrame;
  52436. },
  52437. enumerable: true,
  52438. configurable: true
  52439. });
  52440. Object.defineProperty(Animatable.prototype, "weight", {
  52441. /**
  52442. * Gets or sets the animatable weight (-1.0 by default meaning not weighted)
  52443. */
  52444. get: function () {
  52445. return this._weight;
  52446. },
  52447. set: function (value) {
  52448. if (value === -1) { // -1 is ok and means no weight
  52449. this._weight = -1;
  52450. return;
  52451. }
  52452. // Else weight must be in [0, 1] range
  52453. this._weight = Math.min(Math.max(value, 0), 1.0);
  52454. },
  52455. enumerable: true,
  52456. configurable: true
  52457. });
  52458. Object.defineProperty(Animatable.prototype, "speedRatio", {
  52459. /**
  52460. * Gets or sets the speed ratio to apply to the animatable (1.0 by default)
  52461. */
  52462. get: function () {
  52463. return this._speedRatio;
  52464. },
  52465. set: function (value) {
  52466. for (var index = 0; index < this._runtimeAnimations.length; index++) {
  52467. var animation = this._runtimeAnimations[index];
  52468. animation._prepareForSpeedRatioChange(value);
  52469. }
  52470. this._speedRatio = value;
  52471. },
  52472. enumerable: true,
  52473. configurable: true
  52474. });
  52475. // Methods
  52476. /**
  52477. * Synchronize and normalize current Animatable with a source Animatable
  52478. * This is useful when using animation weights and when animations are not of the same length
  52479. * @param root defines the root Animatable to synchronize with
  52480. * @returns the current Animatable
  52481. */
  52482. Animatable.prototype.syncWith = function (root) {
  52483. this._syncRoot = root;
  52484. if (root) {
  52485. // Make sure this animatable will animate after the root
  52486. var index = this._scene._activeAnimatables.indexOf(this);
  52487. if (index > -1) {
  52488. this._scene._activeAnimatables.splice(index, 1);
  52489. this._scene._activeAnimatables.push(this);
  52490. }
  52491. }
  52492. return this;
  52493. };
  52494. Animatable.prototype.getAnimations = function () {
  52495. return this._runtimeAnimations;
  52496. };
  52497. Animatable.prototype.appendAnimations = function (target, animations) {
  52498. for (var index = 0; index < animations.length; index++) {
  52499. var animation = animations[index];
  52500. this._runtimeAnimations.push(new BABYLON.RuntimeAnimation(target, animation, this._scene, this));
  52501. }
  52502. };
  52503. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  52504. var runtimeAnimations = this._runtimeAnimations;
  52505. for (var index = 0; index < runtimeAnimations.length; index++) {
  52506. if (runtimeAnimations[index].animation.targetProperty === property) {
  52507. return runtimeAnimations[index].animation;
  52508. }
  52509. }
  52510. return null;
  52511. };
  52512. Animatable.prototype.getRuntimeAnimationByTargetProperty = function (property) {
  52513. var runtimeAnimations = this._runtimeAnimations;
  52514. for (var index = 0; index < runtimeAnimations.length; index++) {
  52515. if (runtimeAnimations[index].animation.targetProperty === property) {
  52516. return runtimeAnimations[index];
  52517. }
  52518. }
  52519. return null;
  52520. };
  52521. Animatable.prototype.reset = function () {
  52522. var runtimeAnimations = this._runtimeAnimations;
  52523. for (var index = 0; index < runtimeAnimations.length; index++) {
  52524. runtimeAnimations[index].reset(true);
  52525. }
  52526. this._localDelayOffset = null;
  52527. this._pausedDelay = null;
  52528. };
  52529. Animatable.prototype.enableBlending = function (blendingSpeed) {
  52530. var runtimeAnimations = this._runtimeAnimations;
  52531. for (var index = 0; index < runtimeAnimations.length; index++) {
  52532. runtimeAnimations[index].animation.enableBlending = true;
  52533. runtimeAnimations[index].animation.blendingSpeed = blendingSpeed;
  52534. }
  52535. };
  52536. Animatable.prototype.disableBlending = function () {
  52537. var runtimeAnimations = this._runtimeAnimations;
  52538. for (var index = 0; index < runtimeAnimations.length; index++) {
  52539. runtimeAnimations[index].animation.enableBlending = false;
  52540. }
  52541. };
  52542. Animatable.prototype.goToFrame = function (frame) {
  52543. var runtimeAnimations = this._runtimeAnimations;
  52544. if (runtimeAnimations[0]) {
  52545. var fps = runtimeAnimations[0].animation.framePerSecond;
  52546. var currentFrame = runtimeAnimations[0].currentFrame;
  52547. var adjustTime = frame - currentFrame;
  52548. var delay = adjustTime * 1000 / (fps * this.speedRatio);
  52549. if (this._localDelayOffset === null) {
  52550. this._localDelayOffset = 0;
  52551. }
  52552. this._localDelayOffset -= delay;
  52553. }
  52554. for (var index = 0; index < runtimeAnimations.length; index++) {
  52555. runtimeAnimations[index].goToFrame(frame);
  52556. }
  52557. };
  52558. Animatable.prototype.pause = function () {
  52559. if (this._paused) {
  52560. return;
  52561. }
  52562. this._paused = true;
  52563. };
  52564. Animatable.prototype.restart = function () {
  52565. this._paused = false;
  52566. };
  52567. Animatable.prototype._raiseOnAnimationEnd = function () {
  52568. if (this.onAnimationEnd) {
  52569. this.onAnimationEnd();
  52570. }
  52571. this.onAnimationEndObservable.notifyObservers(this);
  52572. };
  52573. Animatable.prototype.stop = function (animationName) {
  52574. if (animationName) {
  52575. var idx = this._scene._activeAnimatables.indexOf(this);
  52576. if (idx > -1) {
  52577. var runtimeAnimations = this._runtimeAnimations;
  52578. for (var index = runtimeAnimations.length - 1; index >= 0; index--) {
  52579. if (typeof animationName === "string" && runtimeAnimations[index].animation.name != animationName) {
  52580. continue;
  52581. }
  52582. runtimeAnimations[index].dispose();
  52583. runtimeAnimations.splice(index, 1);
  52584. }
  52585. if (runtimeAnimations.length == 0) {
  52586. this._scene._activeAnimatables.splice(idx, 1);
  52587. this._raiseOnAnimationEnd();
  52588. }
  52589. }
  52590. }
  52591. else {
  52592. var index = this._scene._activeAnimatables.indexOf(this);
  52593. if (index > -1) {
  52594. this._scene._activeAnimatables.splice(index, 1);
  52595. var runtimeAnimations = this._runtimeAnimations;
  52596. for (var index = 0; index < runtimeAnimations.length; index++) {
  52597. runtimeAnimations[index].dispose();
  52598. }
  52599. this._raiseOnAnimationEnd();
  52600. }
  52601. }
  52602. };
  52603. /**
  52604. * Wait asynchronously for the animation to end
  52605. * @returns a promise which will be fullfilled when the animation ends
  52606. */
  52607. Animatable.prototype.waitAsync = function () {
  52608. var _this = this;
  52609. return new Promise(function (resolve, reject) {
  52610. _this.onAnimationEndObservable.add(function () {
  52611. resolve(_this);
  52612. }, undefined, undefined, _this, true);
  52613. });
  52614. };
  52615. /** @hidden */
  52616. Animatable.prototype._animate = function (delay) {
  52617. if (this._paused) {
  52618. this.animationStarted = false;
  52619. if (this._pausedDelay === null) {
  52620. this._pausedDelay = delay;
  52621. }
  52622. return true;
  52623. }
  52624. if (this._localDelayOffset === null) {
  52625. this._localDelayOffset = delay;
  52626. this._pausedDelay = null;
  52627. }
  52628. else if (this._pausedDelay !== null) {
  52629. this._localDelayOffset += delay - this._pausedDelay;
  52630. this._pausedDelay = null;
  52631. }
  52632. if (this._weight === 0) { // We consider that an animation with a weight === 0 is "actively" paused
  52633. return true;
  52634. }
  52635. // Animating
  52636. var running = false;
  52637. var runtimeAnimations = this._runtimeAnimations;
  52638. var index;
  52639. for (index = 0; index < runtimeAnimations.length; index++) {
  52640. var animation = runtimeAnimations[index];
  52641. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this._speedRatio, this._weight);
  52642. running = running || isRunning;
  52643. }
  52644. this.animationStarted = running;
  52645. if (!running) {
  52646. // Remove from active animatables
  52647. index = this._scene._activeAnimatables.indexOf(this);
  52648. this._scene._activeAnimatables.splice(index, 1);
  52649. // Dispose all runtime animations
  52650. for (index = 0; index < runtimeAnimations.length; index++) {
  52651. runtimeAnimations[index].dispose();
  52652. }
  52653. this._raiseOnAnimationEnd();
  52654. this.onAnimationEnd = null;
  52655. this.onAnimationEndObservable.clear();
  52656. }
  52657. return running;
  52658. };
  52659. return Animatable;
  52660. }());
  52661. BABYLON.Animatable = Animatable;
  52662. })(BABYLON || (BABYLON = {}));
  52663. //# sourceMappingURL=babylon.animatable.js.map
  52664. var BABYLON;
  52665. (function (BABYLON) {
  52666. var EasingFunction = /** @class */ (function () {
  52667. function EasingFunction() {
  52668. // Properties
  52669. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  52670. }
  52671. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  52672. get: function () {
  52673. return EasingFunction._EASINGMODE_EASEIN;
  52674. },
  52675. enumerable: true,
  52676. configurable: true
  52677. });
  52678. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  52679. get: function () {
  52680. return EasingFunction._EASINGMODE_EASEOUT;
  52681. },
  52682. enumerable: true,
  52683. configurable: true
  52684. });
  52685. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  52686. get: function () {
  52687. return EasingFunction._EASINGMODE_EASEINOUT;
  52688. },
  52689. enumerable: true,
  52690. configurable: true
  52691. });
  52692. EasingFunction.prototype.setEasingMode = function (easingMode) {
  52693. var n = Math.min(Math.max(easingMode, 0), 2);
  52694. this._easingMode = n;
  52695. };
  52696. EasingFunction.prototype.getEasingMode = function () {
  52697. return this._easingMode;
  52698. };
  52699. EasingFunction.prototype.easeInCore = function (gradient) {
  52700. throw new Error('You must implement this method');
  52701. };
  52702. EasingFunction.prototype.ease = function (gradient) {
  52703. switch (this._easingMode) {
  52704. case EasingFunction.EASINGMODE_EASEIN:
  52705. return this.easeInCore(gradient);
  52706. case EasingFunction.EASINGMODE_EASEOUT:
  52707. return (1 - this.easeInCore(1 - gradient));
  52708. }
  52709. if (gradient >= 0.5) {
  52710. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  52711. }
  52712. return (this.easeInCore(gradient * 2) * 0.5);
  52713. };
  52714. //Statics
  52715. EasingFunction._EASINGMODE_EASEIN = 0;
  52716. EasingFunction._EASINGMODE_EASEOUT = 1;
  52717. EasingFunction._EASINGMODE_EASEINOUT = 2;
  52718. return EasingFunction;
  52719. }());
  52720. BABYLON.EasingFunction = EasingFunction;
  52721. var CircleEase = /** @class */ (function (_super) {
  52722. __extends(CircleEase, _super);
  52723. function CircleEase() {
  52724. return _super !== null && _super.apply(this, arguments) || this;
  52725. }
  52726. CircleEase.prototype.easeInCore = function (gradient) {
  52727. gradient = Math.max(0, Math.min(1, gradient));
  52728. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  52729. };
  52730. return CircleEase;
  52731. }(EasingFunction));
  52732. BABYLON.CircleEase = CircleEase;
  52733. var BackEase = /** @class */ (function (_super) {
  52734. __extends(BackEase, _super);
  52735. function BackEase(amplitude) {
  52736. if (amplitude === void 0) { amplitude = 1; }
  52737. var _this = _super.call(this) || this;
  52738. _this.amplitude = amplitude;
  52739. return _this;
  52740. }
  52741. BackEase.prototype.easeInCore = function (gradient) {
  52742. var num = Math.max(0, this.amplitude);
  52743. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  52744. };
  52745. return BackEase;
  52746. }(EasingFunction));
  52747. BABYLON.BackEase = BackEase;
  52748. var BounceEase = /** @class */ (function (_super) {
  52749. __extends(BounceEase, _super);
  52750. function BounceEase(bounces, bounciness) {
  52751. if (bounces === void 0) { bounces = 3; }
  52752. if (bounciness === void 0) { bounciness = 2; }
  52753. var _this = _super.call(this) || this;
  52754. _this.bounces = bounces;
  52755. _this.bounciness = bounciness;
  52756. return _this;
  52757. }
  52758. BounceEase.prototype.easeInCore = function (gradient) {
  52759. var y = Math.max(0.0, this.bounces);
  52760. var bounciness = this.bounciness;
  52761. if (bounciness <= 1.0) {
  52762. bounciness = 1.001;
  52763. }
  52764. var num9 = Math.pow(bounciness, y);
  52765. var num5 = 1.0 - bounciness;
  52766. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  52767. var num15 = gradient * num4;
  52768. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  52769. var num3 = Math.floor(num65);
  52770. var num13 = num3 + 1.0;
  52771. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  52772. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  52773. var num7 = (num8 + num12) * 0.5;
  52774. var num6 = gradient - num7;
  52775. var num2 = num7 - num8;
  52776. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  52777. };
  52778. return BounceEase;
  52779. }(EasingFunction));
  52780. BABYLON.BounceEase = BounceEase;
  52781. var CubicEase = /** @class */ (function (_super) {
  52782. __extends(CubicEase, _super);
  52783. function CubicEase() {
  52784. return _super !== null && _super.apply(this, arguments) || this;
  52785. }
  52786. CubicEase.prototype.easeInCore = function (gradient) {
  52787. return (gradient * gradient * gradient);
  52788. };
  52789. return CubicEase;
  52790. }(EasingFunction));
  52791. BABYLON.CubicEase = CubicEase;
  52792. var ElasticEase = /** @class */ (function (_super) {
  52793. __extends(ElasticEase, _super);
  52794. function ElasticEase(oscillations, springiness) {
  52795. if (oscillations === void 0) { oscillations = 3; }
  52796. if (springiness === void 0) { springiness = 3; }
  52797. var _this = _super.call(this) || this;
  52798. _this.oscillations = oscillations;
  52799. _this.springiness = springiness;
  52800. return _this;
  52801. }
  52802. ElasticEase.prototype.easeInCore = function (gradient) {
  52803. var num2;
  52804. var num3 = Math.max(0.0, this.oscillations);
  52805. var num = Math.max(0.0, this.springiness);
  52806. if (num == 0) {
  52807. num2 = gradient;
  52808. }
  52809. else {
  52810. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  52811. }
  52812. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  52813. };
  52814. return ElasticEase;
  52815. }(EasingFunction));
  52816. BABYLON.ElasticEase = ElasticEase;
  52817. var ExponentialEase = /** @class */ (function (_super) {
  52818. __extends(ExponentialEase, _super);
  52819. function ExponentialEase(exponent) {
  52820. if (exponent === void 0) { exponent = 2; }
  52821. var _this = _super.call(this) || this;
  52822. _this.exponent = exponent;
  52823. return _this;
  52824. }
  52825. ExponentialEase.prototype.easeInCore = function (gradient) {
  52826. if (this.exponent <= 0) {
  52827. return gradient;
  52828. }
  52829. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  52830. };
  52831. return ExponentialEase;
  52832. }(EasingFunction));
  52833. BABYLON.ExponentialEase = ExponentialEase;
  52834. var PowerEase = /** @class */ (function (_super) {
  52835. __extends(PowerEase, _super);
  52836. function PowerEase(power) {
  52837. if (power === void 0) { power = 2; }
  52838. var _this = _super.call(this) || this;
  52839. _this.power = power;
  52840. return _this;
  52841. }
  52842. PowerEase.prototype.easeInCore = function (gradient) {
  52843. var y = Math.max(0.0, this.power);
  52844. return Math.pow(gradient, y);
  52845. };
  52846. return PowerEase;
  52847. }(EasingFunction));
  52848. BABYLON.PowerEase = PowerEase;
  52849. var QuadraticEase = /** @class */ (function (_super) {
  52850. __extends(QuadraticEase, _super);
  52851. function QuadraticEase() {
  52852. return _super !== null && _super.apply(this, arguments) || this;
  52853. }
  52854. QuadraticEase.prototype.easeInCore = function (gradient) {
  52855. return (gradient * gradient);
  52856. };
  52857. return QuadraticEase;
  52858. }(EasingFunction));
  52859. BABYLON.QuadraticEase = QuadraticEase;
  52860. var QuarticEase = /** @class */ (function (_super) {
  52861. __extends(QuarticEase, _super);
  52862. function QuarticEase() {
  52863. return _super !== null && _super.apply(this, arguments) || this;
  52864. }
  52865. QuarticEase.prototype.easeInCore = function (gradient) {
  52866. return (gradient * gradient * gradient * gradient);
  52867. };
  52868. return QuarticEase;
  52869. }(EasingFunction));
  52870. BABYLON.QuarticEase = QuarticEase;
  52871. var QuinticEase = /** @class */ (function (_super) {
  52872. __extends(QuinticEase, _super);
  52873. function QuinticEase() {
  52874. return _super !== null && _super.apply(this, arguments) || this;
  52875. }
  52876. QuinticEase.prototype.easeInCore = function (gradient) {
  52877. return (gradient * gradient * gradient * gradient * gradient);
  52878. };
  52879. return QuinticEase;
  52880. }(EasingFunction));
  52881. BABYLON.QuinticEase = QuinticEase;
  52882. var SineEase = /** @class */ (function (_super) {
  52883. __extends(SineEase, _super);
  52884. function SineEase() {
  52885. return _super !== null && _super.apply(this, arguments) || this;
  52886. }
  52887. SineEase.prototype.easeInCore = function (gradient) {
  52888. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  52889. };
  52890. return SineEase;
  52891. }(EasingFunction));
  52892. BABYLON.SineEase = SineEase;
  52893. var BezierCurveEase = /** @class */ (function (_super) {
  52894. __extends(BezierCurveEase, _super);
  52895. function BezierCurveEase(x1, y1, x2, y2) {
  52896. if (x1 === void 0) { x1 = 0; }
  52897. if (y1 === void 0) { y1 = 0; }
  52898. if (x2 === void 0) { x2 = 1; }
  52899. if (y2 === void 0) { y2 = 1; }
  52900. var _this = _super.call(this) || this;
  52901. _this.x1 = x1;
  52902. _this.y1 = y1;
  52903. _this.x2 = x2;
  52904. _this.y2 = y2;
  52905. return _this;
  52906. }
  52907. BezierCurveEase.prototype.easeInCore = function (gradient) {
  52908. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  52909. };
  52910. return BezierCurveEase;
  52911. }(EasingFunction));
  52912. BABYLON.BezierCurveEase = BezierCurveEase;
  52913. })(BABYLON || (BABYLON = {}));
  52914. //# sourceMappingURL=babylon.easing.js.map
  52915. var BABYLON;
  52916. (function (BABYLON) {
  52917. /**
  52918. * A Condition applied to an Action
  52919. */
  52920. var Condition = /** @class */ (function () {
  52921. /**
  52922. * Creates a new Condition
  52923. * @param actionManager the manager of the action the condition is applied to
  52924. */
  52925. function Condition(actionManager) {
  52926. this._actionManager = actionManager;
  52927. }
  52928. /**
  52929. * Check if the current condition is valid
  52930. * @returns a boolean
  52931. */
  52932. Condition.prototype.isValid = function () {
  52933. return true;
  52934. };
  52935. /**
  52936. * Internal only
  52937. * @hidden
  52938. */
  52939. Condition.prototype._getProperty = function (propertyPath) {
  52940. return this._actionManager._getProperty(propertyPath);
  52941. };
  52942. /**
  52943. * Internal only
  52944. * @hidden
  52945. */
  52946. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  52947. return this._actionManager._getEffectiveTarget(target, propertyPath);
  52948. };
  52949. /**
  52950. * Serialize placeholder for child classes
  52951. * @returns the serialized object
  52952. */
  52953. Condition.prototype.serialize = function () {
  52954. };
  52955. /**
  52956. * Internal only
  52957. * @hidden
  52958. */
  52959. Condition.prototype._serialize = function (serializedCondition) {
  52960. return {
  52961. type: 2,
  52962. children: [],
  52963. name: serializedCondition.name,
  52964. properties: serializedCondition.properties
  52965. };
  52966. };
  52967. return Condition;
  52968. }());
  52969. BABYLON.Condition = Condition;
  52970. /**
  52971. * Defines specific conditional operators as extensions of Condition
  52972. */
  52973. var ValueCondition = /** @class */ (function (_super) {
  52974. __extends(ValueCondition, _super);
  52975. /**
  52976. * Creates a new ValueCondition
  52977. * @param actionManager manager for the action the condition applies to
  52978. * @param target for the action
  52979. * @param propertyPath path to specify the property of the target the conditional operator uses
  52980. * @param value the value compared by the conditional operator against the current value of the property
  52981. * @param operator the conditional operator, default ValueCondition.IsEqual
  52982. */
  52983. function ValueCondition(actionManager, target,
  52984. /** path to specify the property of the target the conditional operator uses */
  52985. propertyPath,
  52986. /** the value compared by the conditional operator against the current value of the property */
  52987. value,
  52988. /** the conditional operator, default ValueCondition.IsEqual */
  52989. operator) {
  52990. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  52991. var _this = _super.call(this, actionManager) || this;
  52992. _this.propertyPath = propertyPath;
  52993. _this.value = value;
  52994. _this.operator = operator;
  52995. _this._target = target;
  52996. _this._effectiveTarget = _this._getEffectiveTarget(target, _this.propertyPath);
  52997. _this._property = _this._getProperty(_this.propertyPath);
  52998. return _this;
  52999. }
  53000. Object.defineProperty(ValueCondition, "IsEqual", {
  53001. /**
  53002. * returns the number for IsEqual
  53003. */
  53004. get: function () {
  53005. return ValueCondition._IsEqual;
  53006. },
  53007. enumerable: true,
  53008. configurable: true
  53009. });
  53010. Object.defineProperty(ValueCondition, "IsDifferent", {
  53011. /**
  53012. * Returns the number for IsDifferent
  53013. */
  53014. get: function () {
  53015. return ValueCondition._IsDifferent;
  53016. },
  53017. enumerable: true,
  53018. configurable: true
  53019. });
  53020. Object.defineProperty(ValueCondition, "IsGreater", {
  53021. /**
  53022. * Returns the number for IsGreater
  53023. */
  53024. get: function () {
  53025. return ValueCondition._IsGreater;
  53026. },
  53027. enumerable: true,
  53028. configurable: true
  53029. });
  53030. Object.defineProperty(ValueCondition, "IsLesser", {
  53031. /**
  53032. * Returns the number for IsLesser
  53033. */
  53034. get: function () {
  53035. return ValueCondition._IsLesser;
  53036. },
  53037. enumerable: true,
  53038. configurable: true
  53039. });
  53040. /**
  53041. * Compares the given value with the property value for the specified conditional operator
  53042. * @returns the result of the comparison
  53043. */
  53044. ValueCondition.prototype.isValid = function () {
  53045. switch (this.operator) {
  53046. case ValueCondition.IsGreater:
  53047. return this._effectiveTarget[this._property] > this.value;
  53048. case ValueCondition.IsLesser:
  53049. return this._effectiveTarget[this._property] < this.value;
  53050. case ValueCondition.IsEqual:
  53051. case ValueCondition.IsDifferent:
  53052. var check;
  53053. if (this.value.equals) {
  53054. check = this.value.equals(this._effectiveTarget[this._property]);
  53055. }
  53056. else {
  53057. check = this.value === this._effectiveTarget[this._property];
  53058. }
  53059. return this.operator === ValueCondition.IsEqual ? check : !check;
  53060. }
  53061. return false;
  53062. };
  53063. /**
  53064. * Serialize the ValueCondition into a JSON compatible object
  53065. * @returns serialization object
  53066. */
  53067. ValueCondition.prototype.serialize = function () {
  53068. return this._serialize({
  53069. name: "ValueCondition",
  53070. properties: [
  53071. BABYLON.Action._GetTargetProperty(this._target),
  53072. { name: "propertyPath", value: this.propertyPath },
  53073. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  53074. { name: "operator", value: ValueCondition.GetOperatorName(this.operator) }
  53075. ]
  53076. });
  53077. };
  53078. /**
  53079. * Gets the name of the conditional operator for the ValueCondition
  53080. * @param operator the conditional operator
  53081. * @returns the name
  53082. */
  53083. ValueCondition.GetOperatorName = function (operator) {
  53084. switch (operator) {
  53085. case ValueCondition._IsEqual: return "IsEqual";
  53086. case ValueCondition._IsDifferent: return "IsDifferent";
  53087. case ValueCondition._IsGreater: return "IsGreater";
  53088. case ValueCondition._IsLesser: return "IsLesser";
  53089. default: return "";
  53090. }
  53091. };
  53092. /**
  53093. * Internal only
  53094. * @hidden
  53095. */
  53096. ValueCondition._IsEqual = 0;
  53097. /**
  53098. * Internal only
  53099. * @hidden
  53100. */
  53101. ValueCondition._IsDifferent = 1;
  53102. /**
  53103. * Internal only
  53104. * @hidden
  53105. */
  53106. ValueCondition._IsGreater = 2;
  53107. /**
  53108. * Internal only
  53109. * @hidden
  53110. */
  53111. ValueCondition._IsLesser = 3;
  53112. return ValueCondition;
  53113. }(Condition));
  53114. BABYLON.ValueCondition = ValueCondition;
  53115. /**
  53116. * Defines a predicate condition as an extension of Condition
  53117. */
  53118. var PredicateCondition = /** @class */ (function (_super) {
  53119. __extends(PredicateCondition, _super);
  53120. /**
  53121. * Creates a new PredicateCondition
  53122. * @param actionManager manager for the action the condition applies to
  53123. * @param predicate defines the predicate function used to validate the condition
  53124. */
  53125. function PredicateCondition(actionManager,
  53126. /** defines the predicate function used to validate the condition */
  53127. predicate) {
  53128. var _this = _super.call(this, actionManager) || this;
  53129. _this.predicate = predicate;
  53130. return _this;
  53131. }
  53132. /**
  53133. * @returns the validity of the predicate condition
  53134. */
  53135. PredicateCondition.prototype.isValid = function () {
  53136. return this.predicate();
  53137. };
  53138. return PredicateCondition;
  53139. }(Condition));
  53140. BABYLON.PredicateCondition = PredicateCondition;
  53141. /**
  53142. * Defines a state condition as an extension of Condition
  53143. */
  53144. var StateCondition = /** @class */ (function (_super) {
  53145. __extends(StateCondition, _super);
  53146. /**
  53147. * Creates a new StateCondition
  53148. * @param actionManager manager for the action the condition applies to
  53149. * @param target of the condition
  53150. * @param value to compare with target state
  53151. */
  53152. function StateCondition(actionManager, target, value) {
  53153. var _this = _super.call(this, actionManager) || this;
  53154. _this.value = value;
  53155. _this._target = target;
  53156. return _this;
  53157. }
  53158. /**
  53159. * @returns the validity of the state
  53160. */
  53161. StateCondition.prototype.isValid = function () {
  53162. return this._target.state === this.value;
  53163. };
  53164. /**
  53165. * Serialize the StateCondition into a JSON compatible object
  53166. * @returns serialization object
  53167. */
  53168. StateCondition.prototype.serialize = function () {
  53169. return this._serialize({
  53170. name: "StateCondition",
  53171. properties: [
  53172. BABYLON.Action._GetTargetProperty(this._target),
  53173. { name: "value", value: this.value }
  53174. ]
  53175. });
  53176. };
  53177. return StateCondition;
  53178. }(Condition));
  53179. BABYLON.StateCondition = StateCondition;
  53180. })(BABYLON || (BABYLON = {}));
  53181. //# sourceMappingURL=babylon.condition.js.map
  53182. var BABYLON;
  53183. (function (BABYLON) {
  53184. /**
  53185. * The action to be carried out following a trigger
  53186. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#available-actions
  53187. */
  53188. var Action = /** @class */ (function () {
  53189. /**
  53190. * Creates a new Action
  53191. * @param triggerOptions the trigger, with or without parameters, for the action
  53192. * @param condition an optional determinant of action
  53193. */
  53194. function Action(
  53195. /** the trigger, with or without parameters, for the action */
  53196. triggerOptions, condition) {
  53197. this.triggerOptions = triggerOptions;
  53198. /**
  53199. * An event triggered prior to action being executed.
  53200. */
  53201. this.onBeforeExecuteObservable = new BABYLON.Observable();
  53202. if (triggerOptions.parameter) {
  53203. this.trigger = triggerOptions.trigger;
  53204. this._triggerParameter = triggerOptions.parameter;
  53205. }
  53206. else {
  53207. this.trigger = triggerOptions;
  53208. }
  53209. this._nextActiveAction = this;
  53210. this._condition = condition;
  53211. }
  53212. /**
  53213. * Internal only
  53214. * @hidden
  53215. */
  53216. Action.prototype._prepare = function () {
  53217. };
  53218. /**
  53219. * Gets the trigger parameters
  53220. * @returns the trigger parameters
  53221. */
  53222. Action.prototype.getTriggerParameter = function () {
  53223. return this._triggerParameter;
  53224. };
  53225. /**
  53226. * Internal only - executes current action event
  53227. * @hidden
  53228. */
  53229. Action.prototype._executeCurrent = function (evt) {
  53230. if (this._nextActiveAction._condition) {
  53231. var condition = this._nextActiveAction._condition;
  53232. var currentRenderId = this._actionManager.getScene().getRenderId();
  53233. // We cache the current evaluation for the current frame
  53234. if (condition._evaluationId === currentRenderId) {
  53235. if (!condition._currentResult) {
  53236. return;
  53237. }
  53238. }
  53239. else {
  53240. condition._evaluationId = currentRenderId;
  53241. if (!condition.isValid()) {
  53242. condition._currentResult = false;
  53243. return;
  53244. }
  53245. condition._currentResult = true;
  53246. }
  53247. }
  53248. this.onBeforeExecuteObservable.notifyObservers(this);
  53249. this._nextActiveAction.execute(evt);
  53250. this.skipToNextActiveAction();
  53251. };
  53252. /**
  53253. * Execute placeholder for child classes
  53254. * @param evt optional action event
  53255. */
  53256. Action.prototype.execute = function (evt) {
  53257. };
  53258. /**
  53259. * Skips to next active action
  53260. */
  53261. Action.prototype.skipToNextActiveAction = function () {
  53262. if (this._nextActiveAction._child) {
  53263. if (!this._nextActiveAction._child._actionManager) {
  53264. this._nextActiveAction._child._actionManager = this._actionManager;
  53265. }
  53266. this._nextActiveAction = this._nextActiveAction._child;
  53267. }
  53268. else {
  53269. this._nextActiveAction = this;
  53270. }
  53271. };
  53272. /**
  53273. * Adds action to chain of actions, may be a DoNothingAction
  53274. * @param action defines the next action to execute
  53275. * @returns The action passed in
  53276. * @see https://www.babylonjs-playground.com/#1T30HR#0
  53277. */
  53278. Action.prototype.then = function (action) {
  53279. this._child = action;
  53280. action._actionManager = this._actionManager;
  53281. action._prepare();
  53282. return action;
  53283. };
  53284. /**
  53285. * Internal only
  53286. * @hidden
  53287. */
  53288. Action.prototype._getProperty = function (propertyPath) {
  53289. return this._actionManager._getProperty(propertyPath);
  53290. };
  53291. /**
  53292. * Internal only
  53293. * @hidden
  53294. */
  53295. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  53296. return this._actionManager._getEffectiveTarget(target, propertyPath);
  53297. };
  53298. /**
  53299. * Serialize placeholder for child classes
  53300. * @param parent of child
  53301. * @returns the serialized object
  53302. */
  53303. Action.prototype.serialize = function (parent) {
  53304. };
  53305. /**
  53306. * Internal only called by serialize
  53307. * @hidden
  53308. */
  53309. Action.prototype._serialize = function (serializedAction, parent) {
  53310. var serializationObject = {
  53311. type: 1,
  53312. children: [],
  53313. name: serializedAction.name,
  53314. properties: serializedAction.properties || []
  53315. };
  53316. // Serialize child
  53317. if (this._child) {
  53318. this._child.serialize(serializationObject);
  53319. }
  53320. // Check if "this" has a condition
  53321. if (this._condition) {
  53322. var serializedCondition = this._condition.serialize();
  53323. serializedCondition.children.push(serializationObject);
  53324. if (parent) {
  53325. parent.children.push(serializedCondition);
  53326. }
  53327. return serializedCondition;
  53328. }
  53329. if (parent) {
  53330. parent.children.push(serializationObject);
  53331. }
  53332. return serializationObject;
  53333. };
  53334. /**
  53335. * Internal only
  53336. * @hidden
  53337. */
  53338. Action._SerializeValueAsString = function (value) {
  53339. if (typeof value === "number") {
  53340. return value.toString();
  53341. }
  53342. if (typeof value === "boolean") {
  53343. return value ? "true" : "false";
  53344. }
  53345. if (value instanceof BABYLON.Vector2) {
  53346. return value.x + ", " + value.y;
  53347. }
  53348. if (value instanceof BABYLON.Vector3) {
  53349. return value.x + ", " + value.y + ", " + value.z;
  53350. }
  53351. if (value instanceof BABYLON.Color3) {
  53352. return value.r + ", " + value.g + ", " + value.b;
  53353. }
  53354. if (value instanceof BABYLON.Color4) {
  53355. return value.r + ", " + value.g + ", " + value.b + ", " + value.a;
  53356. }
  53357. return value; // string
  53358. };
  53359. /**
  53360. * Internal only
  53361. * @hidden
  53362. */
  53363. Action._GetTargetProperty = function (target) {
  53364. return {
  53365. name: "target",
  53366. targetType: target instanceof BABYLON.Mesh ? "MeshProperties"
  53367. : target instanceof BABYLON.Light ? "LightProperties"
  53368. : target instanceof BABYLON.Camera ? "CameraProperties"
  53369. : "SceneProperties",
  53370. value: target instanceof BABYLON.Scene ? "Scene" : target.name
  53371. };
  53372. };
  53373. return Action;
  53374. }());
  53375. BABYLON.Action = Action;
  53376. })(BABYLON || (BABYLON = {}));
  53377. //# sourceMappingURL=babylon.action.js.map
  53378. var BABYLON;
  53379. (function (BABYLON) {
  53380. /**
  53381. * ActionEvent is the event being sent when an action is triggered.
  53382. */
  53383. var ActionEvent = /** @class */ (function () {
  53384. /**
  53385. * Creates a new ActionEvent
  53386. * @param source The mesh or sprite that triggered the action
  53387. * @param pointerX The X mouse cursor position at the time of the event
  53388. * @param pointerY The Y mouse cursor position at the time of the event
  53389. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  53390. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  53391. * @param additionalData additional data for the event
  53392. */
  53393. function ActionEvent(
  53394. /** The mesh or sprite that triggered the action */
  53395. source,
  53396. /** The X mouse cursor position at the time of the event */
  53397. pointerX,
  53398. /** The Y mouse cursor position at the time of the event */
  53399. pointerY,
  53400. /** The mesh that is currently pointed at (can be null) */
  53401. meshUnderPointer,
  53402. /** the original (browser) event that triggered the ActionEvent */
  53403. sourceEvent,
  53404. /** additional data for the event */
  53405. additionalData) {
  53406. this.source = source;
  53407. this.pointerX = pointerX;
  53408. this.pointerY = pointerY;
  53409. this.meshUnderPointer = meshUnderPointer;
  53410. this.sourceEvent = sourceEvent;
  53411. this.additionalData = additionalData;
  53412. }
  53413. /**
  53414. * Helper function to auto-create an ActionEvent from a source mesh.
  53415. * @param source The source mesh that triggered the event
  53416. * @param evt The original (browser) event
  53417. * @param additionalData additional data for the event
  53418. * @returns the new ActionEvent
  53419. */
  53420. ActionEvent.CreateNew = function (source, evt, additionalData) {
  53421. var scene = source.getScene();
  53422. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  53423. };
  53424. /**
  53425. * Helper function to auto-create an ActionEvent from a source sprite
  53426. * @param source The source sprite that triggered the event
  53427. * @param scene Scene associated with the sprite
  53428. * @param evt The original (browser) event
  53429. * @param additionalData additional data for the event
  53430. * @returns the new ActionEvent
  53431. */
  53432. ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
  53433. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  53434. };
  53435. /**
  53436. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  53437. * @param scene the scene where the event occurred
  53438. * @param evt The original (browser) event
  53439. * @returns the new ActionEvent
  53440. */
  53441. ActionEvent.CreateNewFromScene = function (scene, evt) {
  53442. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  53443. };
  53444. /**
  53445. * Helper function to auto-create an ActionEvent from a primitive
  53446. * @param prim defines the target primitive
  53447. * @param pointerPos defines the pointer position
  53448. * @param evt The original (browser) event
  53449. * @param additionalData additional data for the event
  53450. * @returns the new ActionEvent
  53451. */
  53452. ActionEvent.CreateNewFromPrimitive = function (prim, pointerPos, evt, additionalData) {
  53453. return new ActionEvent(prim, pointerPos.x, pointerPos.y, null, evt, additionalData);
  53454. };
  53455. return ActionEvent;
  53456. }());
  53457. BABYLON.ActionEvent = ActionEvent;
  53458. /**
  53459. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  53460. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  53461. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  53462. */
  53463. var ActionManager = /** @class */ (function () {
  53464. /**
  53465. * Creates a new action manager
  53466. * @param scene defines the hosting scene
  53467. */
  53468. function ActionManager(scene) {
  53469. // Members
  53470. /** Gets the list of actions */
  53471. this.actions = new Array();
  53472. /** Gets the cursor to use when hovering items */
  53473. this.hoverCursor = '';
  53474. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  53475. scene._actionManagers.push(this);
  53476. }
  53477. Object.defineProperty(ActionManager, "NothingTrigger", {
  53478. /**
  53479. * Nothing
  53480. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53481. */
  53482. get: function () {
  53483. return ActionManager._NothingTrigger;
  53484. },
  53485. enumerable: true,
  53486. configurable: true
  53487. });
  53488. Object.defineProperty(ActionManager, "OnPickTrigger", {
  53489. /**
  53490. * On pick
  53491. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53492. */
  53493. get: function () {
  53494. return ActionManager._OnPickTrigger;
  53495. },
  53496. enumerable: true,
  53497. configurable: true
  53498. });
  53499. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  53500. /**
  53501. * On left pick
  53502. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53503. */
  53504. get: function () {
  53505. return ActionManager._OnLeftPickTrigger;
  53506. },
  53507. enumerable: true,
  53508. configurable: true
  53509. });
  53510. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  53511. /**
  53512. * On right pick
  53513. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53514. */
  53515. get: function () {
  53516. return ActionManager._OnRightPickTrigger;
  53517. },
  53518. enumerable: true,
  53519. configurable: true
  53520. });
  53521. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  53522. /**
  53523. * On center pick
  53524. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53525. */
  53526. get: function () {
  53527. return ActionManager._OnCenterPickTrigger;
  53528. },
  53529. enumerable: true,
  53530. configurable: true
  53531. });
  53532. Object.defineProperty(ActionManager, "OnPickDownTrigger", {
  53533. /**
  53534. * On pick down
  53535. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53536. */
  53537. get: function () {
  53538. return ActionManager._OnPickDownTrigger;
  53539. },
  53540. enumerable: true,
  53541. configurable: true
  53542. });
  53543. Object.defineProperty(ActionManager, "OnDoublePickTrigger", {
  53544. /**
  53545. * On double pick
  53546. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53547. */
  53548. get: function () {
  53549. return ActionManager._OnDoublePickTrigger;
  53550. },
  53551. enumerable: true,
  53552. configurable: true
  53553. });
  53554. Object.defineProperty(ActionManager, "OnPickUpTrigger", {
  53555. /**
  53556. * On pick up
  53557. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53558. */
  53559. get: function () {
  53560. return ActionManager._OnPickUpTrigger;
  53561. },
  53562. enumerable: true,
  53563. configurable: true
  53564. });
  53565. Object.defineProperty(ActionManager, "OnPickOutTrigger", {
  53566. /**
  53567. * On pick out.
  53568. * This trigger will only be raised if you also declared a OnPickDown
  53569. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53570. */
  53571. get: function () {
  53572. return ActionManager._OnPickOutTrigger;
  53573. },
  53574. enumerable: true,
  53575. configurable: true
  53576. });
  53577. Object.defineProperty(ActionManager, "OnLongPressTrigger", {
  53578. /**
  53579. * On long press
  53580. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53581. */
  53582. get: function () {
  53583. return ActionManager._OnLongPressTrigger;
  53584. },
  53585. enumerable: true,
  53586. configurable: true
  53587. });
  53588. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  53589. /**
  53590. * On pointer over
  53591. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53592. */
  53593. get: function () {
  53594. return ActionManager._OnPointerOverTrigger;
  53595. },
  53596. enumerable: true,
  53597. configurable: true
  53598. });
  53599. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  53600. /**
  53601. * On pointer out
  53602. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53603. */
  53604. get: function () {
  53605. return ActionManager._OnPointerOutTrigger;
  53606. },
  53607. enumerable: true,
  53608. configurable: true
  53609. });
  53610. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  53611. /**
  53612. * On every frame
  53613. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53614. */
  53615. get: function () {
  53616. return ActionManager._OnEveryFrameTrigger;
  53617. },
  53618. enumerable: true,
  53619. configurable: true
  53620. });
  53621. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  53622. /**
  53623. * On intersection enter
  53624. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53625. */
  53626. get: function () {
  53627. return ActionManager._OnIntersectionEnterTrigger;
  53628. },
  53629. enumerable: true,
  53630. configurable: true
  53631. });
  53632. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  53633. /**
  53634. * On intersection exit
  53635. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53636. */
  53637. get: function () {
  53638. return ActionManager._OnIntersectionExitTrigger;
  53639. },
  53640. enumerable: true,
  53641. configurable: true
  53642. });
  53643. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  53644. /**
  53645. * On key down
  53646. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53647. */
  53648. get: function () {
  53649. return ActionManager._OnKeyDownTrigger;
  53650. },
  53651. enumerable: true,
  53652. configurable: true
  53653. });
  53654. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  53655. /**
  53656. * On key up
  53657. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53658. */
  53659. get: function () {
  53660. return ActionManager._OnKeyUpTrigger;
  53661. },
  53662. enumerable: true,
  53663. configurable: true
  53664. });
  53665. // Methods
  53666. /**
  53667. * Releases all associated resources
  53668. */
  53669. ActionManager.prototype.dispose = function () {
  53670. var index = this._scene._actionManagers.indexOf(this);
  53671. for (var i = 0; i < this.actions.length; i++) {
  53672. var action = this.actions[i];
  53673. ActionManager.Triggers[action.trigger]--;
  53674. if (ActionManager.Triggers[action.trigger] === 0) {
  53675. delete ActionManager.Triggers[action.trigger];
  53676. }
  53677. }
  53678. if (index > -1) {
  53679. this._scene._actionManagers.splice(index, 1);
  53680. }
  53681. };
  53682. /**
  53683. * Gets hosting scene
  53684. * @returns the hosting scene
  53685. */
  53686. ActionManager.prototype.getScene = function () {
  53687. return this._scene;
  53688. };
  53689. /**
  53690. * Does this action manager handles actions of any of the given triggers
  53691. * @param triggers defines the triggers to be tested
  53692. * @return a boolean indicating whether one (or more) of the triggers is handled
  53693. */
  53694. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  53695. for (var index = 0; index < this.actions.length; index++) {
  53696. var action = this.actions[index];
  53697. if (triggers.indexOf(action.trigger) > -1) {
  53698. return true;
  53699. }
  53700. }
  53701. return false;
  53702. };
  53703. /**
  53704. * Does this action manager handles actions of a given trigger
  53705. * @param trigger defines the trigger to be tested
  53706. * @param parameterPredicate defines an optional predicate to filter triggers by parameter
  53707. * @return whether the trigger is handled
  53708. */
  53709. ActionManager.prototype.hasSpecificTrigger = function (trigger, parameterPredicate) {
  53710. for (var index = 0; index < this.actions.length; index++) {
  53711. var action = this.actions[index];
  53712. if (action.trigger === trigger) {
  53713. if (parameterPredicate) {
  53714. if (parameterPredicate(action.getTriggerParameter())) {
  53715. return true;
  53716. }
  53717. }
  53718. else {
  53719. return true;
  53720. }
  53721. }
  53722. }
  53723. return false;
  53724. };
  53725. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  53726. /**
  53727. * Does this action manager has pointer triggers
  53728. */
  53729. get: function () {
  53730. for (var index = 0; index < this.actions.length; index++) {
  53731. var action = this.actions[index];
  53732. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  53733. return true;
  53734. }
  53735. }
  53736. return false;
  53737. },
  53738. enumerable: true,
  53739. configurable: true
  53740. });
  53741. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  53742. /**
  53743. * Does this action manager has pick triggers
  53744. */
  53745. get: function () {
  53746. for (var index = 0; index < this.actions.length; index++) {
  53747. var action = this.actions[index];
  53748. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPickUpTrigger) {
  53749. return true;
  53750. }
  53751. }
  53752. return false;
  53753. },
  53754. enumerable: true,
  53755. configurable: true
  53756. });
  53757. Object.defineProperty(ActionManager, "HasTriggers", {
  53758. /**
  53759. * Does exist one action manager with at least one trigger
  53760. **/
  53761. get: function () {
  53762. for (var t in ActionManager.Triggers) {
  53763. if (ActionManager.Triggers.hasOwnProperty(t)) {
  53764. return true;
  53765. }
  53766. }
  53767. return false;
  53768. },
  53769. enumerable: true,
  53770. configurable: true
  53771. });
  53772. Object.defineProperty(ActionManager, "HasPickTriggers", {
  53773. /**
  53774. * Does exist one action manager with at least one pick trigger
  53775. **/
  53776. get: function () {
  53777. for (var t in ActionManager.Triggers) {
  53778. if (ActionManager.Triggers.hasOwnProperty(t)) {
  53779. var t_int = parseInt(t);
  53780. if (t_int >= ActionManager._OnPickTrigger && t_int <= ActionManager._OnPickUpTrigger) {
  53781. return true;
  53782. }
  53783. }
  53784. }
  53785. return false;
  53786. },
  53787. enumerable: true,
  53788. configurable: true
  53789. });
  53790. /**
  53791. * Does exist one action manager that handles actions of a given trigger
  53792. * @param trigger defines the trigger to be tested
  53793. * @return a boolean indicating whether the trigger is handeled by at least one action manager
  53794. **/
  53795. ActionManager.HasSpecificTrigger = function (trigger) {
  53796. for (var t in ActionManager.Triggers) {
  53797. if (ActionManager.Triggers.hasOwnProperty(t)) {
  53798. var t_int = parseInt(t);
  53799. if (t_int === trigger) {
  53800. return true;
  53801. }
  53802. }
  53803. }
  53804. return false;
  53805. };
  53806. /**
  53807. * Registers an action to this action manager
  53808. * @param action defines the action to be registered
  53809. * @return the action amended (prepared) after registration
  53810. */
  53811. ActionManager.prototype.registerAction = function (action) {
  53812. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  53813. if (this.getScene().actionManager !== this) {
  53814. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  53815. return null;
  53816. }
  53817. }
  53818. this.actions.push(action);
  53819. if (ActionManager.Triggers[action.trigger]) {
  53820. ActionManager.Triggers[action.trigger]++;
  53821. }
  53822. else {
  53823. ActionManager.Triggers[action.trigger] = 1;
  53824. }
  53825. action._actionManager = this;
  53826. action._prepare();
  53827. return action;
  53828. };
  53829. /**
  53830. * Unregisters an action to this action manager
  53831. * @param action defines the action to be unregistered
  53832. * @return a boolean indicating whether the action has been unregistered
  53833. */
  53834. ActionManager.prototype.unregisterAction = function (action) {
  53835. var index = this.actions.indexOf(action);
  53836. if (index !== -1) {
  53837. this.actions.splice(index, 1);
  53838. ActionManager.Triggers[action.trigger] -= 1;
  53839. if (ActionManager.Triggers[action.trigger] === 0) {
  53840. delete ActionManager.Triggers[action.trigger];
  53841. }
  53842. delete action._actionManager;
  53843. return true;
  53844. }
  53845. return false;
  53846. };
  53847. /**
  53848. * Process a specific trigger
  53849. * @param trigger defines the trigger to process
  53850. * @param evt defines the event details to be processed
  53851. */
  53852. ActionManager.prototype.processTrigger = function (trigger, evt) {
  53853. for (var index = 0; index < this.actions.length; index++) {
  53854. var action = this.actions[index];
  53855. if (action.trigger === trigger) {
  53856. if (evt) {
  53857. if (trigger === ActionManager.OnKeyUpTrigger
  53858. || trigger === ActionManager.OnKeyDownTrigger) {
  53859. var parameter = action.getTriggerParameter();
  53860. if (parameter && parameter !== evt.sourceEvent.keyCode) {
  53861. if (!parameter.toLowerCase) {
  53862. continue;
  53863. }
  53864. var lowerCase = parameter.toLowerCase();
  53865. if (lowerCase !== evt.sourceEvent.key) {
  53866. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  53867. var actualkey = String.fromCharCode(unicode).toLowerCase();
  53868. if (actualkey !== lowerCase) {
  53869. continue;
  53870. }
  53871. }
  53872. }
  53873. }
  53874. }
  53875. action._executeCurrent(evt);
  53876. }
  53877. }
  53878. };
  53879. /** @hidden */
  53880. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  53881. var properties = propertyPath.split(".");
  53882. for (var index = 0; index < properties.length - 1; index++) {
  53883. target = target[properties[index]];
  53884. }
  53885. return target;
  53886. };
  53887. /** @hidden */
  53888. ActionManager.prototype._getProperty = function (propertyPath) {
  53889. var properties = propertyPath.split(".");
  53890. return properties[properties.length - 1];
  53891. };
  53892. /**
  53893. * Serialize this manager to a JSON object
  53894. * @param name defines the property name to store this manager
  53895. * @returns a JSON representation of this manager
  53896. */
  53897. ActionManager.prototype.serialize = function (name) {
  53898. var root = {
  53899. children: new Array(),
  53900. name: name,
  53901. type: 3,
  53902. properties: new Array() // Empty for root but required
  53903. };
  53904. for (var i = 0; i < this.actions.length; i++) {
  53905. var triggerObject = {
  53906. type: 0,
  53907. children: new Array(),
  53908. name: ActionManager.GetTriggerName(this.actions[i].trigger),
  53909. properties: new Array()
  53910. };
  53911. var triggerOptions = this.actions[i].triggerOptions;
  53912. if (triggerOptions && typeof triggerOptions !== "number") {
  53913. if (triggerOptions.parameter instanceof BABYLON.Node) {
  53914. triggerObject.properties.push(BABYLON.Action._GetTargetProperty(triggerOptions.parameter));
  53915. }
  53916. else {
  53917. var parameter = {};
  53918. BABYLON.Tools.DeepCopy(triggerOptions.parameter, parameter, ["mesh"]);
  53919. if (triggerOptions.parameter.mesh) {
  53920. parameter._meshId = triggerOptions.parameter.mesh.id;
  53921. }
  53922. triggerObject.properties.push({ name: "parameter", targetType: null, value: parameter });
  53923. }
  53924. }
  53925. // Serialize child action, recursively
  53926. this.actions[i].serialize(triggerObject);
  53927. // Add serialized trigger
  53928. root.children.push(triggerObject);
  53929. }
  53930. return root;
  53931. };
  53932. /**
  53933. * Creates a new ActionManager from a JSON data
  53934. * @param parsedActions defines the JSON data to read from
  53935. * @param object defines the hosting mesh
  53936. * @param scene defines the hosting scene
  53937. */
  53938. ActionManager.Parse = function (parsedActions, object, scene) {
  53939. var actionManager = new ActionManager(scene);
  53940. if (object === null)
  53941. scene.actionManager = actionManager;
  53942. else
  53943. object.actionManager = actionManager;
  53944. // instanciate a new object
  53945. var instanciate = function (name, params) {
  53946. // TODO: We will need to find a solution for the next line when using commonjs / es6 .
  53947. var newInstance = Object.create(BABYLON.Tools.Instantiate("BABYLON." + name).prototype);
  53948. newInstance.constructor.apply(newInstance, params);
  53949. return newInstance;
  53950. };
  53951. var parseParameter = function (name, value, target, propertyPath) {
  53952. if (propertyPath === null) {
  53953. // String, boolean or float
  53954. var floatValue = parseFloat(value);
  53955. if (value === "true" || value === "false")
  53956. return value === "true";
  53957. else
  53958. return isNaN(floatValue) ? value : floatValue;
  53959. }
  53960. var effectiveTarget = propertyPath.split(".");
  53961. var values = value.split(",");
  53962. // Get effective Target
  53963. for (var i = 0; i < effectiveTarget.length; i++) {
  53964. target = target[effectiveTarget[i]];
  53965. }
  53966. // Return appropriate value with its type
  53967. if (typeof (target) === "boolean")
  53968. return values[0] === "true";
  53969. if (typeof (target) === "string")
  53970. return values[0];
  53971. // Parameters with multiple values such as Vector3 etc.
  53972. var split = new Array();
  53973. for (var i = 0; i < values.length; i++)
  53974. split.push(parseFloat(values[i]));
  53975. if (target instanceof BABYLON.Vector3)
  53976. return BABYLON.Vector3.FromArray(split);
  53977. if (target instanceof BABYLON.Vector4)
  53978. return BABYLON.Vector4.FromArray(split);
  53979. if (target instanceof BABYLON.Color3)
  53980. return BABYLON.Color3.FromArray(split);
  53981. if (target instanceof BABYLON.Color4)
  53982. return BABYLON.Color4.FromArray(split);
  53983. return parseFloat(values[0]);
  53984. };
  53985. // traverse graph per trigger
  53986. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  53987. if (combineArray === void 0) { combineArray = null; }
  53988. if (parsedAction.detached)
  53989. return;
  53990. var parameters = new Array();
  53991. var target = null;
  53992. var propertyPath = null;
  53993. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  53994. // Parameters
  53995. if (parsedAction.type === 2)
  53996. parameters.push(actionManager);
  53997. else
  53998. parameters.push(trigger);
  53999. if (combine) {
  54000. var actions = new Array();
  54001. for (var j = 0; j < parsedAction.combine.length; j++) {
  54002. traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions);
  54003. }
  54004. parameters.push(actions);
  54005. }
  54006. else {
  54007. for (var i = 0; i < parsedAction.properties.length; i++) {
  54008. var value = parsedAction.properties[i].value;
  54009. var name = parsedAction.properties[i].name;
  54010. var targetType = parsedAction.properties[i].targetType;
  54011. if (name === "target")
  54012. if (targetType !== null && targetType === "SceneProperties")
  54013. value = target = scene;
  54014. else
  54015. value = target = scene.getNodeByName(value);
  54016. else if (name === "parent")
  54017. value = scene.getNodeByName(value);
  54018. else if (name === "sound")
  54019. value = scene.getSoundByName(value);
  54020. else if (name !== "propertyPath") {
  54021. if (parsedAction.type === 2 && name === "operator")
  54022. value = BABYLON.ValueCondition[value];
  54023. else
  54024. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  54025. }
  54026. else {
  54027. propertyPath = value;
  54028. }
  54029. parameters.push(value);
  54030. }
  54031. }
  54032. if (combineArray === null) {
  54033. parameters.push(condition);
  54034. }
  54035. else {
  54036. parameters.push(null);
  54037. }
  54038. // If interpolate value action
  54039. if (parsedAction.name === "InterpolateValueAction") {
  54040. var param = parameters[parameters.length - 2];
  54041. parameters[parameters.length - 1] = param;
  54042. parameters[parameters.length - 2] = condition;
  54043. }
  54044. // Action or condition(s) and not CombineAction
  54045. var newAction = instanciate(parsedAction.name, parameters);
  54046. if (newAction instanceof BABYLON.Condition && condition !== null) {
  54047. var nothing = new BABYLON.DoNothingAction(trigger, condition);
  54048. if (action)
  54049. action.then(nothing);
  54050. else
  54051. actionManager.registerAction(nothing);
  54052. action = nothing;
  54053. }
  54054. if (combineArray === null) {
  54055. if (newAction instanceof BABYLON.Condition) {
  54056. condition = newAction;
  54057. newAction = action;
  54058. }
  54059. else {
  54060. condition = null;
  54061. if (action)
  54062. action.then(newAction);
  54063. else
  54064. actionManager.registerAction(newAction);
  54065. }
  54066. }
  54067. else {
  54068. combineArray.push(newAction);
  54069. }
  54070. for (var i = 0; i < parsedAction.children.length; i++)
  54071. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  54072. };
  54073. // triggers
  54074. for (var i = 0; i < parsedActions.children.length; i++) {
  54075. var triggerParams;
  54076. var trigger = parsedActions.children[i];
  54077. if (trigger.properties.length > 0) {
  54078. var param = trigger.properties[0].value;
  54079. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  54080. if (value._meshId) {
  54081. value.mesh = scene.getMeshByID(value._meshId);
  54082. }
  54083. triggerParams = { trigger: ActionManager[trigger.name], parameter: value };
  54084. }
  54085. else
  54086. triggerParams = ActionManager[trigger.name];
  54087. for (var j = 0; j < trigger.children.length; j++) {
  54088. if (!trigger.detached)
  54089. traverse(trigger.children[j], triggerParams, null, null);
  54090. }
  54091. }
  54092. };
  54093. /**
  54094. * Get a trigger name by index
  54095. * @param trigger defines the trigger index
  54096. * @returns a trigger name
  54097. */
  54098. ActionManager.GetTriggerName = function (trigger) {
  54099. switch (trigger) {
  54100. case 0: return "NothingTrigger";
  54101. case 1: return "OnPickTrigger";
  54102. case 2: return "OnLeftPickTrigger";
  54103. case 3: return "OnRightPickTrigger";
  54104. case 4: return "OnCenterPickTrigger";
  54105. case 5: return "OnPickDownTrigger";
  54106. case 6: return "OnPickUpTrigger";
  54107. case 7: return "OnLongPressTrigger";
  54108. case 8: return "OnPointerOverTrigger";
  54109. case 9: return "OnPointerOutTrigger";
  54110. case 10: return "OnEveryFrameTrigger";
  54111. case 11: return "OnIntersectionEnterTrigger";
  54112. case 12: return "OnIntersectionExitTrigger";
  54113. case 13: return "OnKeyDownTrigger";
  54114. case 14: return "OnKeyUpTrigger";
  54115. case 15: return "OnPickOutTrigger";
  54116. default: return "";
  54117. }
  54118. };
  54119. // Statics
  54120. ActionManager._NothingTrigger = 0;
  54121. ActionManager._OnPickTrigger = 1;
  54122. ActionManager._OnLeftPickTrigger = 2;
  54123. ActionManager._OnRightPickTrigger = 3;
  54124. ActionManager._OnCenterPickTrigger = 4;
  54125. ActionManager._OnPickDownTrigger = 5;
  54126. ActionManager._OnDoublePickTrigger = 6;
  54127. ActionManager._OnPickUpTrigger = 7;
  54128. ActionManager._OnLongPressTrigger = 8;
  54129. ActionManager._OnPointerOverTrigger = 9;
  54130. ActionManager._OnPointerOutTrigger = 10;
  54131. ActionManager._OnEveryFrameTrigger = 11;
  54132. ActionManager._OnIntersectionEnterTrigger = 12;
  54133. ActionManager._OnIntersectionExitTrigger = 13;
  54134. ActionManager._OnKeyDownTrigger = 14;
  54135. ActionManager._OnKeyUpTrigger = 15;
  54136. ActionManager._OnPickOutTrigger = 16;
  54137. /** Gets the list of active triggers */
  54138. ActionManager.Triggers = {};
  54139. return ActionManager;
  54140. }());
  54141. BABYLON.ActionManager = ActionManager;
  54142. })(BABYLON || (BABYLON = {}));
  54143. //# sourceMappingURL=babylon.actionManager.js.map
  54144. var BABYLON;
  54145. (function (BABYLON) {
  54146. var InterpolateValueAction = /** @class */ (function (_super) {
  54147. __extends(InterpolateValueAction, _super);
  54148. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
  54149. if (duration === void 0) { duration = 1000; }
  54150. var _this = _super.call(this, triggerOptions, condition) || this;
  54151. _this.propertyPath = propertyPath;
  54152. _this.value = value;
  54153. _this.duration = duration;
  54154. _this.stopOtherAnimations = stopOtherAnimations;
  54155. _this.onInterpolationDone = onInterpolationDone;
  54156. _this.onInterpolationDoneObservable = new BABYLON.Observable();
  54157. _this._target = _this._effectiveTarget = target;
  54158. return _this;
  54159. }
  54160. InterpolateValueAction.prototype._prepare = function () {
  54161. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  54162. this._property = this._getProperty(this.propertyPath);
  54163. };
  54164. InterpolateValueAction.prototype.execute = function () {
  54165. var _this = this;
  54166. var scene = this._actionManager.getScene();
  54167. var keys = [
  54168. {
  54169. frame: 0,
  54170. value: this._effectiveTarget[this._property]
  54171. }, {
  54172. frame: 100,
  54173. value: this.value
  54174. }
  54175. ];
  54176. var dataType;
  54177. if (typeof this.value === "number") {
  54178. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  54179. }
  54180. else if (this.value instanceof BABYLON.Color3) {
  54181. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  54182. }
  54183. else if (this.value instanceof BABYLON.Vector3) {
  54184. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  54185. }
  54186. else if (this.value instanceof BABYLON.Matrix) {
  54187. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  54188. }
  54189. else if (this.value instanceof BABYLON.Quaternion) {
  54190. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  54191. }
  54192. else {
  54193. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  54194. return;
  54195. }
  54196. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  54197. animation.setKeys(keys);
  54198. if (this.stopOtherAnimations) {
  54199. scene.stopAnimation(this._effectiveTarget);
  54200. }
  54201. var wrapper = function () {
  54202. _this.onInterpolationDoneObservable.notifyObservers(_this);
  54203. if (_this.onInterpolationDone) {
  54204. _this.onInterpolationDone();
  54205. }
  54206. };
  54207. scene.beginDirectAnimation(this._effectiveTarget, [animation], 0, 100, false, 1, wrapper);
  54208. };
  54209. InterpolateValueAction.prototype.serialize = function (parent) {
  54210. return _super.prototype._serialize.call(this, {
  54211. name: "InterpolateValueAction",
  54212. properties: [
  54213. BABYLON.Action._GetTargetProperty(this._target),
  54214. { name: "propertyPath", value: this.propertyPath },
  54215. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  54216. { name: "duration", value: BABYLON.Action._SerializeValueAsString(this.duration) },
  54217. { name: "stopOtherAnimations", value: BABYLON.Action._SerializeValueAsString(this.stopOtherAnimations) || false }
  54218. ]
  54219. }, parent);
  54220. };
  54221. return InterpolateValueAction;
  54222. }(BABYLON.Action));
  54223. BABYLON.InterpolateValueAction = InterpolateValueAction;
  54224. })(BABYLON || (BABYLON = {}));
  54225. //# sourceMappingURL=babylon.interpolateValueAction.js.map
  54226. var BABYLON;
  54227. (function (BABYLON) {
  54228. var SwitchBooleanAction = /** @class */ (function (_super) {
  54229. __extends(SwitchBooleanAction, _super);
  54230. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  54231. var _this = _super.call(this, triggerOptions, condition) || this;
  54232. _this.propertyPath = propertyPath;
  54233. _this._target = _this._effectiveTarget = target;
  54234. return _this;
  54235. }
  54236. SwitchBooleanAction.prototype._prepare = function () {
  54237. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  54238. this._property = this._getProperty(this.propertyPath);
  54239. };
  54240. SwitchBooleanAction.prototype.execute = function () {
  54241. this._effectiveTarget[this._property] = !this._effectiveTarget[this._property];
  54242. };
  54243. SwitchBooleanAction.prototype.serialize = function (parent) {
  54244. return _super.prototype._serialize.call(this, {
  54245. name: "SwitchBooleanAction",
  54246. properties: [
  54247. BABYLON.Action._GetTargetProperty(this._target),
  54248. { name: "propertyPath", value: this.propertyPath }
  54249. ]
  54250. }, parent);
  54251. };
  54252. return SwitchBooleanAction;
  54253. }(BABYLON.Action));
  54254. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  54255. var SetStateAction = /** @class */ (function (_super) {
  54256. __extends(SetStateAction, _super);
  54257. function SetStateAction(triggerOptions, target, value, condition) {
  54258. var _this = _super.call(this, triggerOptions, condition) || this;
  54259. _this.value = value;
  54260. _this._target = target;
  54261. return _this;
  54262. }
  54263. SetStateAction.prototype.execute = function () {
  54264. this._target.state = this.value;
  54265. };
  54266. SetStateAction.prototype.serialize = function (parent) {
  54267. return _super.prototype._serialize.call(this, {
  54268. name: "SetStateAction",
  54269. properties: [
  54270. BABYLON.Action._GetTargetProperty(this._target),
  54271. { name: "value", value: this.value }
  54272. ]
  54273. }, parent);
  54274. };
  54275. return SetStateAction;
  54276. }(BABYLON.Action));
  54277. BABYLON.SetStateAction = SetStateAction;
  54278. var SetValueAction = /** @class */ (function (_super) {
  54279. __extends(SetValueAction, _super);
  54280. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  54281. var _this = _super.call(this, triggerOptions, condition) || this;
  54282. _this.propertyPath = propertyPath;
  54283. _this.value = value;
  54284. _this._target = _this._effectiveTarget = target;
  54285. return _this;
  54286. }
  54287. SetValueAction.prototype._prepare = function () {
  54288. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  54289. this._property = this._getProperty(this.propertyPath);
  54290. };
  54291. SetValueAction.prototype.execute = function () {
  54292. this._effectiveTarget[this._property] = this.value;
  54293. if (this._target.markAsDirty) {
  54294. this._target.markAsDirty(this._property);
  54295. }
  54296. };
  54297. SetValueAction.prototype.serialize = function (parent) {
  54298. return _super.prototype._serialize.call(this, {
  54299. name: "SetValueAction",
  54300. properties: [
  54301. BABYLON.Action._GetTargetProperty(this._target),
  54302. { name: "propertyPath", value: this.propertyPath },
  54303. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  54304. ]
  54305. }, parent);
  54306. };
  54307. return SetValueAction;
  54308. }(BABYLON.Action));
  54309. BABYLON.SetValueAction = SetValueAction;
  54310. var IncrementValueAction = /** @class */ (function (_super) {
  54311. __extends(IncrementValueAction, _super);
  54312. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  54313. var _this = _super.call(this, triggerOptions, condition) || this;
  54314. _this.propertyPath = propertyPath;
  54315. _this.value = value;
  54316. _this._target = _this._effectiveTarget = target;
  54317. return _this;
  54318. }
  54319. IncrementValueAction.prototype._prepare = function () {
  54320. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  54321. this._property = this._getProperty(this.propertyPath);
  54322. if (typeof this._effectiveTarget[this._property] !== "number") {
  54323. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  54324. }
  54325. };
  54326. IncrementValueAction.prototype.execute = function () {
  54327. this._effectiveTarget[this._property] += this.value;
  54328. if (this._target.markAsDirty) {
  54329. this._target.markAsDirty(this._property);
  54330. }
  54331. };
  54332. IncrementValueAction.prototype.serialize = function (parent) {
  54333. return _super.prototype._serialize.call(this, {
  54334. name: "IncrementValueAction",
  54335. properties: [
  54336. BABYLON.Action._GetTargetProperty(this._target),
  54337. { name: "propertyPath", value: this.propertyPath },
  54338. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  54339. ]
  54340. }, parent);
  54341. };
  54342. return IncrementValueAction;
  54343. }(BABYLON.Action));
  54344. BABYLON.IncrementValueAction = IncrementValueAction;
  54345. var PlayAnimationAction = /** @class */ (function (_super) {
  54346. __extends(PlayAnimationAction, _super);
  54347. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  54348. var _this = _super.call(this, triggerOptions, condition) || this;
  54349. _this.from = from;
  54350. _this.to = to;
  54351. _this.loop = loop;
  54352. _this._target = target;
  54353. return _this;
  54354. }
  54355. PlayAnimationAction.prototype._prepare = function () {
  54356. };
  54357. PlayAnimationAction.prototype.execute = function () {
  54358. var scene = this._actionManager.getScene();
  54359. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  54360. };
  54361. PlayAnimationAction.prototype.serialize = function (parent) {
  54362. return _super.prototype._serialize.call(this, {
  54363. name: "PlayAnimationAction",
  54364. properties: [
  54365. BABYLON.Action._GetTargetProperty(this._target),
  54366. { name: "from", value: String(this.from) },
  54367. { name: "to", value: String(this.to) },
  54368. { name: "loop", value: BABYLON.Action._SerializeValueAsString(this.loop) || false }
  54369. ]
  54370. }, parent);
  54371. };
  54372. return PlayAnimationAction;
  54373. }(BABYLON.Action));
  54374. BABYLON.PlayAnimationAction = PlayAnimationAction;
  54375. var StopAnimationAction = /** @class */ (function (_super) {
  54376. __extends(StopAnimationAction, _super);
  54377. function StopAnimationAction(triggerOptions, target, condition) {
  54378. var _this = _super.call(this, triggerOptions, condition) || this;
  54379. _this._target = target;
  54380. return _this;
  54381. }
  54382. StopAnimationAction.prototype._prepare = function () {
  54383. };
  54384. StopAnimationAction.prototype.execute = function () {
  54385. var scene = this._actionManager.getScene();
  54386. scene.stopAnimation(this._target);
  54387. };
  54388. StopAnimationAction.prototype.serialize = function (parent) {
  54389. return _super.prototype._serialize.call(this, {
  54390. name: "StopAnimationAction",
  54391. properties: [BABYLON.Action._GetTargetProperty(this._target)]
  54392. }, parent);
  54393. };
  54394. return StopAnimationAction;
  54395. }(BABYLON.Action));
  54396. BABYLON.StopAnimationAction = StopAnimationAction;
  54397. var DoNothingAction = /** @class */ (function (_super) {
  54398. __extends(DoNothingAction, _super);
  54399. function DoNothingAction(triggerOptions, condition) {
  54400. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  54401. return _super.call(this, triggerOptions, condition) || this;
  54402. }
  54403. DoNothingAction.prototype.execute = function () {
  54404. };
  54405. DoNothingAction.prototype.serialize = function (parent) {
  54406. return _super.prototype._serialize.call(this, {
  54407. name: "DoNothingAction",
  54408. properties: []
  54409. }, parent);
  54410. };
  54411. return DoNothingAction;
  54412. }(BABYLON.Action));
  54413. BABYLON.DoNothingAction = DoNothingAction;
  54414. var CombineAction = /** @class */ (function (_super) {
  54415. __extends(CombineAction, _super);
  54416. function CombineAction(triggerOptions, children, condition) {
  54417. var _this = _super.call(this, triggerOptions, condition) || this;
  54418. _this.children = children;
  54419. return _this;
  54420. }
  54421. CombineAction.prototype._prepare = function () {
  54422. for (var index = 0; index < this.children.length; index++) {
  54423. this.children[index]._actionManager = this._actionManager;
  54424. this.children[index]._prepare();
  54425. }
  54426. };
  54427. CombineAction.prototype.execute = function (evt) {
  54428. for (var index = 0; index < this.children.length; index++) {
  54429. this.children[index].execute(evt);
  54430. }
  54431. };
  54432. CombineAction.prototype.serialize = function (parent) {
  54433. var serializationObject = _super.prototype._serialize.call(this, {
  54434. name: "CombineAction",
  54435. properties: [],
  54436. combine: []
  54437. }, parent);
  54438. for (var i = 0; i < this.children.length; i++) {
  54439. serializationObject.combine.push(this.children[i].serialize(null));
  54440. }
  54441. return serializationObject;
  54442. };
  54443. return CombineAction;
  54444. }(BABYLON.Action));
  54445. BABYLON.CombineAction = CombineAction;
  54446. var ExecuteCodeAction = /** @class */ (function (_super) {
  54447. __extends(ExecuteCodeAction, _super);
  54448. function ExecuteCodeAction(triggerOptions, func, condition) {
  54449. var _this = _super.call(this, triggerOptions, condition) || this;
  54450. _this.func = func;
  54451. return _this;
  54452. }
  54453. ExecuteCodeAction.prototype.execute = function (evt) {
  54454. this.func(evt);
  54455. };
  54456. return ExecuteCodeAction;
  54457. }(BABYLON.Action));
  54458. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  54459. var SetParentAction = /** @class */ (function (_super) {
  54460. __extends(SetParentAction, _super);
  54461. function SetParentAction(triggerOptions, target, parent, condition) {
  54462. var _this = _super.call(this, triggerOptions, condition) || this;
  54463. _this._target = target;
  54464. _this._parent = parent;
  54465. return _this;
  54466. }
  54467. SetParentAction.prototype._prepare = function () {
  54468. };
  54469. SetParentAction.prototype.execute = function () {
  54470. if (this._target.parent === this._parent) {
  54471. return;
  54472. }
  54473. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  54474. invertParentWorldMatrix.invert();
  54475. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  54476. this._target.parent = this._parent;
  54477. };
  54478. SetParentAction.prototype.serialize = function (parent) {
  54479. return _super.prototype._serialize.call(this, {
  54480. name: "SetParentAction",
  54481. properties: [
  54482. BABYLON.Action._GetTargetProperty(this._target),
  54483. BABYLON.Action._GetTargetProperty(this._parent),
  54484. ]
  54485. }, parent);
  54486. };
  54487. return SetParentAction;
  54488. }(BABYLON.Action));
  54489. BABYLON.SetParentAction = SetParentAction;
  54490. var PlaySoundAction = /** @class */ (function (_super) {
  54491. __extends(PlaySoundAction, _super);
  54492. function PlaySoundAction(triggerOptions, sound, condition) {
  54493. var _this = _super.call(this, triggerOptions, condition) || this;
  54494. _this._sound = sound;
  54495. return _this;
  54496. }
  54497. PlaySoundAction.prototype._prepare = function () {
  54498. };
  54499. PlaySoundAction.prototype.execute = function () {
  54500. if (this._sound !== undefined)
  54501. this._sound.play();
  54502. };
  54503. PlaySoundAction.prototype.serialize = function (parent) {
  54504. return _super.prototype._serialize.call(this, {
  54505. name: "PlaySoundAction",
  54506. properties: [{ name: "sound", value: this._sound.name }]
  54507. }, parent);
  54508. };
  54509. return PlaySoundAction;
  54510. }(BABYLON.Action));
  54511. BABYLON.PlaySoundAction = PlaySoundAction;
  54512. var StopSoundAction = /** @class */ (function (_super) {
  54513. __extends(StopSoundAction, _super);
  54514. function StopSoundAction(triggerOptions, sound, condition) {
  54515. var _this = _super.call(this, triggerOptions, condition) || this;
  54516. _this._sound = sound;
  54517. return _this;
  54518. }
  54519. StopSoundAction.prototype._prepare = function () {
  54520. };
  54521. StopSoundAction.prototype.execute = function () {
  54522. if (this._sound !== undefined)
  54523. this._sound.stop();
  54524. };
  54525. StopSoundAction.prototype.serialize = function (parent) {
  54526. return _super.prototype._serialize.call(this, {
  54527. name: "StopSoundAction",
  54528. properties: [{ name: "sound", value: this._sound.name }]
  54529. }, parent);
  54530. };
  54531. return StopSoundAction;
  54532. }(BABYLON.Action));
  54533. BABYLON.StopSoundAction = StopSoundAction;
  54534. })(BABYLON || (BABYLON = {}));
  54535. //# sourceMappingURL=babylon.directActions.js.map
  54536. var BABYLON;
  54537. (function (BABYLON) {
  54538. var SpriteManager = /** @class */ (function () {
  54539. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  54540. if (epsilon === void 0) { epsilon = 0.01; }
  54541. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  54542. this.name = name;
  54543. this.sprites = new Array();
  54544. this.renderingGroupId = 0;
  54545. this.layerMask = 0x0FFFFFFF;
  54546. this.fogEnabled = true;
  54547. this.isPickable = false;
  54548. /**
  54549. * An event triggered when the manager is disposed.
  54550. */
  54551. this.onDisposeObservable = new BABYLON.Observable();
  54552. this._vertexBuffers = {};
  54553. this._capacity = capacity;
  54554. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  54555. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  54556. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  54557. if (cellSize.width && cellSize.height) {
  54558. this.cellWidth = cellSize.width;
  54559. this.cellHeight = cellSize.height;
  54560. }
  54561. else if (cellSize !== undefined) {
  54562. this.cellWidth = cellSize;
  54563. this.cellHeight = cellSize;
  54564. }
  54565. else {
  54566. return;
  54567. }
  54568. this._epsilon = epsilon;
  54569. this._scene = scene;
  54570. this._scene.spriteManagers.push(this);
  54571. var indices = [];
  54572. var index = 0;
  54573. for (var count = 0; count < capacity; count++) {
  54574. indices.push(index);
  54575. indices.push(index + 1);
  54576. indices.push(index + 2);
  54577. indices.push(index);
  54578. indices.push(index + 2);
  54579. indices.push(index + 3);
  54580. index += 4;
  54581. }
  54582. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  54583. // VBO
  54584. // 16 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color r, color g, color b, color a)
  54585. this._vertexData = new Float32Array(capacity * 16 * 4);
  54586. this._buffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 16);
  54587. var positions = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 4);
  54588. var options = this._buffer.createVertexBuffer("options", 4, 4);
  54589. var cellInfo = this._buffer.createVertexBuffer("cellInfo", 8, 4);
  54590. var colors = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 12, 4);
  54591. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  54592. this._vertexBuffers["options"] = options;
  54593. this._vertexBuffers["cellInfo"] = cellInfo;
  54594. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  54595. // Effects
  54596. this._effectBase = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  54597. this._effectFog = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  54598. }
  54599. Object.defineProperty(SpriteManager.prototype, "onDispose", {
  54600. set: function (callback) {
  54601. if (this._onDisposeObserver) {
  54602. this.onDisposeObservable.remove(this._onDisposeObserver);
  54603. }
  54604. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  54605. },
  54606. enumerable: true,
  54607. configurable: true
  54608. });
  54609. Object.defineProperty(SpriteManager.prototype, "texture", {
  54610. get: function () {
  54611. return this._spriteTexture;
  54612. },
  54613. set: function (value) {
  54614. this._spriteTexture = value;
  54615. },
  54616. enumerable: true,
  54617. configurable: true
  54618. });
  54619. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  54620. var arrayOffset = index * 16;
  54621. if (offsetX === 0)
  54622. offsetX = this._epsilon;
  54623. else if (offsetX === 1)
  54624. offsetX = 1 - this._epsilon;
  54625. if (offsetY === 0)
  54626. offsetY = this._epsilon;
  54627. else if (offsetY === 1)
  54628. offsetY = 1 - this._epsilon;
  54629. this._vertexData[arrayOffset] = sprite.position.x;
  54630. this._vertexData[arrayOffset + 1] = sprite.position.y;
  54631. this._vertexData[arrayOffset + 2] = sprite.position.z;
  54632. this._vertexData[arrayOffset + 3] = sprite.angle;
  54633. this._vertexData[arrayOffset + 4] = sprite.width;
  54634. this._vertexData[arrayOffset + 5] = sprite.height;
  54635. this._vertexData[arrayOffset + 6] = offsetX;
  54636. this._vertexData[arrayOffset + 7] = offsetY;
  54637. this._vertexData[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  54638. this._vertexData[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  54639. var offset = (sprite.cellIndex / rowSize) >> 0;
  54640. this._vertexData[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  54641. this._vertexData[arrayOffset + 11] = offset;
  54642. // Color
  54643. this._vertexData[arrayOffset + 12] = sprite.color.r;
  54644. this._vertexData[arrayOffset + 13] = sprite.color.g;
  54645. this._vertexData[arrayOffset + 14] = sprite.color.b;
  54646. this._vertexData[arrayOffset + 15] = sprite.color.a;
  54647. };
  54648. SpriteManager.prototype.intersects = function (ray, camera, predicate, fastCheck) {
  54649. var count = Math.min(this._capacity, this.sprites.length);
  54650. var min = BABYLON.Vector3.Zero();
  54651. var max = BABYLON.Vector3.Zero();
  54652. var distance = Number.MAX_VALUE;
  54653. var currentSprite = null;
  54654. var cameraSpacePosition = BABYLON.Vector3.Zero();
  54655. var cameraView = camera.getViewMatrix();
  54656. for (var index = 0; index < count; index++) {
  54657. var sprite = this.sprites[index];
  54658. if (!sprite) {
  54659. continue;
  54660. }
  54661. if (predicate) {
  54662. if (!predicate(sprite)) {
  54663. continue;
  54664. }
  54665. }
  54666. else if (!sprite.isPickable) {
  54667. continue;
  54668. }
  54669. BABYLON.Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition);
  54670. min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z);
  54671. max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z);
  54672. if (ray.intersectsBoxMinMax(min, max)) {
  54673. var currentDistance = BABYLON.Vector3.Distance(cameraSpacePosition, ray.origin);
  54674. if (distance > currentDistance) {
  54675. distance = currentDistance;
  54676. currentSprite = sprite;
  54677. if (fastCheck) {
  54678. break;
  54679. }
  54680. }
  54681. }
  54682. }
  54683. if (currentSprite) {
  54684. var result = new BABYLON.PickingInfo();
  54685. result.hit = true;
  54686. result.pickedSprite = currentSprite;
  54687. result.distance = distance;
  54688. return result;
  54689. }
  54690. return null;
  54691. };
  54692. SpriteManager.prototype.render = function () {
  54693. // Check
  54694. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  54695. return;
  54696. var engine = this._scene.getEngine();
  54697. var baseSize = this._spriteTexture.getBaseSize();
  54698. // Sprites
  54699. var deltaTime = engine.getDeltaTime();
  54700. var max = Math.min(this._capacity, this.sprites.length);
  54701. var rowSize = baseSize.width / this.cellWidth;
  54702. var offset = 0;
  54703. for (var index = 0; index < max; index++) {
  54704. var sprite = this.sprites[index];
  54705. if (!sprite) {
  54706. continue;
  54707. }
  54708. sprite._animate(deltaTime);
  54709. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  54710. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  54711. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  54712. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  54713. }
  54714. this._buffer.update(this._vertexData);
  54715. // Render
  54716. var effect = this._effectBase;
  54717. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  54718. effect = this._effectFog;
  54719. }
  54720. engine.enableEffect(effect);
  54721. var viewMatrix = this._scene.getViewMatrix();
  54722. effect.setTexture("diffuseSampler", this._spriteTexture);
  54723. effect.setMatrix("view", viewMatrix);
  54724. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  54725. effect.setFloat2("textureInfos", this.cellWidth / baseSize.width, this.cellHeight / baseSize.height);
  54726. // Fog
  54727. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  54728. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  54729. effect.setColor3("vFogColor", this._scene.fogColor);
  54730. }
  54731. // VBOs
  54732. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  54733. // Draw order
  54734. engine.setDepthFunctionToLessOrEqual();
  54735. effect.setBool("alphaTest", true);
  54736. engine.setColorWrite(false);
  54737. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, max * 6);
  54738. engine.setColorWrite(true);
  54739. effect.setBool("alphaTest", false);
  54740. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  54741. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, max * 6);
  54742. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  54743. };
  54744. SpriteManager.prototype.dispose = function () {
  54745. if (this._buffer) {
  54746. this._buffer.dispose();
  54747. this._buffer = null;
  54748. }
  54749. if (this._indexBuffer) {
  54750. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  54751. this._indexBuffer = null;
  54752. }
  54753. if (this._spriteTexture) {
  54754. this._spriteTexture.dispose();
  54755. this._spriteTexture = null;
  54756. }
  54757. // Remove from scene
  54758. var index = this._scene.spriteManagers.indexOf(this);
  54759. this._scene.spriteManagers.splice(index, 1);
  54760. // Callback
  54761. this.onDisposeObservable.notifyObservers(this);
  54762. this.onDisposeObservable.clear();
  54763. };
  54764. return SpriteManager;
  54765. }());
  54766. BABYLON.SpriteManager = SpriteManager;
  54767. })(BABYLON || (BABYLON = {}));
  54768. //# sourceMappingURL=babylon.spriteManager.js.map
  54769. var BABYLON;
  54770. (function (BABYLON) {
  54771. var Sprite = /** @class */ (function () {
  54772. function Sprite(name, manager) {
  54773. this.name = name;
  54774. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  54775. this.width = 1.0;
  54776. this.height = 1.0;
  54777. this.angle = 0;
  54778. this.cellIndex = 0;
  54779. this.invertU = 0;
  54780. this.invertV = 0;
  54781. this.animations = new Array();
  54782. this.isPickable = false;
  54783. this._animationStarted = false;
  54784. this._loopAnimation = false;
  54785. this._fromIndex = 0;
  54786. this._toIndex = 0;
  54787. this._delay = 0;
  54788. this._direction = 1;
  54789. this._time = 0;
  54790. this._manager = manager;
  54791. this._manager.sprites.push(this);
  54792. this.position = BABYLON.Vector3.Zero();
  54793. }
  54794. Object.defineProperty(Sprite.prototype, "size", {
  54795. get: function () {
  54796. return this.width;
  54797. },
  54798. set: function (value) {
  54799. this.width = value;
  54800. this.height = value;
  54801. },
  54802. enumerable: true,
  54803. configurable: true
  54804. });
  54805. Sprite.prototype.playAnimation = function (from, to, loop, delay, onAnimationEnd) {
  54806. this._fromIndex = from;
  54807. this._toIndex = to;
  54808. this._loopAnimation = loop;
  54809. this._delay = delay;
  54810. this._animationStarted = true;
  54811. this._direction = from < to ? 1 : -1;
  54812. this.cellIndex = from;
  54813. this._time = 0;
  54814. this._onAnimationEnd = onAnimationEnd;
  54815. };
  54816. Sprite.prototype.stopAnimation = function () {
  54817. this._animationStarted = false;
  54818. };
  54819. Sprite.prototype._animate = function (deltaTime) {
  54820. if (!this._animationStarted)
  54821. return;
  54822. this._time += deltaTime;
  54823. if (this._time > this._delay) {
  54824. this._time = this._time % this._delay;
  54825. this.cellIndex += this._direction;
  54826. if (this.cellIndex > this._toIndex) {
  54827. if (this._loopAnimation) {
  54828. this.cellIndex = this._fromIndex;
  54829. }
  54830. else {
  54831. this.cellIndex = this._toIndex;
  54832. this._animationStarted = false;
  54833. if (this._onAnimationEnd) {
  54834. this._onAnimationEnd();
  54835. }
  54836. if (this.disposeWhenFinishedAnimating) {
  54837. this.dispose();
  54838. }
  54839. }
  54840. }
  54841. }
  54842. };
  54843. Sprite.prototype.dispose = function () {
  54844. for (var i = 0; i < this._manager.sprites.length; i++) {
  54845. if (this._manager.sprites[i] == this) {
  54846. this._manager.sprites.splice(i, 1);
  54847. }
  54848. }
  54849. };
  54850. return Sprite;
  54851. }());
  54852. BABYLON.Sprite = Sprite;
  54853. })(BABYLON || (BABYLON = {}));
  54854. //# sourceMappingURL=babylon.sprite.js.map
  54855. var BABYLON;
  54856. (function (BABYLON) {
  54857. var IntersectionInfo = /** @class */ (function () {
  54858. function IntersectionInfo(bu, bv, distance) {
  54859. this.bu = bu;
  54860. this.bv = bv;
  54861. this.distance = distance;
  54862. this.faceId = 0;
  54863. this.subMeshId = 0;
  54864. }
  54865. return IntersectionInfo;
  54866. }());
  54867. BABYLON.IntersectionInfo = IntersectionInfo;
  54868. /**
  54869. * Information about the result of picking within a scene
  54870. * See https://doc.babylonjs.com/babylon101/picking_collisions
  54871. */
  54872. var PickingInfo = /** @class */ (function () {
  54873. function PickingInfo() {
  54874. /**
  54875. * If the pick collided with an object
  54876. */
  54877. this.hit = false;
  54878. /**
  54879. * Distance away where the pick collided
  54880. */
  54881. this.distance = 0;
  54882. /**
  54883. * The location of pick collision
  54884. */
  54885. this.pickedPoint = null;
  54886. /**
  54887. * The mesh corrisponding the the pick collision
  54888. */
  54889. this.pickedMesh = null;
  54890. /** (See getTextureCoordinates) The barycentric U coordinate that is used when calulating the texture coordinates of the collision.*/
  54891. this.bu = 0;
  54892. /** (See getTextureCoordinates) The barycentric V coordinate that is used when calulating the texture coordinates of the collision.*/
  54893. this.bv = 0;
  54894. /** The id of the face on the mesh that was picked */
  54895. this.faceId = -1;
  54896. /** Id of the the submesh that was picked */
  54897. this.subMeshId = 0;
  54898. /** If a sprite was picked, this will be the sprite the pick collided with */
  54899. this.pickedSprite = null;
  54900. /**
  54901. * If a mesh was used to do the picking (eg. 6dof controller) this will be populated.
  54902. */
  54903. this.originMesh = null;
  54904. /**
  54905. * The ray that was used to perform the picking.
  54906. */
  54907. this.ray = null;
  54908. }
  54909. /**
  54910. * Gets the normal corrispodning to the face the pick collided with
  54911. * @param useWorldCoordinates If the resulting normal should be relative to the world (default: false)
  54912. * @param useVerticesNormals If the vertices normals should be used to calculate the normal instead of the normal map
  54913. * @returns The normal corrispodning to the face the pick collided with
  54914. */
  54915. PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) {
  54916. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  54917. if (useVerticesNormals === void 0) { useVerticesNormals = true; }
  54918. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  54919. return null;
  54920. }
  54921. var indices = this.pickedMesh.getIndices();
  54922. if (!indices) {
  54923. return null;
  54924. }
  54925. var result;
  54926. if (useVerticesNormals) {
  54927. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  54928. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  54929. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  54930. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  54931. normal0 = normal0.scale(this.bu);
  54932. normal1 = normal1.scale(this.bv);
  54933. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  54934. result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  54935. }
  54936. else {
  54937. var positions = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  54938. var vertex1 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3] * 3);
  54939. var vertex2 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 1] * 3);
  54940. var vertex3 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 2] * 3);
  54941. var p1p2 = vertex1.subtract(vertex2);
  54942. var p3p2 = vertex3.subtract(vertex2);
  54943. result = BABYLON.Vector3.Cross(p1p2, p3p2);
  54944. }
  54945. if (useWorldCoordinates) {
  54946. result = BABYLON.Vector3.TransformNormal(result, this.pickedMesh.getWorldMatrix());
  54947. }
  54948. return BABYLON.Vector3.Normalize(result);
  54949. };
  54950. /**
  54951. * Gets the texture coordinates of where the pick occured
  54952. * @returns the vector containing the coordnates of the texture
  54953. */
  54954. PickingInfo.prototype.getTextureCoordinates = function () {
  54955. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  54956. return null;
  54957. }
  54958. var indices = this.pickedMesh.getIndices();
  54959. if (!indices) {
  54960. return null;
  54961. }
  54962. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  54963. if (!uvs) {
  54964. return null;
  54965. }
  54966. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  54967. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  54968. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  54969. uv0 = uv0.scale(1.0 - this.bu - this.bv);
  54970. uv1 = uv1.scale(this.bu);
  54971. uv2 = uv2.scale(this.bv);
  54972. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  54973. };
  54974. return PickingInfo;
  54975. }());
  54976. BABYLON.PickingInfo = PickingInfo;
  54977. })(BABYLON || (BABYLON = {}));
  54978. //# sourceMappingURL=babylon.pickingInfo.js.map
  54979. var BABYLON;
  54980. (function (BABYLON) {
  54981. var Ray = /** @class */ (function () {
  54982. function Ray(origin, direction, length) {
  54983. if (length === void 0) { length = Number.MAX_VALUE; }
  54984. this.origin = origin;
  54985. this.direction = direction;
  54986. this.length = length;
  54987. }
  54988. // Methods
  54989. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  54990. var d = 0.0;
  54991. var maxValue = Number.MAX_VALUE;
  54992. var inv;
  54993. var min;
  54994. var max;
  54995. var temp;
  54996. if (Math.abs(this.direction.x) < 0.0000001) {
  54997. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  54998. return false;
  54999. }
  55000. }
  55001. else {
  55002. inv = 1.0 / this.direction.x;
  55003. min = (minimum.x - this.origin.x) * inv;
  55004. max = (maximum.x - this.origin.x) * inv;
  55005. if (max === -Infinity) {
  55006. max = Infinity;
  55007. }
  55008. if (min > max) {
  55009. temp = min;
  55010. min = max;
  55011. max = temp;
  55012. }
  55013. d = Math.max(min, d);
  55014. maxValue = Math.min(max, maxValue);
  55015. if (d > maxValue) {
  55016. return false;
  55017. }
  55018. }
  55019. if (Math.abs(this.direction.y) < 0.0000001) {
  55020. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  55021. return false;
  55022. }
  55023. }
  55024. else {
  55025. inv = 1.0 / this.direction.y;
  55026. min = (minimum.y - this.origin.y) * inv;
  55027. max = (maximum.y - this.origin.y) * inv;
  55028. if (max === -Infinity) {
  55029. max = Infinity;
  55030. }
  55031. if (min > max) {
  55032. temp = min;
  55033. min = max;
  55034. max = temp;
  55035. }
  55036. d = Math.max(min, d);
  55037. maxValue = Math.min(max, maxValue);
  55038. if (d > maxValue) {
  55039. return false;
  55040. }
  55041. }
  55042. if (Math.abs(this.direction.z) < 0.0000001) {
  55043. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  55044. return false;
  55045. }
  55046. }
  55047. else {
  55048. inv = 1.0 / this.direction.z;
  55049. min = (minimum.z - this.origin.z) * inv;
  55050. max = (maximum.z - this.origin.z) * inv;
  55051. if (max === -Infinity) {
  55052. max = Infinity;
  55053. }
  55054. if (min > max) {
  55055. temp = min;
  55056. min = max;
  55057. max = temp;
  55058. }
  55059. d = Math.max(min, d);
  55060. maxValue = Math.min(max, maxValue);
  55061. if (d > maxValue) {
  55062. return false;
  55063. }
  55064. }
  55065. return true;
  55066. };
  55067. Ray.prototype.intersectsBox = function (box) {
  55068. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  55069. };
  55070. Ray.prototype.intersectsSphere = function (sphere) {
  55071. var x = sphere.center.x - this.origin.x;
  55072. var y = sphere.center.y - this.origin.y;
  55073. var z = sphere.center.z - this.origin.z;
  55074. var pyth = (x * x) + (y * y) + (z * z);
  55075. var rr = sphere.radius * sphere.radius;
  55076. if (pyth <= rr) {
  55077. return true;
  55078. }
  55079. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  55080. if (dot < 0.0) {
  55081. return false;
  55082. }
  55083. var temp = pyth - (dot * dot);
  55084. return temp <= rr;
  55085. };
  55086. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  55087. if (!this._edge1) {
  55088. this._edge1 = BABYLON.Vector3.Zero();
  55089. this._edge2 = BABYLON.Vector3.Zero();
  55090. this._pvec = BABYLON.Vector3.Zero();
  55091. this._tvec = BABYLON.Vector3.Zero();
  55092. this._qvec = BABYLON.Vector3.Zero();
  55093. }
  55094. vertex1.subtractToRef(vertex0, this._edge1);
  55095. vertex2.subtractToRef(vertex0, this._edge2);
  55096. BABYLON.Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  55097. var det = BABYLON.Vector3.Dot(this._edge1, this._pvec);
  55098. if (det === 0) {
  55099. return null;
  55100. }
  55101. var invdet = 1 / det;
  55102. this.origin.subtractToRef(vertex0, this._tvec);
  55103. var bu = BABYLON.Vector3.Dot(this._tvec, this._pvec) * invdet;
  55104. if (bu < 0 || bu > 1.0) {
  55105. return null;
  55106. }
  55107. BABYLON.Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  55108. var bv = BABYLON.Vector3.Dot(this.direction, this._qvec) * invdet;
  55109. if (bv < 0 || bu + bv > 1.0) {
  55110. return null;
  55111. }
  55112. //check if the distance is longer than the predefined length.
  55113. var distance = BABYLON.Vector3.Dot(this._edge2, this._qvec) * invdet;
  55114. if (distance > this.length) {
  55115. return null;
  55116. }
  55117. return new BABYLON.IntersectionInfo(bu, bv, distance);
  55118. };
  55119. Ray.prototype.intersectsPlane = function (plane) {
  55120. var distance;
  55121. var result1 = BABYLON.Vector3.Dot(plane.normal, this.direction);
  55122. if (Math.abs(result1) < 9.99999997475243E-07) {
  55123. return null;
  55124. }
  55125. else {
  55126. var result2 = BABYLON.Vector3.Dot(plane.normal, this.origin);
  55127. distance = (-plane.d - result2) / result1;
  55128. if (distance < 0.0) {
  55129. if (distance < -9.99999997475243E-07) {
  55130. return null;
  55131. }
  55132. else {
  55133. return 0;
  55134. }
  55135. }
  55136. return distance;
  55137. }
  55138. };
  55139. Ray.prototype.intersectsMesh = function (mesh, fastCheck) {
  55140. var tm = BABYLON.Tmp.Matrix[0];
  55141. mesh.getWorldMatrix().invertToRef(tm);
  55142. if (this._tmpRay) {
  55143. Ray.TransformToRef(this, tm, this._tmpRay);
  55144. }
  55145. else {
  55146. this._tmpRay = Ray.Transform(this, tm);
  55147. }
  55148. return mesh.intersects(this._tmpRay, fastCheck);
  55149. };
  55150. Ray.prototype.intersectsMeshes = function (meshes, fastCheck, results) {
  55151. if (results) {
  55152. results.length = 0;
  55153. }
  55154. else {
  55155. results = [];
  55156. }
  55157. for (var i = 0; i < meshes.length; i++) {
  55158. var pickInfo = this.intersectsMesh(meshes[i], fastCheck);
  55159. if (pickInfo.hit) {
  55160. results.push(pickInfo);
  55161. }
  55162. }
  55163. results.sort(this._comparePickingInfo);
  55164. return results;
  55165. };
  55166. Ray.prototype._comparePickingInfo = function (pickingInfoA, pickingInfoB) {
  55167. if (pickingInfoA.distance < pickingInfoB.distance) {
  55168. return -1;
  55169. }
  55170. else if (pickingInfoA.distance > pickingInfoB.distance) {
  55171. return 1;
  55172. }
  55173. else {
  55174. return 0;
  55175. }
  55176. };
  55177. /**
  55178. * Intersection test between the ray and a given segment whithin a given tolerance (threshold)
  55179. * @param sega the first point of the segment to test the intersection against
  55180. * @param segb the second point of the segment to test the intersection against
  55181. * @param threshold the tolerance margin, if the ray doesn't intersect the segment but is close to the given threshold, the intersection is successful
  55182. * @return the distance from the ray origin to the intersection point if there's intersection, or -1 if there's no intersection
  55183. */
  55184. Ray.prototype.intersectionSegment = function (sega, segb, threshold) {
  55185. var rsegb = this.origin.add(this.direction.multiplyByFloats(Ray.rayl, Ray.rayl, Ray.rayl));
  55186. var u = segb.subtract(sega);
  55187. var v = rsegb.subtract(this.origin);
  55188. var w = sega.subtract(this.origin);
  55189. var a = BABYLON.Vector3.Dot(u, u); // always >= 0
  55190. var b = BABYLON.Vector3.Dot(u, v);
  55191. var c = BABYLON.Vector3.Dot(v, v); // always >= 0
  55192. var d = BABYLON.Vector3.Dot(u, w);
  55193. var e = BABYLON.Vector3.Dot(v, w);
  55194. var D = a * c - b * b; // always >= 0
  55195. var sc, sN, sD = D; // sc = sN / sD, default sD = D >= 0
  55196. var tc, tN, tD = D; // tc = tN / tD, default tD = D >= 0
  55197. // compute the line parameters of the two closest points
  55198. if (D < Ray.smallnum) { // the lines are almost parallel
  55199. sN = 0.0; // force using point P0 on segment S1
  55200. sD = 1.0; // to prevent possible division by 0.0 later
  55201. tN = e;
  55202. tD = c;
  55203. }
  55204. else { // get the closest points on the infinite lines
  55205. sN = (b * e - c * d);
  55206. tN = (a * e - b * d);
  55207. if (sN < 0.0) { // sc < 0 => the s=0 edge is visible
  55208. sN = 0.0;
  55209. tN = e;
  55210. tD = c;
  55211. }
  55212. else if (sN > sD) { // sc > 1 => the s=1 edge is visible
  55213. sN = sD;
  55214. tN = e + b;
  55215. tD = c;
  55216. }
  55217. }
  55218. if (tN < 0.0) { // tc < 0 => the t=0 edge is visible
  55219. tN = 0.0;
  55220. // recompute sc for this edge
  55221. if (-d < 0.0) {
  55222. sN = 0.0;
  55223. }
  55224. else if (-d > a)
  55225. sN = sD;
  55226. else {
  55227. sN = -d;
  55228. sD = a;
  55229. }
  55230. }
  55231. else if (tN > tD) { // tc > 1 => the t=1 edge is visible
  55232. tN = tD;
  55233. // recompute sc for this edge
  55234. if ((-d + b) < 0.0) {
  55235. sN = 0;
  55236. }
  55237. else if ((-d + b) > a) {
  55238. sN = sD;
  55239. }
  55240. else {
  55241. sN = (-d + b);
  55242. sD = a;
  55243. }
  55244. }
  55245. // finally do the division to get sc and tc
  55246. sc = (Math.abs(sN) < Ray.smallnum ? 0.0 : sN / sD);
  55247. tc = (Math.abs(tN) < Ray.smallnum ? 0.0 : tN / tD);
  55248. // get the difference of the two closest points
  55249. var qtc = v.multiplyByFloats(tc, tc, tc);
  55250. var dP = w.add(u.multiplyByFloats(sc, sc, sc)).subtract(qtc); // = S1(sc) - S2(tc)
  55251. var isIntersected = (tc > 0) && (tc <= this.length) && (dP.lengthSquared() < (threshold * threshold)); // return intersection result
  55252. if (isIntersected) {
  55253. return qtc.length();
  55254. }
  55255. return -1;
  55256. };
  55257. Ray.prototype.update = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  55258. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 0, viewportWidth, viewportHeight, world, view, projection, this.origin);
  55259. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 1, viewportWidth, viewportHeight, world, view, projection, BABYLON.Tmp.Vector3[0]);
  55260. BABYLON.Tmp.Vector3[0].subtractToRef(this.origin, this.direction);
  55261. this.direction.normalize();
  55262. return this;
  55263. };
  55264. // Statics
  55265. Ray.Zero = function () {
  55266. return new Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero());
  55267. };
  55268. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  55269. var result = Ray.Zero();
  55270. return result.update(x, y, viewportWidth, viewportHeight, world, view, projection);
  55271. };
  55272. /**
  55273. * 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
  55274. * transformed to the given world matrix.
  55275. * @param origin The origin point
  55276. * @param end The end point
  55277. * @param world a matrix to transform the ray to. Default is the identity matrix.
  55278. */
  55279. Ray.CreateNewFromTo = function (origin, end, world) {
  55280. if (world === void 0) { world = BABYLON.Matrix.Identity(); }
  55281. var direction = end.subtract(origin);
  55282. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  55283. direction.normalize();
  55284. return Ray.Transform(new Ray(origin, direction, length), world);
  55285. };
  55286. Ray.Transform = function (ray, matrix) {
  55287. var result = new Ray(new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 0, 0));
  55288. Ray.TransformToRef(ray, matrix, result);
  55289. return result;
  55290. };
  55291. Ray.TransformToRef = function (ray, matrix, result) {
  55292. BABYLON.Vector3.TransformCoordinatesToRef(ray.origin, matrix, result.origin);
  55293. BABYLON.Vector3.TransformNormalToRef(ray.direction, matrix, result.direction);
  55294. result.length = ray.length;
  55295. var dir = result.direction;
  55296. var len = dir.length();
  55297. if (!(len === 0 || len === 1)) {
  55298. var num = 1.0 / len;
  55299. dir.x *= num;
  55300. dir.y *= num;
  55301. dir.z *= num;
  55302. result.length *= len;
  55303. }
  55304. };
  55305. Ray.smallnum = 0.00000001;
  55306. Ray.rayl = 10e8;
  55307. return Ray;
  55308. }());
  55309. BABYLON.Ray = Ray;
  55310. })(BABYLON || (BABYLON = {}));
  55311. //# sourceMappingURL=babylon.ray.js.map
  55312. var BABYLON;
  55313. (function (BABYLON) {
  55314. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  55315. if (boxMin.x > sphereCenter.x + sphereRadius)
  55316. return false;
  55317. if (sphereCenter.x - sphereRadius > boxMax.x)
  55318. return false;
  55319. if (boxMin.y > sphereCenter.y + sphereRadius)
  55320. return false;
  55321. if (sphereCenter.y - sphereRadius > boxMax.y)
  55322. return false;
  55323. if (boxMin.z > sphereCenter.z + sphereRadius)
  55324. return false;
  55325. if (sphereCenter.z - sphereRadius > boxMax.z)
  55326. return false;
  55327. return true;
  55328. };
  55329. var getLowestRoot = (function () {
  55330. var result = { root: 0, found: false };
  55331. return function (a, b, c, maxR) {
  55332. result.root = 0;
  55333. result.found = false;
  55334. var determinant = b * b - 4.0 * a * c;
  55335. if (determinant < 0)
  55336. return result;
  55337. var sqrtD = Math.sqrt(determinant);
  55338. var r1 = (-b - sqrtD) / (2.0 * a);
  55339. var r2 = (-b + sqrtD) / (2.0 * a);
  55340. if (r1 > r2) {
  55341. var temp = r2;
  55342. r2 = r1;
  55343. r1 = temp;
  55344. }
  55345. if (r1 > 0 && r1 < maxR) {
  55346. result.root = r1;
  55347. result.found = true;
  55348. return result;
  55349. }
  55350. if (r2 > 0 && r2 < maxR) {
  55351. result.root = r2;
  55352. result.found = true;
  55353. return result;
  55354. }
  55355. return result;
  55356. };
  55357. })();
  55358. var Collider = /** @class */ (function () {
  55359. function Collider() {
  55360. this._collisionPoint = BABYLON.Vector3.Zero();
  55361. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  55362. this._tempVector = BABYLON.Vector3.Zero();
  55363. this._tempVector2 = BABYLON.Vector3.Zero();
  55364. this._tempVector3 = BABYLON.Vector3.Zero();
  55365. this._tempVector4 = BABYLON.Vector3.Zero();
  55366. this._edge = BABYLON.Vector3.Zero();
  55367. this._baseToVertex = BABYLON.Vector3.Zero();
  55368. this._destinationPoint = BABYLON.Vector3.Zero();
  55369. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  55370. this._displacementVector = BABYLON.Vector3.Zero();
  55371. this._radius = BABYLON.Vector3.One();
  55372. this._retry = 0;
  55373. this._basePointWorld = BABYLON.Vector3.Zero();
  55374. this._velocityWorld = BABYLON.Vector3.Zero();
  55375. this._normalizedVelocity = BABYLON.Vector3.Zero();
  55376. this._collisionMask = -1;
  55377. }
  55378. Object.defineProperty(Collider.prototype, "collisionMask", {
  55379. get: function () {
  55380. return this._collisionMask;
  55381. },
  55382. set: function (mask) {
  55383. this._collisionMask = !isNaN(mask) ? mask : -1;
  55384. },
  55385. enumerable: true,
  55386. configurable: true
  55387. });
  55388. Object.defineProperty(Collider.prototype, "slidePlaneNormal", {
  55389. /**
  55390. * Gets the plane normal used to compute the sliding response (in local space)
  55391. */
  55392. get: function () {
  55393. return this._slidePlaneNormal;
  55394. },
  55395. enumerable: true,
  55396. configurable: true
  55397. });
  55398. // Methods
  55399. Collider.prototype._initialize = function (source, dir, e) {
  55400. this._velocity = dir;
  55401. BABYLON.Vector3.NormalizeToRef(dir, this._normalizedVelocity);
  55402. this._basePoint = source;
  55403. source.multiplyToRef(this._radius, this._basePointWorld);
  55404. dir.multiplyToRef(this._radius, this._velocityWorld);
  55405. this._velocityWorldLength = this._velocityWorld.length();
  55406. this._epsilon = e;
  55407. this.collisionFound = false;
  55408. };
  55409. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  55410. pa.subtractToRef(point, this._tempVector);
  55411. pb.subtractToRef(point, this._tempVector2);
  55412. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  55413. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  55414. if (d < 0)
  55415. return false;
  55416. pc.subtractToRef(point, this._tempVector3);
  55417. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  55418. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  55419. if (d < 0)
  55420. return false;
  55421. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  55422. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  55423. return d >= 0;
  55424. };
  55425. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  55426. var distance = BABYLON.Vector3.Distance(this._basePointWorld, sphereCenter);
  55427. var max = Math.max(this._radius.x, this._radius.y, this._radius.z);
  55428. if (distance > this._velocityWorldLength + max + sphereRadius) {
  55429. return false;
  55430. }
  55431. if (!intersectBoxAASphere(vecMin, vecMax, this._basePointWorld, this._velocityWorldLength + max))
  55432. return false;
  55433. return true;
  55434. };
  55435. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  55436. var t0;
  55437. var embeddedInPlane = false;
  55438. //defensive programming, actually not needed.
  55439. if (!trianglePlaneArray) {
  55440. trianglePlaneArray = [];
  55441. }
  55442. if (!trianglePlaneArray[faceIndex]) {
  55443. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  55444. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  55445. }
  55446. var trianglePlane = trianglePlaneArray[faceIndex];
  55447. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this._normalizedVelocity, 0))
  55448. return;
  55449. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this._basePoint);
  55450. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this._velocity);
  55451. if (normalDotVelocity == 0) {
  55452. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  55453. return;
  55454. embeddedInPlane = true;
  55455. t0 = 0;
  55456. }
  55457. else {
  55458. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  55459. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  55460. if (t0 > t1) {
  55461. var temp = t1;
  55462. t1 = t0;
  55463. t0 = temp;
  55464. }
  55465. if (t0 > 1.0 || t1 < 0.0)
  55466. return;
  55467. if (t0 < 0)
  55468. t0 = 0;
  55469. if (t0 > 1.0)
  55470. t0 = 1.0;
  55471. }
  55472. this._collisionPoint.copyFromFloats(0, 0, 0);
  55473. var found = false;
  55474. var t = 1.0;
  55475. if (!embeddedInPlane) {
  55476. this._basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  55477. this._velocity.scaleToRef(t0, this._tempVector);
  55478. this._planeIntersectionPoint.addInPlace(this._tempVector);
  55479. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  55480. found = true;
  55481. t = t0;
  55482. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  55483. }
  55484. }
  55485. if (!found) {
  55486. var velocitySquaredLength = this._velocity.lengthSquared();
  55487. var a = velocitySquaredLength;
  55488. this._basePoint.subtractToRef(p1, this._tempVector);
  55489. var b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  55490. var c = this._tempVector.lengthSquared() - 1.0;
  55491. var lowestRoot = getLowestRoot(a, b, c, t);
  55492. if (lowestRoot.found) {
  55493. t = lowestRoot.root;
  55494. found = true;
  55495. this._collisionPoint.copyFrom(p1);
  55496. }
  55497. this._basePoint.subtractToRef(p2, this._tempVector);
  55498. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  55499. c = this._tempVector.lengthSquared() - 1.0;
  55500. lowestRoot = getLowestRoot(a, b, c, t);
  55501. if (lowestRoot.found) {
  55502. t = lowestRoot.root;
  55503. found = true;
  55504. this._collisionPoint.copyFrom(p2);
  55505. }
  55506. this._basePoint.subtractToRef(p3, this._tempVector);
  55507. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  55508. c = this._tempVector.lengthSquared() - 1.0;
  55509. lowestRoot = getLowestRoot(a, b, c, t);
  55510. if (lowestRoot.found) {
  55511. t = lowestRoot.root;
  55512. found = true;
  55513. this._collisionPoint.copyFrom(p3);
  55514. }
  55515. p2.subtractToRef(p1, this._edge);
  55516. p1.subtractToRef(this._basePoint, this._baseToVertex);
  55517. var edgeSquaredLength = this._edge.lengthSquared();
  55518. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  55519. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  55520. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  55521. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  55522. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  55523. lowestRoot = getLowestRoot(a, b, c, t);
  55524. if (lowestRoot.found) {
  55525. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  55526. if (f >= 0.0 && f <= 1.0) {
  55527. t = lowestRoot.root;
  55528. found = true;
  55529. this._edge.scaleInPlace(f);
  55530. p1.addToRef(this._edge, this._collisionPoint);
  55531. }
  55532. }
  55533. p3.subtractToRef(p2, this._edge);
  55534. p2.subtractToRef(this._basePoint, this._baseToVertex);
  55535. edgeSquaredLength = this._edge.lengthSquared();
  55536. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  55537. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  55538. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  55539. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  55540. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  55541. lowestRoot = getLowestRoot(a, b, c, t);
  55542. if (lowestRoot.found) {
  55543. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  55544. if (f >= 0.0 && f <= 1.0) {
  55545. t = lowestRoot.root;
  55546. found = true;
  55547. this._edge.scaleInPlace(f);
  55548. p2.addToRef(this._edge, this._collisionPoint);
  55549. }
  55550. }
  55551. p1.subtractToRef(p3, this._edge);
  55552. p3.subtractToRef(this._basePoint, this._baseToVertex);
  55553. edgeSquaredLength = this._edge.lengthSquared();
  55554. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  55555. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  55556. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  55557. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  55558. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  55559. lowestRoot = getLowestRoot(a, b, c, t);
  55560. if (lowestRoot.found) {
  55561. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  55562. if (f >= 0.0 && f <= 1.0) {
  55563. t = lowestRoot.root;
  55564. found = true;
  55565. this._edge.scaleInPlace(f);
  55566. p3.addToRef(this._edge, this._collisionPoint);
  55567. }
  55568. }
  55569. }
  55570. if (found) {
  55571. var distToCollision = t * this._velocity.length();
  55572. if (!this.collisionFound || distToCollision < this._nearestDistance) {
  55573. if (!this.intersectionPoint) {
  55574. this.intersectionPoint = this._collisionPoint.clone();
  55575. }
  55576. else {
  55577. this.intersectionPoint.copyFrom(this._collisionPoint);
  55578. }
  55579. this._nearestDistance = distToCollision;
  55580. this.collisionFound = true;
  55581. }
  55582. }
  55583. };
  55584. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  55585. for (var i = indexStart; i < indexEnd; i += 3) {
  55586. var p1 = pts[indices[i] - decal];
  55587. var p2 = pts[indices[i + 1] - decal];
  55588. var p3 = pts[indices[i + 2] - decal];
  55589. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  55590. }
  55591. };
  55592. Collider.prototype._getResponse = function (pos, vel) {
  55593. pos.addToRef(vel, this._destinationPoint);
  55594. vel.scaleInPlace((this._nearestDistance / vel.length()));
  55595. this._basePoint.addToRef(vel, pos);
  55596. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  55597. this._slidePlaneNormal.normalize();
  55598. this._slidePlaneNormal.scaleToRef(this._epsilon, this._displacementVector);
  55599. pos.addInPlace(this._displacementVector);
  55600. this.intersectionPoint.addInPlace(this._displacementVector);
  55601. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  55602. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  55603. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  55604. };
  55605. return Collider;
  55606. }());
  55607. BABYLON.Collider = Collider;
  55608. })(BABYLON || (BABYLON = {}));
  55609. //# sourceMappingURL=babylon.collider.js.map
  55610. var BABYLON;
  55611. (function (BABYLON) {
  55612. //WebWorker code will be inserted to this variable.
  55613. BABYLON.CollisionWorker = "";
  55614. /** Defines supported task for worker process */
  55615. var WorkerTaskType;
  55616. (function (WorkerTaskType) {
  55617. /** Initialization */
  55618. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  55619. /** Update of geometry */
  55620. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  55621. /** Evaluate collision */
  55622. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  55623. })(WorkerTaskType = BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  55624. /** Defines kind of replies returned by worker */
  55625. var WorkerReplyType;
  55626. (function (WorkerReplyType) {
  55627. /** Success */
  55628. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  55629. /** Unkown error */
  55630. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  55631. })(WorkerReplyType = BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  55632. var CollisionCoordinatorWorker = /** @class */ (function () {
  55633. function CollisionCoordinatorWorker() {
  55634. var _this = this;
  55635. this._scaledPosition = BABYLON.Vector3.Zero();
  55636. this._scaledVelocity = BABYLON.Vector3.Zero();
  55637. this.onMeshUpdated = function (transformNode) {
  55638. _this._addUpdateMeshesList[transformNode.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(transformNode);
  55639. };
  55640. this.onGeometryUpdated = function (geometry) {
  55641. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  55642. };
  55643. this._afterRender = function () {
  55644. if (!_this._init)
  55645. return;
  55646. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  55647. return;
  55648. }
  55649. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  55650. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  55651. if (_this._runningUpdated > 4) {
  55652. return;
  55653. }
  55654. ++_this._runningUpdated;
  55655. var payload = {
  55656. updatedMeshes: _this._addUpdateMeshesList,
  55657. updatedGeometries: _this._addUpdateGeometriesList,
  55658. removedGeometries: _this._toRemoveGeometryArray,
  55659. removedMeshes: _this._toRemoveMeshesArray
  55660. };
  55661. var message = {
  55662. payload: payload,
  55663. taskType: WorkerTaskType.UPDATE
  55664. };
  55665. var serializable = [];
  55666. for (var id in payload.updatedGeometries) {
  55667. if (payload.updatedGeometries.hasOwnProperty(id)) {
  55668. //prepare transferables
  55669. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  55670. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  55671. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  55672. }
  55673. }
  55674. _this._worker.postMessage(message, serializable);
  55675. _this._addUpdateMeshesList = {};
  55676. _this._addUpdateGeometriesList = {};
  55677. _this._toRemoveGeometryArray = [];
  55678. _this._toRemoveMeshesArray = [];
  55679. };
  55680. this._onMessageFromWorker = function (e) {
  55681. var returnData = e.data;
  55682. if (returnData.error != WorkerReplyType.SUCCESS) {
  55683. //TODO what errors can be returned from the worker?
  55684. BABYLON.Tools.Warn("error returned from worker!");
  55685. return;
  55686. }
  55687. switch (returnData.taskType) {
  55688. case WorkerTaskType.INIT:
  55689. _this._init = true;
  55690. //Update the worked with ALL of the scene's current state
  55691. _this._scene.meshes.forEach(function (mesh) {
  55692. _this.onMeshAdded(mesh);
  55693. });
  55694. _this._scene.getGeometries().forEach(function (geometry) {
  55695. _this.onGeometryAdded(geometry);
  55696. });
  55697. break;
  55698. case WorkerTaskType.UPDATE:
  55699. _this._runningUpdated--;
  55700. break;
  55701. case WorkerTaskType.COLLIDE:
  55702. var returnPayload = returnData.payload;
  55703. if (!_this._collisionsCallbackArray[returnPayload.collisionId])
  55704. return;
  55705. var callback = _this._collisionsCallbackArray[returnPayload.collisionId];
  55706. if (callback) {
  55707. var mesh = _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId);
  55708. if (mesh) {
  55709. callback(returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), mesh);
  55710. }
  55711. }
  55712. //cleanup
  55713. _this._collisionsCallbackArray[returnPayload.collisionId] = null;
  55714. break;
  55715. }
  55716. };
  55717. this._collisionsCallbackArray = [];
  55718. this._init = false;
  55719. this._runningUpdated = 0;
  55720. this._addUpdateMeshesList = {};
  55721. this._addUpdateGeometriesList = {};
  55722. this._toRemoveGeometryArray = [];
  55723. this._toRemoveMeshesArray = [];
  55724. }
  55725. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  55726. if (!this._init)
  55727. return;
  55728. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000])
  55729. return;
  55730. position.divideToRef(collider._radius, this._scaledPosition);
  55731. displacement.divideToRef(collider._radius, this._scaledVelocity);
  55732. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  55733. var payload = {
  55734. collider: {
  55735. position: this._scaledPosition.asArray(),
  55736. velocity: this._scaledVelocity.asArray(),
  55737. radius: collider._radius.asArray()
  55738. },
  55739. collisionId: collisionIndex,
  55740. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  55741. maximumRetry: maximumRetry
  55742. };
  55743. var message = {
  55744. payload: payload,
  55745. taskType: WorkerTaskType.COLLIDE
  55746. };
  55747. this._worker.postMessage(message);
  55748. };
  55749. CollisionCoordinatorWorker.prototype.init = function (scene) {
  55750. this._scene = scene;
  55751. this._scene.registerAfterRender(this._afterRender);
  55752. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  55753. this._worker = new Worker(workerUrl);
  55754. this._worker.onmessage = this._onMessageFromWorker;
  55755. var message = {
  55756. payload: {},
  55757. taskType: WorkerTaskType.INIT
  55758. };
  55759. this._worker.postMessage(message);
  55760. };
  55761. CollisionCoordinatorWorker.prototype.destroy = function () {
  55762. this._scene.unregisterAfterRender(this._afterRender);
  55763. this._worker.terminate();
  55764. };
  55765. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  55766. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  55767. this.onMeshUpdated(mesh);
  55768. };
  55769. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  55770. this._toRemoveMeshesArray.push(mesh.uniqueId);
  55771. };
  55772. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  55773. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  55774. geometry.onGeometryUpdated = this.onGeometryUpdated;
  55775. this.onGeometryUpdated(geometry);
  55776. };
  55777. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  55778. this._toRemoveGeometryArray.push(geometry.id);
  55779. };
  55780. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  55781. var submeshes = [];
  55782. if (mesh.subMeshes) {
  55783. submeshes = mesh.subMeshes.map(function (sm, idx) {
  55784. var boundingInfo = sm.getBoundingInfo();
  55785. return {
  55786. position: idx,
  55787. verticesStart: sm.verticesStart,
  55788. verticesCount: sm.verticesCount,
  55789. indexStart: sm.indexStart,
  55790. indexCount: sm.indexCount,
  55791. hasMaterial: !!sm.getMaterial(),
  55792. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  55793. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  55794. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  55795. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray()
  55796. };
  55797. });
  55798. }
  55799. var geometryId = null;
  55800. if (mesh instanceof BABYLON.Mesh) {
  55801. var geometry = mesh.geometry;
  55802. geometryId = geometry ? geometry.id : null;
  55803. }
  55804. else if (mesh instanceof BABYLON.InstancedMesh) {
  55805. var geometry = mesh.sourceMesh && mesh.sourceMesh.geometry;
  55806. geometryId = geometry ? geometry.id : null;
  55807. }
  55808. var boundingInfo = mesh.getBoundingInfo();
  55809. return {
  55810. uniqueId: mesh.uniqueId,
  55811. id: mesh.id,
  55812. name: mesh.name,
  55813. geometryId: geometryId,
  55814. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  55815. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  55816. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  55817. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray(),
  55818. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  55819. subMeshes: submeshes,
  55820. checkCollisions: mesh.checkCollisions
  55821. };
  55822. };
  55823. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  55824. return {
  55825. id: geometry.id,
  55826. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  55827. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  55828. indices: new Uint32Array(geometry.getIndices() || []),
  55829. };
  55830. };
  55831. return CollisionCoordinatorWorker;
  55832. }());
  55833. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  55834. var CollisionCoordinatorLegacy = /** @class */ (function () {
  55835. function CollisionCoordinatorLegacy() {
  55836. this._scaledPosition = BABYLON.Vector3.Zero();
  55837. this._scaledVelocity = BABYLON.Vector3.Zero();
  55838. this._finalPosition = BABYLON.Vector3.Zero();
  55839. }
  55840. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  55841. position.divideToRef(collider._radius, this._scaledPosition);
  55842. displacement.divideToRef(collider._radius, this._scaledVelocity);
  55843. collider.collidedMesh = null;
  55844. collider._retry = 0;
  55845. collider._initialVelocity = this._scaledVelocity;
  55846. collider._initialPosition = this._scaledPosition;
  55847. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  55848. this._finalPosition.multiplyInPlace(collider._radius);
  55849. //run the callback
  55850. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  55851. };
  55852. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  55853. this._scene = scene;
  55854. };
  55855. CollisionCoordinatorLegacy.prototype.destroy = function () {
  55856. //Legacy need no destruction method.
  55857. };
  55858. //No update in legacy mode
  55859. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
  55860. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
  55861. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
  55862. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
  55863. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
  55864. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
  55865. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  55866. if (excludedMesh === void 0) { excludedMesh = null; }
  55867. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  55868. if (collider._retry >= maximumRetry) {
  55869. finalPosition.copyFrom(position);
  55870. return;
  55871. }
  55872. // Check if this is a mesh else camera or -1
  55873. var collisionMask = (excludedMesh ? excludedMesh.collisionMask : collider.collisionMask);
  55874. collider._initialize(position, velocity, closeDistance);
  55875. // Check all meshes
  55876. for (var index = 0; index < this._scene.meshes.length; index++) {
  55877. var mesh = this._scene.meshes[index];
  55878. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh && ((collisionMask & mesh.collisionGroup) !== 0)) {
  55879. mesh._checkCollision(collider);
  55880. }
  55881. }
  55882. if (!collider.collisionFound) {
  55883. position.addToRef(velocity, finalPosition);
  55884. return;
  55885. }
  55886. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  55887. collider._getResponse(position, velocity);
  55888. }
  55889. if (velocity.length() <= closeDistance) {
  55890. finalPosition.copyFrom(position);
  55891. return;
  55892. }
  55893. collider._retry++;
  55894. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  55895. };
  55896. return CollisionCoordinatorLegacy;
  55897. }());
  55898. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  55899. })(BABYLON || (BABYLON = {}));
  55900. //# sourceMappingURL=babylon.collisionCoordinator.js.map
  55901. var BABYLON;
  55902. (function (BABYLON) {
  55903. /**
  55904. * A particle represents one of the element emitted by a particle system.
  55905. * This is mainly define by its coordinates, direction, velocity and age.
  55906. */
  55907. var Particle = /** @class */ (function () {
  55908. /**
  55909. * Creates a new instance Particle
  55910. * @param particleSystem the particle system the particle belongs to
  55911. */
  55912. function Particle(
  55913. /**
  55914. * particleSystem the particle system the particle belongs to.
  55915. */
  55916. particleSystem) {
  55917. this.particleSystem = particleSystem;
  55918. /**
  55919. * The world position of the particle in the scene.
  55920. */
  55921. this.position = BABYLON.Vector3.Zero();
  55922. /**
  55923. * The world direction of the particle in the scene.
  55924. */
  55925. this.direction = BABYLON.Vector3.Zero();
  55926. /**
  55927. * The color of the particle.
  55928. */
  55929. this.color = new BABYLON.Color4(0, 0, 0, 0);
  55930. /**
  55931. * The color change of the particle per step.
  55932. */
  55933. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  55934. /**
  55935. * Defines how long will the life of the particle be.
  55936. */
  55937. this.lifeTime = 1.0;
  55938. /**
  55939. * The current age of the particle.
  55940. */
  55941. this.age = 0;
  55942. /**
  55943. * The current size of the particle.
  55944. */
  55945. this.size = 0;
  55946. /**
  55947. * The current angle of the particle.
  55948. */
  55949. this.angle = 0;
  55950. /**
  55951. * Defines how fast is the angle changing.
  55952. */
  55953. this.angularSpeed = 0;
  55954. /**
  55955. * Defines the cell index used by the particle to be rendered from a sprite.
  55956. */
  55957. this.cellIndex = 0;
  55958. this._currentFrameCounter = 0;
  55959. if (!this.particleSystem.isAnimationSheetEnabled) {
  55960. return;
  55961. }
  55962. this.updateCellInfoFromSystem();
  55963. }
  55964. Particle.prototype.updateCellInfoFromSystem = function () {
  55965. this.cellIndex = this.particleSystem.startSpriteCellID;
  55966. if (this.particleSystem.spriteCellChangeSpeed == 0) {
  55967. this.updateCellIndex = this._updateCellIndexWithSpeedCalculated;
  55968. }
  55969. else {
  55970. this.updateCellIndex = this._updateCellIndexWithCustomSpeed;
  55971. }
  55972. };
  55973. Particle.prototype._updateCellIndexWithSpeedCalculated = function (scaledUpdateSpeed) {
  55974. // (ageOffset / scaledUpdateSpeed) / available cells
  55975. var numberOfScaledUpdatesPerCell = ((this.lifeTime - this.age) / scaledUpdateSpeed) / (this.particleSystem.endSpriteCellID + 1 - this.cellIndex);
  55976. this._currentFrameCounter += scaledUpdateSpeed;
  55977. if (this._currentFrameCounter >= numberOfScaledUpdatesPerCell * scaledUpdateSpeed) {
  55978. this._currentFrameCounter = 0;
  55979. this.cellIndex++;
  55980. if (this.cellIndex > this.particleSystem.endSpriteCellID) {
  55981. this.cellIndex = this.particleSystem.endSpriteCellID;
  55982. }
  55983. }
  55984. };
  55985. Particle.prototype._updateCellIndexWithCustomSpeed = function () {
  55986. if (this._currentFrameCounter >= this.particleSystem.spriteCellChangeSpeed) {
  55987. this.cellIndex++;
  55988. this._currentFrameCounter = 0;
  55989. if (this.cellIndex > this.particleSystem.endSpriteCellID) {
  55990. if (this.particleSystem.spriteCellLoop) {
  55991. this.cellIndex = this.particleSystem.startSpriteCellID;
  55992. }
  55993. else {
  55994. this.cellIndex = this.particleSystem.endSpriteCellID;
  55995. }
  55996. }
  55997. }
  55998. else {
  55999. this._currentFrameCounter++;
  56000. }
  56001. };
  56002. /**
  56003. * Copy the properties of particle to another one.
  56004. * @param other the particle to copy the information to.
  56005. */
  56006. Particle.prototype.copyTo = function (other) {
  56007. other.position.copyFrom(this.position);
  56008. other.direction.copyFrom(this.direction);
  56009. other.color.copyFrom(this.color);
  56010. other.colorStep.copyFrom(this.colorStep);
  56011. other.lifeTime = this.lifeTime;
  56012. other.age = this.age;
  56013. other.size = this.size;
  56014. other.angle = this.angle;
  56015. other.angularSpeed = this.angularSpeed;
  56016. other.particleSystem = this.particleSystem;
  56017. other.cellIndex = this.cellIndex;
  56018. };
  56019. return Particle;
  56020. }());
  56021. BABYLON.Particle = Particle;
  56022. })(BABYLON || (BABYLON = {}));
  56023. //# sourceMappingURL=babylon.particle.js.map
  56024. var BABYLON;
  56025. (function (BABYLON) {
  56026. /**
  56027. * This represents a particle system in Babylon.
  56028. * 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.
  56029. * Particles can take different shapes while emitted like box, sphere, cone or you can write your custom function.
  56030. * @example https://doc.babylonjs.com/babylon101/particles
  56031. */
  56032. var ParticleSystem = /** @class */ (function () {
  56033. /**
  56034. * Instantiates a particle system.
  56035. * 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.
  56036. * @param name The name of the particle system
  56037. * @param capacity The max number of particles alive at the same time
  56038. * @param scene The scene the particle system belongs to
  56039. * @param customEffect a custom effect used to change the way particles are rendered by default
  56040. * @param isAnimationSheetEnabled Must be true if using a spritesheet to animate the particles texture
  56041. * @param epsilon Offset used to render the particles
  56042. */
  56043. function ParticleSystem(name, capacity, scene, customEffect, isAnimationSheetEnabled, epsilon) {
  56044. if (customEffect === void 0) { customEffect = null; }
  56045. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  56046. if (epsilon === void 0) { epsilon = 0.01; }
  56047. var _this = this;
  56048. /**
  56049. * List of animations used by the particle system.
  56050. */
  56051. this.animations = [];
  56052. /**
  56053. * The rendering group used by the Particle system to chose when to render.
  56054. */
  56055. this.renderingGroupId = 0;
  56056. /**
  56057. * The emitter represents the Mesh or position we are attaching the particle system to.
  56058. */
  56059. this.emitter = null;
  56060. /**
  56061. * The maximum number of particles to emit per frame
  56062. */
  56063. this.emitRate = 10;
  56064. /**
  56065. * If you want to launch only a few particles at once, that can be done, as well.
  56066. */
  56067. this.manualEmitCount = -1;
  56068. /**
  56069. * The overall motion speed (0.01 is default update speed, faster updates = faster animation)
  56070. */
  56071. this.updateSpeed = 0.01;
  56072. /**
  56073. * The amount of time the particle system is running (depends of the overall update speed).
  56074. */
  56075. this.targetStopDuration = 0;
  56076. /**
  56077. * Specifies whether the particle system will be disposed once it reaches the end of the animation.
  56078. */
  56079. this.disposeOnStop = false;
  56080. /**
  56081. * Minimum power of emitting particles.
  56082. */
  56083. this.minEmitPower = 1;
  56084. /**
  56085. * Maximum power of emitting particles.
  56086. */
  56087. this.maxEmitPower = 1;
  56088. /**
  56089. * Minimum life time of emitting particles.
  56090. */
  56091. this.minLifeTime = 1;
  56092. /**
  56093. * Maximum life time of emitting particles.
  56094. */
  56095. this.maxLifeTime = 1;
  56096. /**
  56097. * Minimum Size of emitting particles.
  56098. */
  56099. this.minSize = 1;
  56100. /**
  56101. * Maximum Size of emitting particles.
  56102. */
  56103. this.maxSize = 1;
  56104. /**
  56105. * Minimum angular speed of emitting particles (Z-axis rotation for each particle).
  56106. */
  56107. this.minAngularSpeed = 0;
  56108. /**
  56109. * Maximum angular speed of emitting particles (Z-axis rotation for each particle).
  56110. */
  56111. this.maxAngularSpeed = 0;
  56112. /**
  56113. * The layer mask we are rendering the particles through.
  56114. */
  56115. this.layerMask = 0x0FFFFFFF;
  56116. /**
  56117. * This can help using your own shader to render the particle system.
  56118. * The according effect will be created
  56119. */
  56120. this.customShader = null;
  56121. /**
  56122. * By default particle system starts as soon as they are created. This prevents the
  56123. * automatic start to happen and let you decide when to start emitting particles.
  56124. */
  56125. this.preventAutoStart = false;
  56126. /**
  56127. * Callback triggered when the particle animation is ending.
  56128. */
  56129. this.onAnimationEnd = null;
  56130. /**
  56131. * Blend mode use to render the particle, it can be either ParticleSystem.BLENDMODE_ONEONE or ParticleSystem.BLENDMODE_STANDARD.
  56132. */
  56133. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  56134. /**
  56135. * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls
  56136. * to override the particles.
  56137. */
  56138. this.forceDepthWrite = false;
  56139. /**
  56140. * You can use gravity if you want to give an orientation to your particles.
  56141. */
  56142. this.gravity = BABYLON.Vector3.Zero();
  56143. /**
  56144. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  56145. */
  56146. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  56147. /**
  56148. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  56149. */
  56150. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  56151. /**
  56152. * Color the particle will have at the end of its lifetime.
  56153. */
  56154. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  56155. /**
  56156. * An optional mask to filter some colors out of the texture, or filter a part of the alpha channel.
  56157. */
  56158. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  56159. /**
  56160. * If using a spritesheet (isAnimationSheetEnabled), defines if the sprite animation should loop between startSpriteCellID and endSpriteCellID or not.
  56161. */
  56162. this.spriteCellLoop = true;
  56163. /**
  56164. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the speed of the sprite loop.
  56165. */
  56166. this.spriteCellChangeSpeed = 0;
  56167. /**
  56168. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the first sprite cell to display.
  56169. */
  56170. this.startSpriteCellID = 0;
  56171. /**
  56172. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the last sprite cell to display.
  56173. */
  56174. this.endSpriteCellID = 0;
  56175. /**
  56176. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell width to use.
  56177. */
  56178. this.spriteCellWidth = 0;
  56179. /**
  56180. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell height to use.
  56181. */
  56182. this.spriteCellHeight = 0;
  56183. /**
  56184. * An event triggered when the system is disposed.
  56185. */
  56186. this.onDisposeObservable = new BABYLON.Observable();
  56187. this._particles = new Array();
  56188. this._stockParticles = new Array();
  56189. this._newPartsExcess = 0;
  56190. this._vertexBuffers = {};
  56191. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  56192. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  56193. this._scaledDirection = BABYLON.Vector3.Zero();
  56194. this._scaledGravity = BABYLON.Vector3.Zero();
  56195. this._currentRenderId = -1;
  56196. this._started = false;
  56197. this._stopped = false;
  56198. this._actualFrame = 0;
  56199. this._vertexBufferSize = 11;
  56200. // start of sub system methods
  56201. /**
  56202. * "Recycles" one of the particle by copying it back to the "stock" of particles and removing it from the active list.
  56203. * Its lifetime will start back at 0.
  56204. */
  56205. this.recycleParticle = function (particle) {
  56206. var lastParticle = _this._particles.pop();
  56207. if (lastParticle !== particle) {
  56208. lastParticle.copyTo(particle);
  56209. }
  56210. _this._stockParticles.push(lastParticle);
  56211. };
  56212. this._createParticle = function () {
  56213. var particle;
  56214. if (_this._stockParticles.length !== 0) {
  56215. particle = _this._stockParticles.pop();
  56216. particle.age = 0;
  56217. particle.cellIndex = _this.startSpriteCellID;
  56218. }
  56219. else {
  56220. particle = new BABYLON.Particle(_this);
  56221. }
  56222. return particle;
  56223. };
  56224. this._emitFromParticle = function (particle) {
  56225. if (!_this.subEmitters || _this.subEmitters.length === 0) {
  56226. return;
  56227. }
  56228. var templateIndex = Math.floor(Math.random() * _this.subEmitters.length);
  56229. var subSystem = _this.subEmitters[templateIndex].clone(_this.name + "_sub", particle.position.clone());
  56230. subSystem._rootParticleSystem = _this;
  56231. _this.activeSubSystems.push(subSystem);
  56232. subSystem.start();
  56233. };
  56234. this._appendParticleVertexes = null;
  56235. this.id = name;
  56236. this.name = name;
  56237. this._capacity = capacity;
  56238. this._epsilon = epsilon;
  56239. this._isAnimationSheetEnabled = isAnimationSheetEnabled;
  56240. if (isAnimationSheetEnabled) {
  56241. this._vertexBufferSize = 12;
  56242. }
  56243. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  56244. this._customEffect = customEffect;
  56245. scene.particleSystems.push(this);
  56246. this._createIndexBuffer();
  56247. // 11 floats per particle (x, y, z, r, g, b, a, angle, size, offsetX, offsetY) + 1 filler
  56248. this._vertexData = new Float32Array(capacity * this._vertexBufferSize * 4);
  56249. this._vertexBuffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, this._vertexBufferSize);
  56250. var positions = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 3);
  56251. var colors = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 3, 4);
  56252. var options = this._vertexBuffer.createVertexBuffer("options", 7, 4);
  56253. if (this._isAnimationSheetEnabled) {
  56254. var cellIndexBuffer = this._vertexBuffer.createVertexBuffer("cellIndex", 11, 1);
  56255. this._vertexBuffers["cellIndex"] = cellIndexBuffer;
  56256. }
  56257. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  56258. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  56259. this._vertexBuffers["options"] = options;
  56260. // Default emitter type
  56261. this.particleEmitterType = new BABYLON.BoxParticleEmitter();
  56262. this.updateFunction = function (particles) {
  56263. for (var index = 0; index < particles.length; index++) {
  56264. var particle = particles[index];
  56265. particle.age += _this._scaledUpdateSpeed;
  56266. if (particle.age >= particle.lifeTime) { // Recycle by swapping with last particle
  56267. _this._emitFromParticle(particle);
  56268. _this.recycleParticle(particle);
  56269. index--;
  56270. continue;
  56271. }
  56272. else {
  56273. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  56274. particle.color.addInPlace(_this._scaledColorStep);
  56275. if (particle.color.a < 0)
  56276. particle.color.a = 0;
  56277. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  56278. particle.direction.scaleToRef(_this._scaledUpdateSpeed, _this._scaledDirection);
  56279. particle.position.addInPlace(_this._scaledDirection);
  56280. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  56281. particle.direction.addInPlace(_this._scaledGravity);
  56282. if (_this._isAnimationSheetEnabled) {
  56283. particle.updateCellIndex(_this._scaledUpdateSpeed);
  56284. }
  56285. }
  56286. }
  56287. };
  56288. }
  56289. Object.defineProperty(ParticleSystem.prototype, "direction1", {
  56290. /**
  56291. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  56292. * This only works when particleEmitterTyps is a BoxParticleEmitter
  56293. */
  56294. get: function () {
  56295. if (this.particleEmitterType.direction1) {
  56296. return this.particleEmitterType.direction1;
  56297. }
  56298. return BABYLON.Vector3.Zero();
  56299. },
  56300. set: function (value) {
  56301. if (this.particleEmitterType.direction1) {
  56302. this.particleEmitterType.direction1 = value;
  56303. }
  56304. },
  56305. enumerable: true,
  56306. configurable: true
  56307. });
  56308. Object.defineProperty(ParticleSystem.prototype, "direction2", {
  56309. /**
  56310. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  56311. * This only works when particleEmitterTyps is a BoxParticleEmitter
  56312. */
  56313. get: function () {
  56314. if (this.particleEmitterType.direction2) {
  56315. return this.particleEmitterType.direction2;
  56316. }
  56317. return BABYLON.Vector3.Zero();
  56318. },
  56319. set: function (value) {
  56320. if (this.particleEmitterType.direction2) {
  56321. this.particleEmitterType.direction2 = value;
  56322. }
  56323. },
  56324. enumerable: true,
  56325. configurable: true
  56326. });
  56327. Object.defineProperty(ParticleSystem.prototype, "minEmitBox", {
  56328. /**
  56329. * 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.
  56330. * This only works when particleEmitterTyps is a BoxParticleEmitter
  56331. */
  56332. get: function () {
  56333. if (this.particleEmitterType.minEmitBox) {
  56334. return this.particleEmitterType.minEmitBox;
  56335. }
  56336. return BABYLON.Vector3.Zero();
  56337. },
  56338. set: function (value) {
  56339. if (this.particleEmitterType.minEmitBox) {
  56340. this.particleEmitterType.minEmitBox = value;
  56341. }
  56342. },
  56343. enumerable: true,
  56344. configurable: true
  56345. });
  56346. Object.defineProperty(ParticleSystem.prototype, "maxEmitBox", {
  56347. /**
  56348. * 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.
  56349. * This only works when particleEmitterTyps is a BoxParticleEmitter
  56350. */
  56351. get: function () {
  56352. if (this.particleEmitterType.maxEmitBox) {
  56353. return this.particleEmitterType.maxEmitBox;
  56354. }
  56355. return BABYLON.Vector3.Zero();
  56356. },
  56357. set: function (value) {
  56358. if (this.particleEmitterType.maxEmitBox) {
  56359. this.particleEmitterType.maxEmitBox = value;
  56360. }
  56361. },
  56362. enumerable: true,
  56363. configurable: true
  56364. });
  56365. Object.defineProperty(ParticleSystem.prototype, "onDispose", {
  56366. /**
  56367. * Sets a callback that will be triggered when the system is disposed.
  56368. */
  56369. set: function (callback) {
  56370. if (this._onDisposeObserver) {
  56371. this.onDisposeObservable.remove(this._onDisposeObserver);
  56372. }
  56373. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  56374. },
  56375. enumerable: true,
  56376. configurable: true
  56377. });
  56378. Object.defineProperty(ParticleSystem.prototype, "isAnimationSheetEnabled", {
  56379. /**
  56380. * Gets wether an animation sprite sheet is enabled or not on the particle system.
  56381. */
  56382. get: function () {
  56383. return this._isAnimationSheetEnabled;
  56384. },
  56385. enumerable: true,
  56386. configurable: true
  56387. });
  56388. Object.defineProperty(ParticleSystem.prototype, "particles", {
  56389. //end of Sub-emitter
  56390. /**
  56391. * Gets the current list of active particles
  56392. */
  56393. get: function () {
  56394. return this._particles;
  56395. },
  56396. enumerable: true,
  56397. configurable: true
  56398. });
  56399. /**
  56400. * Returns the string "ParticleSystem"
  56401. * @returns a string containing the class name
  56402. */
  56403. ParticleSystem.prototype.getClassName = function () {
  56404. return "ParticleSystem";
  56405. };
  56406. ParticleSystem.prototype._createIndexBuffer = function () {
  56407. var indices = [];
  56408. var index = 0;
  56409. for (var count = 0; count < this._capacity; count++) {
  56410. indices.push(index);
  56411. indices.push(index + 1);
  56412. indices.push(index + 2);
  56413. indices.push(index);
  56414. indices.push(index + 2);
  56415. indices.push(index + 3);
  56416. index += 4;
  56417. }
  56418. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  56419. };
  56420. /**
  56421. * Gets the maximum number of particles active at the same time.
  56422. * @returns The max number of active particles.
  56423. */
  56424. ParticleSystem.prototype.getCapacity = function () {
  56425. return this._capacity;
  56426. };
  56427. /**
  56428. * Gets Wether there are still active particles in the system.
  56429. * @returns True if it is alive, otherwise false.
  56430. */
  56431. ParticleSystem.prototype.isAlive = function () {
  56432. return this._alive;
  56433. };
  56434. /**
  56435. * Gets Wether the system has been started.
  56436. * @returns True if it has been started, otherwise false.
  56437. */
  56438. ParticleSystem.prototype.isStarted = function () {
  56439. return this._started;
  56440. };
  56441. /**
  56442. * Starts the particle system and begins to emit.
  56443. */
  56444. ParticleSystem.prototype.start = function () {
  56445. this._started = true;
  56446. this._stopped = false;
  56447. this._actualFrame = 0;
  56448. if (this.subEmitters && this.subEmitters.length != 0) {
  56449. this.activeSubSystems = new Array();
  56450. }
  56451. };
  56452. /**
  56453. * Stops the particle system.
  56454. * @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.
  56455. */
  56456. ParticleSystem.prototype.stop = function (stopSubEmitters) {
  56457. if (stopSubEmitters === void 0) { stopSubEmitters = true; }
  56458. this._stopped = true;
  56459. if (stopSubEmitters) {
  56460. this._stopSubEmitters();
  56461. }
  56462. };
  56463. // animation sheet
  56464. /**
  56465. * Remove all active particles
  56466. */
  56467. ParticleSystem.prototype.reset = function () {
  56468. this._stockParticles = [];
  56469. this._particles = [];
  56470. };
  56471. /**
  56472. * @hidden (for internal use only)
  56473. */
  56474. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  56475. var offset = index * this._vertexBufferSize;
  56476. this._vertexData[offset] = particle.position.x;
  56477. this._vertexData[offset + 1] = particle.position.y;
  56478. this._vertexData[offset + 2] = particle.position.z;
  56479. this._vertexData[offset + 3] = particle.color.r;
  56480. this._vertexData[offset + 4] = particle.color.g;
  56481. this._vertexData[offset + 5] = particle.color.b;
  56482. this._vertexData[offset + 6] = particle.color.a;
  56483. this._vertexData[offset + 7] = particle.angle;
  56484. this._vertexData[offset + 8] = particle.size;
  56485. this._vertexData[offset + 9] = offsetX;
  56486. this._vertexData[offset + 10] = offsetY;
  56487. };
  56488. /**
  56489. * @hidden (for internal use only)
  56490. */
  56491. ParticleSystem.prototype._appendParticleVertexWithAnimation = function (index, particle, offsetX, offsetY) {
  56492. if (offsetX === 0)
  56493. offsetX = this._epsilon;
  56494. else if (offsetX === 1)
  56495. offsetX = 1 - this._epsilon;
  56496. if (offsetY === 0)
  56497. offsetY = this._epsilon;
  56498. else if (offsetY === 1)
  56499. offsetY = 1 - this._epsilon;
  56500. var offset = index * this._vertexBufferSize;
  56501. this._vertexData[offset] = particle.position.x;
  56502. this._vertexData[offset + 1] = particle.position.y;
  56503. this._vertexData[offset + 2] = particle.position.z;
  56504. this._vertexData[offset + 3] = particle.color.r;
  56505. this._vertexData[offset + 4] = particle.color.g;
  56506. this._vertexData[offset + 5] = particle.color.b;
  56507. this._vertexData[offset + 6] = particle.color.a;
  56508. this._vertexData[offset + 7] = particle.angle;
  56509. this._vertexData[offset + 8] = particle.size;
  56510. this._vertexData[offset + 9] = offsetX;
  56511. this._vertexData[offset + 10] = offsetY;
  56512. this._vertexData[offset + 11] = particle.cellIndex;
  56513. };
  56514. ParticleSystem.prototype._stopSubEmitters = function () {
  56515. if (!this.activeSubSystems) {
  56516. return;
  56517. }
  56518. this.activeSubSystems.forEach(function (subSystem) {
  56519. subSystem.stop(true);
  56520. });
  56521. this.activeSubSystems = new Array();
  56522. };
  56523. ParticleSystem.prototype._removeFromRoot = function () {
  56524. if (!this._rootParticleSystem) {
  56525. return;
  56526. }
  56527. var index = this._rootParticleSystem.activeSubSystems.indexOf(this);
  56528. if (index !== -1) {
  56529. this._rootParticleSystem.activeSubSystems.splice(index, 1);
  56530. }
  56531. };
  56532. // end of sub system methods
  56533. ParticleSystem.prototype._update = function (newParticles) {
  56534. // Update current
  56535. this._alive = this._particles.length > 0;
  56536. this.updateFunction(this._particles);
  56537. // Add new ones
  56538. var worldMatrix;
  56539. if (this.emitter.position) {
  56540. var emitterMesh = this.emitter;
  56541. worldMatrix = emitterMesh.getWorldMatrix();
  56542. }
  56543. else {
  56544. var emitterPosition = this.emitter;
  56545. worldMatrix = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  56546. }
  56547. var particle;
  56548. for (var index = 0; index < newParticles; index++) {
  56549. if (this._particles.length === this._capacity) {
  56550. break;
  56551. }
  56552. particle = this._createParticle();
  56553. this._particles.push(particle);
  56554. var emitPower = BABYLON.Scalar.RandomRange(this.minEmitPower, this.maxEmitPower);
  56555. if (this.startPositionFunction) {
  56556. this.startPositionFunction(worldMatrix, particle.position, particle);
  56557. }
  56558. else {
  56559. this.particleEmitterType.startPositionFunction(worldMatrix, particle.position, particle);
  56560. }
  56561. if (this.startDirectionFunction) {
  56562. this.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  56563. }
  56564. else {
  56565. this.particleEmitterType.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  56566. }
  56567. particle.lifeTime = BABYLON.Scalar.RandomRange(this.minLifeTime, this.maxLifeTime);
  56568. particle.size = BABYLON.Scalar.RandomRange(this.minSize, this.maxSize);
  56569. particle.angularSpeed = BABYLON.Scalar.RandomRange(this.minAngularSpeed, this.maxAngularSpeed);
  56570. var step = BABYLON.Scalar.RandomRange(0, 1.0);
  56571. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  56572. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  56573. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  56574. }
  56575. };
  56576. ParticleSystem.prototype._getEffect = function () {
  56577. if (this._customEffect) {
  56578. return this._customEffect;
  56579. }
  56580. ;
  56581. var defines = [];
  56582. if (this._scene.clipPlane) {
  56583. defines.push("#define CLIPPLANE");
  56584. }
  56585. if (this._isAnimationSheetEnabled) {
  56586. defines.push("#define ANIMATESHEET");
  56587. }
  56588. // Effect
  56589. var join = defines.join("\n");
  56590. if (this._cachedDefines !== join) {
  56591. this._cachedDefines = join;
  56592. var attributesNamesOrOptions;
  56593. var effectCreationOption;
  56594. if (this._isAnimationSheetEnabled) {
  56595. attributesNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options", "cellIndex"];
  56596. effectCreationOption = ["invView", "view", "projection", "particlesInfos", "vClipPlane", "textureMask"];
  56597. }
  56598. else {
  56599. attributesNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options"];
  56600. effectCreationOption = ["invView", "view", "projection", "vClipPlane", "textureMask"];
  56601. }
  56602. this._effect = this._scene.getEngine().createEffect("particles", attributesNamesOrOptions, effectCreationOption, ["diffuseSampler"], join);
  56603. }
  56604. return this._effect;
  56605. };
  56606. /**
  56607. * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
  56608. */
  56609. ParticleSystem.prototype.animate = function () {
  56610. if (!this._started)
  56611. return;
  56612. var effect = this._getEffect();
  56613. // Check
  56614. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  56615. return;
  56616. if (this._currentRenderId === this._scene.getRenderId()) {
  56617. return;
  56618. }
  56619. this._currentRenderId = this._scene.getRenderId();
  56620. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  56621. // determine the number of particles we need to create
  56622. var newParticles;
  56623. if (this.manualEmitCount > -1) {
  56624. newParticles = this.manualEmitCount;
  56625. this._newPartsExcess = 0;
  56626. this.manualEmitCount = 0;
  56627. }
  56628. else {
  56629. newParticles = ((this.emitRate * this._scaledUpdateSpeed) >> 0);
  56630. this._newPartsExcess += this.emitRate * this._scaledUpdateSpeed - newParticles;
  56631. }
  56632. if (this._newPartsExcess > 1.0) {
  56633. newParticles += this._newPartsExcess >> 0;
  56634. this._newPartsExcess -= this._newPartsExcess >> 0;
  56635. }
  56636. this._alive = false;
  56637. if (!this._stopped) {
  56638. this._actualFrame += this._scaledUpdateSpeed;
  56639. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  56640. this.stop();
  56641. }
  56642. else {
  56643. newParticles = 0;
  56644. }
  56645. this._update(newParticles);
  56646. // Stopped?
  56647. if (this._stopped) {
  56648. if (!this._alive) {
  56649. this._started = false;
  56650. if (this.onAnimationEnd) {
  56651. this.onAnimationEnd();
  56652. }
  56653. if (this.disposeOnStop) {
  56654. this._scene._toBeDisposed.push(this);
  56655. }
  56656. }
  56657. }
  56658. // Animation sheet
  56659. if (this._isAnimationSheetEnabled) {
  56660. this._appendParticleVertexes = this._appenedParticleVertexesWithSheet;
  56661. }
  56662. else {
  56663. this._appendParticleVertexes = this._appenedParticleVertexesNoSheet;
  56664. }
  56665. // Update VBO
  56666. var offset = 0;
  56667. for (var index = 0; index < this._particles.length; index++) {
  56668. var particle = this._particles[index];
  56669. this._appendParticleVertexes(offset, particle);
  56670. offset += 4;
  56671. }
  56672. if (this._vertexBuffer) {
  56673. this._vertexBuffer.update(this._vertexData);
  56674. }
  56675. if (this.manualEmitCount === 0 && this.disposeOnStop) {
  56676. this.stop();
  56677. }
  56678. };
  56679. ParticleSystem.prototype._appenedParticleVertexesWithSheet = function (offset, particle) {
  56680. this._appendParticleVertexWithAnimation(offset++, particle, 0, 0);
  56681. this._appendParticleVertexWithAnimation(offset++, particle, 1, 0);
  56682. this._appendParticleVertexWithAnimation(offset++, particle, 1, 1);
  56683. this._appendParticleVertexWithAnimation(offset++, particle, 0, 1);
  56684. };
  56685. ParticleSystem.prototype._appenedParticleVertexesNoSheet = function (offset, particle) {
  56686. this._appendParticleVertex(offset++, particle, 0, 0);
  56687. this._appendParticleVertex(offset++, particle, 1, 0);
  56688. this._appendParticleVertex(offset++, particle, 1, 1);
  56689. this._appendParticleVertex(offset++, particle, 0, 1);
  56690. };
  56691. /**
  56692. * Rebuilds the particle system.
  56693. */
  56694. ParticleSystem.prototype.rebuild = function () {
  56695. this._createIndexBuffer();
  56696. if (this._vertexBuffer) {
  56697. this._vertexBuffer._rebuild();
  56698. }
  56699. };
  56700. /**
  56701. * Is this system ready to be used/rendered
  56702. * @return true if the system is ready
  56703. */
  56704. ParticleSystem.prototype.isReady = function () {
  56705. var effect = this._getEffect();
  56706. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady()) {
  56707. return false;
  56708. }
  56709. return true;
  56710. };
  56711. /**
  56712. * Renders the particle system in its current state.
  56713. * @returns the current number of particles
  56714. */
  56715. ParticleSystem.prototype.render = function () {
  56716. var effect = this._getEffect();
  56717. // Check
  56718. if (!this.isReady() || !this._particles.length) {
  56719. return 0;
  56720. }
  56721. var engine = this._scene.getEngine();
  56722. // Render
  56723. engine.enableEffect(effect);
  56724. engine.setState(false);
  56725. var viewMatrix = this._scene.getViewMatrix();
  56726. effect.setTexture("diffuseSampler", this.particleTexture);
  56727. effect.setMatrix("view", viewMatrix);
  56728. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  56729. if (this._isAnimationSheetEnabled && this.particleTexture) {
  56730. var baseSize = this.particleTexture.getBaseSize();
  56731. effect.setFloat3("particlesInfos", this.spriteCellWidth / baseSize.width, this.spriteCellHeight / baseSize.height, baseSize.width / this.spriteCellWidth);
  56732. }
  56733. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  56734. if (this._scene.clipPlane) {
  56735. var clipPlane = this._scene.clipPlane;
  56736. var invView = viewMatrix.clone();
  56737. invView.invert();
  56738. effect.setMatrix("invView", invView);
  56739. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  56740. }
  56741. // VBOs
  56742. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  56743. // Draw order
  56744. if (this.blendMode === ParticleSystem.BLENDMODE_ONEONE) {
  56745. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  56746. }
  56747. else {
  56748. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  56749. }
  56750. if (this.forceDepthWrite) {
  56751. engine.setDepthWrite(true);
  56752. }
  56753. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._particles.length * 6);
  56754. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  56755. return this._particles.length;
  56756. };
  56757. /**
  56758. * Disposes the particle system and free the associated resources
  56759. * @param disposeTexture defines if the particule texture must be disposed as well (true by default)
  56760. */
  56761. ParticleSystem.prototype.dispose = function (disposeTexture) {
  56762. if (disposeTexture === void 0) { disposeTexture = true; }
  56763. if (this._vertexBuffer) {
  56764. this._vertexBuffer.dispose();
  56765. this._vertexBuffer = null;
  56766. }
  56767. if (this._indexBuffer) {
  56768. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  56769. this._indexBuffer = null;
  56770. }
  56771. if (disposeTexture && this.particleTexture) {
  56772. this.particleTexture.dispose();
  56773. this.particleTexture = null;
  56774. }
  56775. this._removeFromRoot();
  56776. // Remove from scene
  56777. var index = this._scene.particleSystems.indexOf(this);
  56778. if (index > -1) {
  56779. this._scene.particleSystems.splice(index, 1);
  56780. }
  56781. // Callback
  56782. this.onDisposeObservable.notifyObservers(this);
  56783. this.onDisposeObservable.clear();
  56784. };
  56785. /**
  56786. * Creates a Sphere Emitter for the particle system. (emits along the sphere radius)
  56787. * @param radius The radius of the sphere to emit from
  56788. * @returns the emitter
  56789. */
  56790. ParticleSystem.prototype.createSphereEmitter = function (radius) {
  56791. if (radius === void 0) { radius = 1; }
  56792. var particleEmitter = new BABYLON.SphereParticleEmitter(radius);
  56793. this.particleEmitterType = particleEmitter;
  56794. return particleEmitter;
  56795. };
  56796. /**
  56797. * Creates a Directed Sphere Emitter for the particle system. (emits between direction1 and direction2)
  56798. * @param radius The radius of the sphere to emit from
  56799. * @param direction1 Particles are emitted between the direction1 and direction2 from within the sphere
  56800. * @param direction2 Particles are emitted between the direction1 and direction2 from within the sphere
  56801. * @returns the emitter
  56802. */
  56803. ParticleSystem.prototype.createDirectedSphereEmitter = function (radius, direction1, direction2) {
  56804. if (radius === void 0) { radius = 1; }
  56805. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1.0, 0); }
  56806. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1.0, 0); }
  56807. var particleEmitter = new BABYLON.SphereDirectedParticleEmitter(radius, direction1, direction2);
  56808. this.particleEmitterType = particleEmitter;
  56809. return particleEmitter;
  56810. };
  56811. /**
  56812. * Creates a Cone Emitter for the particle system. (emits from the cone to the particle position)
  56813. * @param radius The radius of the cone to emit from
  56814. * @param angle The base angle of the cone
  56815. * @returns the emitter
  56816. */
  56817. ParticleSystem.prototype.createConeEmitter = function (radius, angle) {
  56818. if (radius === void 0) { radius = 1; }
  56819. if (angle === void 0) { angle = Math.PI / 4; }
  56820. var particleEmitter = new BABYLON.ConeParticleEmitter(radius, angle);
  56821. this.particleEmitterType = particleEmitter;
  56822. return particleEmitter;
  56823. };
  56824. // this method needs to be changed when breaking changes will be allowed to match the sphere and cone methods and properties direction1,2 and minEmitBox,maxEmitBox to be removed from the system.
  56825. /**
  56826. * Creates a Box Emitter for the particle system. (emits between direction1 and direction2 from withing the box defined by minEmitBox and maxEmitBox)
  56827. * @param direction1 Particles are emitted between the direction1 and direction2 from within the box
  56828. * @param direction2 Particles are emitted between the direction1 and direction2 from within the box
  56829. * @param minEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  56830. * @param maxEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  56831. * @returns the emitter
  56832. */
  56833. ParticleSystem.prototype.createBoxEmitter = function (direction1, direction2, minEmitBox, maxEmitBox) {
  56834. var particleEmitter = new BABYLON.BoxParticleEmitter();
  56835. this.particleEmitterType = particleEmitter;
  56836. this.direction1 = direction1;
  56837. this.direction2 = direction2;
  56838. this.minEmitBox = minEmitBox;
  56839. this.maxEmitBox = maxEmitBox;
  56840. return particleEmitter;
  56841. };
  56842. // Clone
  56843. /**
  56844. * Clones the particle system.
  56845. * @param name The name of the cloned object
  56846. * @param newEmitter The new emitter to use
  56847. * @returns the cloned particle system
  56848. */
  56849. ParticleSystem.prototype.clone = function (name, newEmitter) {
  56850. var custom = null;
  56851. var program = null;
  56852. if (this.customShader != null) {
  56853. program = this.customShader;
  56854. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  56855. custom = this._scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  56856. }
  56857. var result = new ParticleSystem(name, this._capacity, this._scene, custom);
  56858. result.customShader = program;
  56859. BABYLON.Tools.DeepCopy(this, result, ["particles", "customShader"]);
  56860. if (newEmitter === undefined) {
  56861. newEmitter = this.emitter;
  56862. }
  56863. result.emitter = newEmitter;
  56864. if (this.particleTexture) {
  56865. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  56866. }
  56867. if (!this.preventAutoStart) {
  56868. result.start();
  56869. }
  56870. return result;
  56871. };
  56872. /**
  56873. * Serializes the particle system to a JSON object.
  56874. * @returns the JSON object
  56875. */
  56876. ParticleSystem.prototype.serialize = function () {
  56877. var serializationObject = {};
  56878. serializationObject.name = this.name;
  56879. serializationObject.id = this.id;
  56880. // Emitter
  56881. if (this.emitter.position) {
  56882. var emitterMesh = this.emitter;
  56883. serializationObject.emitterId = emitterMesh.id;
  56884. }
  56885. else {
  56886. var emitterPosition = this.emitter;
  56887. serializationObject.emitter = emitterPosition.asArray();
  56888. }
  56889. serializationObject.capacity = this.getCapacity();
  56890. if (this.particleTexture) {
  56891. serializationObject.textureName = this.particleTexture.name;
  56892. }
  56893. // Animations
  56894. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  56895. // Particle system
  56896. serializationObject.minAngularSpeed = this.minAngularSpeed;
  56897. serializationObject.maxAngularSpeed = this.maxAngularSpeed;
  56898. serializationObject.minSize = this.minSize;
  56899. serializationObject.maxSize = this.maxSize;
  56900. serializationObject.minEmitPower = this.minEmitPower;
  56901. serializationObject.maxEmitPower = this.maxEmitPower;
  56902. serializationObject.minLifeTime = this.minLifeTime;
  56903. serializationObject.maxLifeTime = this.maxLifeTime;
  56904. serializationObject.emitRate = this.emitRate;
  56905. serializationObject.minEmitBox = this.minEmitBox.asArray();
  56906. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  56907. serializationObject.gravity = this.gravity.asArray();
  56908. serializationObject.direction1 = this.direction1.asArray();
  56909. serializationObject.direction2 = this.direction2.asArray();
  56910. serializationObject.color1 = this.color1.asArray();
  56911. serializationObject.color2 = this.color2.asArray();
  56912. serializationObject.colorDead = this.colorDead.asArray();
  56913. serializationObject.updateSpeed = this.updateSpeed;
  56914. serializationObject.targetStopDuration = this.targetStopDuration;
  56915. serializationObject.textureMask = this.textureMask.asArray();
  56916. serializationObject.blendMode = this.blendMode;
  56917. serializationObject.customShader = this.customShader;
  56918. serializationObject.preventAutoStart = this.preventAutoStart;
  56919. serializationObject.startSpriteCellID = this.startSpriteCellID;
  56920. serializationObject.endSpriteCellID = this.endSpriteCellID;
  56921. serializationObject.spriteCellLoop = this.spriteCellLoop;
  56922. serializationObject.spriteCellChangeSpeed = this.spriteCellChangeSpeed;
  56923. serializationObject.spriteCellWidth = this.spriteCellWidth;
  56924. serializationObject.spriteCellHeight = this.spriteCellHeight;
  56925. serializationObject.isAnimationSheetEnabled = this._isAnimationSheetEnabled;
  56926. // Emitter
  56927. if (this.particleEmitterType) {
  56928. serializationObject.particleEmitterType = this.particleEmitterType.serialize();
  56929. }
  56930. return serializationObject;
  56931. };
  56932. /**
  56933. * Parses a JSON object to create a particle system.
  56934. * @param parsedParticleSystem The JSON object to parse
  56935. * @param scene The scene to create the particle system in
  56936. * @param rootUrl The root url to use to load external dependencies like texture
  56937. * @returns the Parsed particle system
  56938. */
  56939. ParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  56940. var name = parsedParticleSystem.name;
  56941. var custom = null;
  56942. var program = null;
  56943. if (parsedParticleSystem.customShader) {
  56944. program = parsedParticleSystem.customShader;
  56945. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  56946. custom = scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  56947. }
  56948. var particleSystem = new ParticleSystem(name, parsedParticleSystem.capacity, scene, custom, parsedParticleSystem.isAnimationSheetEnabled);
  56949. particleSystem.customShader = program;
  56950. if (parsedParticleSystem.id) {
  56951. particleSystem.id = parsedParticleSystem.id;
  56952. }
  56953. // Auto start
  56954. if (parsedParticleSystem.preventAutoStart) {
  56955. particleSystem.preventAutoStart = parsedParticleSystem.preventAutoStart;
  56956. }
  56957. // Texture
  56958. if (parsedParticleSystem.textureName) {
  56959. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  56960. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  56961. }
  56962. // Emitter
  56963. if (parsedParticleSystem.emitterId) {
  56964. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  56965. }
  56966. else {
  56967. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  56968. }
  56969. // Animations
  56970. if (parsedParticleSystem.animations) {
  56971. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  56972. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  56973. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  56974. }
  56975. }
  56976. if (parsedParticleSystem.autoAnimate) {
  56977. scene.beginAnimation(particleSystem, parsedParticleSystem.autoAnimateFrom, parsedParticleSystem.autoAnimateTo, parsedParticleSystem.autoAnimateLoop, parsedParticleSystem.autoAnimateSpeed || 1.0);
  56978. }
  56979. // Particle system
  56980. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  56981. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  56982. particleSystem.minSize = parsedParticleSystem.minSize;
  56983. particleSystem.maxSize = parsedParticleSystem.maxSize;
  56984. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  56985. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  56986. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  56987. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  56988. particleSystem.emitRate = parsedParticleSystem.emitRate;
  56989. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  56990. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  56991. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  56992. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  56993. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  56994. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  56995. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  56996. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  56997. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  56998. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  56999. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  57000. particleSystem.blendMode = parsedParticleSystem.blendMode;
  57001. particleSystem.startSpriteCellID = parsedParticleSystem.startSpriteCellID;
  57002. particleSystem.endSpriteCellID = parsedParticleSystem.endSpriteCellID;
  57003. particleSystem.spriteCellLoop = parsedParticleSystem.spriteCellLoop;
  57004. particleSystem.spriteCellChangeSpeed = parsedParticleSystem.spriteCellChangeSpeed;
  57005. particleSystem.spriteCellWidth = parsedParticleSystem.spriteCellWidth;
  57006. particleSystem.spriteCellHeight = parsedParticleSystem.spriteCellHeight;
  57007. if (!particleSystem.preventAutoStart) {
  57008. particleSystem.start();
  57009. }
  57010. return particleSystem;
  57011. };
  57012. /**
  57013. * Source color is added to the destination color without alpha affecting the result.
  57014. */
  57015. ParticleSystem.BLENDMODE_ONEONE = 0;
  57016. /**
  57017. * Blend current color and particle color using particle’s alpha.
  57018. */
  57019. ParticleSystem.BLENDMODE_STANDARD = 1;
  57020. return ParticleSystem;
  57021. }());
  57022. BABYLON.ParticleSystem = ParticleSystem;
  57023. })(BABYLON || (BABYLON = {}));
  57024. //# sourceMappingURL=babylon.particleSystem.js.map
  57025. //# sourceMappingURL=babylon.IParticleEmitterType.js.map
  57026. var BABYLON;
  57027. (function (BABYLON) {
  57028. /**
  57029. * Particle emitter emitting particles from the inside of a box.
  57030. * It emits the particles randomly between 2 given directions.
  57031. */
  57032. var BoxParticleEmitter = /** @class */ (function () {
  57033. /**
  57034. * Creates a new instance BoxParticleEmitter
  57035. */
  57036. function BoxParticleEmitter() {
  57037. /**
  57038. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  57039. */
  57040. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  57041. /**
  57042. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  57043. */
  57044. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  57045. /**
  57046. * 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.
  57047. */
  57048. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  57049. /**
  57050. * 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.
  57051. */
  57052. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  57053. }
  57054. /**
  57055. * Called by the particle System when the direction is computed for the created particle.
  57056. * @param emitPower is the power of the particle (speed)
  57057. * @param worldMatrix is the world matrix of the particle system
  57058. * @param directionToUpdate is the direction vector to update with the result
  57059. * @param particle is the particle we are computed the direction for
  57060. */
  57061. BoxParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  57062. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  57063. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  57064. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  57065. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  57066. };
  57067. /**
  57068. * Called by the particle System when the position is computed for the created particle.
  57069. * @param worldMatrix is the world matrix of the particle system
  57070. * @param positionToUpdate is the position vector to update with the result
  57071. * @param particle is the particle we are computed the position for
  57072. */
  57073. BoxParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  57074. var randX = BABYLON.Scalar.RandomRange(this.minEmitBox.x, this.maxEmitBox.x);
  57075. var randY = BABYLON.Scalar.RandomRange(this.minEmitBox.y, this.maxEmitBox.y);
  57076. var randZ = BABYLON.Scalar.RandomRange(this.minEmitBox.z, this.maxEmitBox.z);
  57077. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  57078. };
  57079. /**
  57080. * Clones the current emitter and returns a copy of it
  57081. * @returns the new emitter
  57082. */
  57083. BoxParticleEmitter.prototype.clone = function () {
  57084. var newOne = new BoxParticleEmitter();
  57085. BABYLON.Tools.DeepCopy(this, newOne);
  57086. return newOne;
  57087. };
  57088. /**
  57089. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  57090. * @param effect defines the update shader
  57091. */
  57092. BoxParticleEmitter.prototype.applyToShader = function (effect) {
  57093. effect.setVector3("direction1", this.direction1);
  57094. effect.setVector3("direction2", this.direction2);
  57095. effect.setVector3("minEmitBox", this.minEmitBox);
  57096. effect.setVector3("maxEmitBox", this.maxEmitBox);
  57097. };
  57098. /**
  57099. * Returns a string to use to update the GPU particles update shader
  57100. * @returns a string containng the defines string
  57101. */
  57102. BoxParticleEmitter.prototype.getEffectDefines = function () {
  57103. return "#define BOXEMITTER";
  57104. };
  57105. /**
  57106. * Returns the string "BoxEmitter"
  57107. * @returns a string containing the class name
  57108. */
  57109. BoxParticleEmitter.prototype.getClassName = function () {
  57110. return "BoxEmitter";
  57111. };
  57112. /**
  57113. * Serializes the particle system to a JSON object.
  57114. * @returns the JSON object
  57115. */
  57116. BoxParticleEmitter.prototype.serialize = function () {
  57117. var serializationObject = {};
  57118. serializationObject.type = this.getClassName();
  57119. serializationObject.direction1 = this.direction1.asArray();
  57120. serializationObject.direction2 = this.direction2.asArray();
  57121. serializationObject.minEmitBox = this.minEmitBox.asArray();
  57122. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  57123. return serializationObject;
  57124. };
  57125. /**
  57126. * Parse properties from a JSON object
  57127. * @param serializationObject defines the JSON object
  57128. */
  57129. BoxParticleEmitter.prototype.parse = function (serializationObject) {
  57130. this.direction1.copyFrom(serializationObject.direction1);
  57131. this.direction2.copyFrom(serializationObject.direction2);
  57132. this.minEmitBox.copyFrom(serializationObject.minEmitBox);
  57133. this.maxEmitBox.copyFrom(serializationObject.maxEmitBox);
  57134. };
  57135. return BoxParticleEmitter;
  57136. }());
  57137. BABYLON.BoxParticleEmitter = BoxParticleEmitter;
  57138. })(BABYLON || (BABYLON = {}));
  57139. //# sourceMappingURL=babylon.boxParticleEmitter.js.map
  57140. var BABYLON;
  57141. (function (BABYLON) {
  57142. /**
  57143. * Particle emitter emitting particles from the inside of a cone.
  57144. * It emits the particles alongside the cone volume from the base to the particle.
  57145. * The emission direction might be randomized.
  57146. */
  57147. var ConeParticleEmitter = /** @class */ (function () {
  57148. /**
  57149. * Creates a new instance ConeParticleEmitter
  57150. * @param radius the radius of the emission cone (1 by default)
  57151. * @param angles the cone base angle (PI by default)
  57152. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  57153. */
  57154. function ConeParticleEmitter(radius,
  57155. /**
  57156. * The radius of the emission cone.
  57157. */
  57158. angle,
  57159. /**
  57160. * The cone base angle.
  57161. */
  57162. directionRandomizer) {
  57163. if (radius === void 0) { radius = 1; }
  57164. if (angle === void 0) { angle = Math.PI; }
  57165. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  57166. this.angle = angle;
  57167. this.directionRandomizer = directionRandomizer;
  57168. this.radius = radius;
  57169. }
  57170. Object.defineProperty(ConeParticleEmitter.prototype, "radius", {
  57171. /**
  57172. * Gets the radius of the emission cone.
  57173. */
  57174. get: function () {
  57175. return this._radius;
  57176. },
  57177. /**
  57178. * Sets the radius of the emission cone.
  57179. */
  57180. set: function (value) {
  57181. this._radius = value;
  57182. if (this.angle !== 0) {
  57183. this._height = value / Math.tan(this.angle / 2);
  57184. }
  57185. else {
  57186. this._height = 1;
  57187. }
  57188. },
  57189. enumerable: true,
  57190. configurable: true
  57191. });
  57192. /**
  57193. * Called by the particle System when the direction is computed for the created particle.
  57194. * @param emitPower is the power of the particle (speed)
  57195. * @param worldMatrix is the world matrix of the particle system
  57196. * @param directionToUpdate is the direction vector to update with the result
  57197. * @param particle is the particle we are computed the direction for
  57198. */
  57199. ConeParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  57200. if (this.angle === 0) {
  57201. BABYLON.Vector3.TransformNormalFromFloatsToRef(0, emitPower, 0, worldMatrix, directionToUpdate);
  57202. }
  57203. else {
  57204. // measure the direction Vector from the emitter to the particle.
  57205. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  57206. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  57207. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  57208. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  57209. direction.x += randX;
  57210. direction.y += randY;
  57211. direction.z += randZ;
  57212. direction.normalize();
  57213. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x * emitPower, direction.y * emitPower, direction.z * emitPower, worldMatrix, directionToUpdate);
  57214. }
  57215. };
  57216. /**
  57217. * Called by the particle System when the position is computed for the created particle.
  57218. * @param worldMatrix is the world matrix of the particle system
  57219. * @param positionToUpdate is the position vector to update with the result
  57220. * @param particle is the particle we are computed the position for
  57221. */
  57222. ConeParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  57223. var s = BABYLON.Scalar.RandomRange(0, Math.PI * 2);
  57224. var h = BABYLON.Scalar.RandomRange(0, 1);
  57225. // Better distribution in a cone at normal angles.
  57226. h = 1 - h * h;
  57227. var radius = BABYLON.Scalar.RandomRange(0, this._radius);
  57228. radius = radius * h;
  57229. var randX = radius * Math.sin(s);
  57230. var randZ = radius * Math.cos(s);
  57231. var randY = h * this._height;
  57232. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  57233. };
  57234. /**
  57235. * Clones the current emitter and returns a copy of it
  57236. * @returns the new emitter
  57237. */
  57238. ConeParticleEmitter.prototype.clone = function () {
  57239. var newOne = new ConeParticleEmitter(this.radius, this.angle, this.directionRandomizer);
  57240. BABYLON.Tools.DeepCopy(this, newOne);
  57241. return newOne;
  57242. };
  57243. /**
  57244. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  57245. * @param effect defines the update shader
  57246. */
  57247. ConeParticleEmitter.prototype.applyToShader = function (effect) {
  57248. effect.setFloat("radius", this.radius);
  57249. effect.setFloat("coneAngle", this.angle);
  57250. effect.setFloat("height", this._height);
  57251. effect.setFloat("directionRandomizer", this.directionRandomizer);
  57252. };
  57253. /**
  57254. * Returns a string to use to update the GPU particles update shader
  57255. * @returns a string containng the defines string
  57256. */
  57257. ConeParticleEmitter.prototype.getEffectDefines = function () {
  57258. return "#define CONEEMITTER";
  57259. };
  57260. /**
  57261. * Returns the string "BoxEmitter"
  57262. * @returns a string containing the class name
  57263. */
  57264. ConeParticleEmitter.prototype.getClassName = function () {
  57265. return "ConeEmitter";
  57266. };
  57267. /**
  57268. * Serializes the particle system to a JSON object.
  57269. * @returns the JSON object
  57270. */
  57271. ConeParticleEmitter.prototype.serialize = function () {
  57272. var serializationObject = {};
  57273. serializationObject.type = this.getClassName();
  57274. serializationObject.radius = this.radius;
  57275. serializationObject.angle = this.angle;
  57276. serializationObject.directionRandomizer = this.directionRandomizer;
  57277. return serializationObject;
  57278. };
  57279. /**
  57280. * Parse properties from a JSON object
  57281. * @param serializationObject defines the JSON object
  57282. */
  57283. ConeParticleEmitter.prototype.parse = function (serializationObject) {
  57284. this.radius = serializationObject.radius;
  57285. this.angle = serializationObject.angle;
  57286. this.directionRandomizer = serializationObject.directionRandomizer;
  57287. };
  57288. return ConeParticleEmitter;
  57289. }());
  57290. BABYLON.ConeParticleEmitter = ConeParticleEmitter;
  57291. })(BABYLON || (BABYLON = {}));
  57292. //# sourceMappingURL=babylon.coneParticleEmitter.js.map
  57293. var BABYLON;
  57294. (function (BABYLON) {
  57295. /**
  57296. * Particle emitter emitting particles from the inside of a sphere.
  57297. * It emits the particles alongside the sphere radius. The emission direction might be randomized.
  57298. */
  57299. var SphereParticleEmitter = /** @class */ (function () {
  57300. /**
  57301. * Creates a new instance SphereParticleEmitter
  57302. * @param radius the radius of the emission sphere (1 by default)
  57303. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  57304. */
  57305. function SphereParticleEmitter(
  57306. /**
  57307. * The radius of the emission sphere.
  57308. */
  57309. radius,
  57310. /**
  57311. * How much to randomize the particle direction [0-1].
  57312. */
  57313. directionRandomizer) {
  57314. if (radius === void 0) { radius = 1; }
  57315. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  57316. this.radius = radius;
  57317. this.directionRandomizer = directionRandomizer;
  57318. }
  57319. /**
  57320. * Called by the particle System when the direction is computed for the created particle.
  57321. * @param emitPower is the power of the particle (speed)
  57322. * @param worldMatrix is the world matrix of the particle system
  57323. * @param directionToUpdate is the direction vector to update with the result
  57324. * @param particle is the particle we are computed the direction for
  57325. */
  57326. SphereParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  57327. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  57328. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  57329. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  57330. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  57331. direction.x += randX;
  57332. direction.y += randY;
  57333. direction.z += randZ;
  57334. direction.normalize();
  57335. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x * emitPower, direction.y * emitPower, direction.z * emitPower, worldMatrix, directionToUpdate);
  57336. };
  57337. /**
  57338. * Called by the particle System when the position is computed for the created particle.
  57339. * @param worldMatrix is the world matrix of the particle system
  57340. * @param positionToUpdate is the position vector to update with the result
  57341. * @param particle is the particle we are computed the position for
  57342. */
  57343. SphereParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  57344. var phi = BABYLON.Scalar.RandomRange(0, 2 * Math.PI);
  57345. var theta = BABYLON.Scalar.RandomRange(0, Math.PI);
  57346. var randRadius = BABYLON.Scalar.RandomRange(0, this.radius);
  57347. var randX = randRadius * Math.cos(phi) * Math.sin(theta);
  57348. var randY = randRadius * Math.cos(theta);
  57349. var randZ = randRadius * Math.sin(phi) * Math.sin(theta);
  57350. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  57351. };
  57352. /**
  57353. * Clones the current emitter and returns a copy of it
  57354. * @returns the new emitter
  57355. */
  57356. SphereParticleEmitter.prototype.clone = function () {
  57357. var newOne = new SphereParticleEmitter(this.radius, this.directionRandomizer);
  57358. BABYLON.Tools.DeepCopy(this, newOne);
  57359. return newOne;
  57360. };
  57361. /**
  57362. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  57363. * @param effect defines the update shader
  57364. */
  57365. SphereParticleEmitter.prototype.applyToShader = function (effect) {
  57366. effect.setFloat("radius", this.radius);
  57367. effect.setFloat("directionRandomizer", this.directionRandomizer);
  57368. };
  57369. /**
  57370. * Returns a string to use to update the GPU particles update shader
  57371. * @returns a string containng the defines string
  57372. */
  57373. SphereParticleEmitter.prototype.getEffectDefines = function () {
  57374. return "#define SPHEREEMITTER";
  57375. };
  57376. /**
  57377. * Returns the string "SphereParticleEmitter"
  57378. * @returns a string containing the class name
  57379. */
  57380. SphereParticleEmitter.prototype.getClassName = function () {
  57381. return "SphereParticleEmitter";
  57382. };
  57383. /**
  57384. * Serializes the particle system to a JSON object.
  57385. * @returns the JSON object
  57386. */
  57387. SphereParticleEmitter.prototype.serialize = function () {
  57388. var serializationObject = {};
  57389. serializationObject.type = this.getClassName();
  57390. serializationObject.radius = this.radius;
  57391. serializationObject.directionRandomizer = this.directionRandomizer;
  57392. return serializationObject;
  57393. };
  57394. /**
  57395. * Parse properties from a JSON object
  57396. * @param serializationObject defines the JSON object
  57397. */
  57398. SphereParticleEmitter.prototype.parse = function (serializationObject) {
  57399. this.radius = serializationObject.radius;
  57400. this.directionRandomizer = serializationObject.directionRandomizer;
  57401. };
  57402. return SphereParticleEmitter;
  57403. }());
  57404. BABYLON.SphereParticleEmitter = SphereParticleEmitter;
  57405. /**
  57406. * Particle emitter emitting particles from the inside of a sphere.
  57407. * It emits the particles randomly between two vectors.
  57408. */
  57409. var SphereDirectedParticleEmitter = /** @class */ (function (_super) {
  57410. __extends(SphereDirectedParticleEmitter, _super);
  57411. /**
  57412. * Creates a new instance SphereDirectedParticleEmitter
  57413. * @param radius the radius of the emission sphere (1 by default)
  57414. * @param direction1 the min limit of the emission direction (up vector by default)
  57415. * @param direction2 the max limit of the emission direction (up vector by default)
  57416. */
  57417. function SphereDirectedParticleEmitter(radius,
  57418. /**
  57419. * The min limit of the emission direction.
  57420. */
  57421. direction1,
  57422. /**
  57423. * The max limit of the emission direction.
  57424. */
  57425. direction2) {
  57426. if (radius === void 0) { radius = 1; }
  57427. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1, 0); }
  57428. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1, 0); }
  57429. var _this = _super.call(this, radius) || this;
  57430. _this.direction1 = direction1;
  57431. _this.direction2 = direction2;
  57432. return _this;
  57433. }
  57434. /**
  57435. * Called by the particle System when the direction is computed for the created particle.
  57436. * @param emitPower is the power of the particle (speed)
  57437. * @param worldMatrix is the world matrix of the particle system
  57438. * @param directionToUpdate is the direction vector to update with the result
  57439. * @param particle is the particle we are computed the direction for
  57440. */
  57441. SphereDirectedParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  57442. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  57443. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  57444. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  57445. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  57446. };
  57447. /**
  57448. * Clones the current emitter and returns a copy of it
  57449. * @returns the new emitter
  57450. */
  57451. SphereDirectedParticleEmitter.prototype.clone = function () {
  57452. var newOne = new SphereDirectedParticleEmitter(this.radius, this.direction1, this.direction2);
  57453. BABYLON.Tools.DeepCopy(this, newOne);
  57454. return newOne;
  57455. };
  57456. /**
  57457. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  57458. * @param effect defines the update shader
  57459. */
  57460. SphereDirectedParticleEmitter.prototype.applyToShader = function (effect) {
  57461. effect.setFloat("radius", this.radius);
  57462. effect.setVector3("direction1", this.direction1);
  57463. effect.setVector3("direction2", this.direction2);
  57464. };
  57465. /**
  57466. * Returns a string to use to update the GPU particles update shader
  57467. * @returns a string containng the defines string
  57468. */
  57469. SphereDirectedParticleEmitter.prototype.getEffectDefines = function () {
  57470. return "#define SPHEREEMITTER\n#define DIRECTEDSPHEREEMITTER";
  57471. };
  57472. /**
  57473. * Returns the string "SphereDirectedParticleEmitter"
  57474. * @returns a string containing the class name
  57475. */
  57476. SphereDirectedParticleEmitter.prototype.getClassName = function () {
  57477. return "SphereDirectedParticleEmitter";
  57478. };
  57479. /**
  57480. * Serializes the particle system to a JSON object.
  57481. * @returns the JSON object
  57482. */
  57483. SphereDirectedParticleEmitter.prototype.serialize = function () {
  57484. var serializationObject = _super.prototype.serialize.call(this);
  57485. serializationObject.direction1 = this.direction1.asArray();
  57486. serializationObject.direction2 = this.direction2.asArray();
  57487. return serializationObject;
  57488. };
  57489. /**
  57490. * Parse properties from a JSON object
  57491. * @param serializationObject defines the JSON object
  57492. */
  57493. SphereDirectedParticleEmitter.prototype.parse = function (serializationObject) {
  57494. _super.prototype.parse.call(this, serializationObject);
  57495. this.direction1.copyFrom(serializationObject.direction1);
  57496. this.direction2.copyFrom(serializationObject.direction2);
  57497. };
  57498. return SphereDirectedParticleEmitter;
  57499. }(SphereParticleEmitter));
  57500. BABYLON.SphereDirectedParticleEmitter = SphereDirectedParticleEmitter;
  57501. })(BABYLON || (BABYLON = {}));
  57502. //# sourceMappingURL=babylon.sphereParticleEmitter.js.map
  57503. var __assign = (this && this.__assign) || Object.assign || function(t) {
  57504. for (var s, i = 1, n = arguments.length; i < n; i++) {
  57505. s = arguments[i];
  57506. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  57507. t[p] = s[p];
  57508. }
  57509. return t;
  57510. };
  57511. var BABYLON;
  57512. (function (BABYLON) {
  57513. /**
  57514. * This represents a GPU particle system in Babylon
  57515. * This is the fastest particle system in Babylon as it uses the GPU to update the individual particle data
  57516. * @see https://www.babylonjs-playground.com/#PU4WYI#4
  57517. */
  57518. var GPUParticleSystem = /** @class */ (function () {
  57519. /**
  57520. * Instantiates a GPU particle system.
  57521. * 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.
  57522. * @param name The name of the particle system
  57523. * @param capacity The max number of particles alive at the same time
  57524. * @param scene The scene the particle system belongs to
  57525. */
  57526. function GPUParticleSystem(name, options, scene) {
  57527. /**
  57528. * The emitter represents the Mesh or position we are attaching the particle system to.
  57529. */
  57530. this.emitter = null;
  57531. /**
  57532. * The rendering group used by the Particle system to chose when to render.
  57533. */
  57534. this.renderingGroupId = 0;
  57535. /**
  57536. * The layer mask we are rendering the particles through.
  57537. */
  57538. this.layerMask = 0x0FFFFFFF;
  57539. this._targetIndex = 0;
  57540. this._currentRenderId = -1;
  57541. this._started = false;
  57542. this._stopped = false;
  57543. this._timeDelta = 0;
  57544. this._attributesStrideSize = 16;
  57545. this._actualFrame = 0;
  57546. /**
  57547. * List of animations used by the particle system.
  57548. */
  57549. this.animations = [];
  57550. /**
  57551. * An event triggered when the system is disposed.
  57552. */
  57553. this.onDisposeObservable = new BABYLON.Observable();
  57554. /**
  57555. * The overall motion speed (0.01 is default update speed, faster updates = faster animation)
  57556. */
  57557. this.updateSpeed = 0.01;
  57558. /**
  57559. * The amount of time the particle system is running (depends of the overall update speed).
  57560. */
  57561. this.targetStopDuration = 0;
  57562. /**
  57563. * Blend mode use to render the particle, it can be either ParticleSystem.BLENDMODE_ONEONE or ParticleSystem.BLENDMODE_STANDARD.
  57564. */
  57565. this.blendMode = BABYLON.ParticleSystem.BLENDMODE_ONEONE;
  57566. /**
  57567. * Minimum life time of emitting particles.
  57568. */
  57569. this.minLifeTime = 1;
  57570. /**
  57571. * Maximum life time of emitting particles.
  57572. */
  57573. this.maxLifeTime = 1;
  57574. /**
  57575. * Minimum Size of emitting particles.
  57576. */
  57577. this.minSize = 1;
  57578. /**
  57579. * Maximum Size of emitting particles.
  57580. */
  57581. this.maxSize = 1;
  57582. /**
  57583. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  57584. */
  57585. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  57586. /**
  57587. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  57588. */
  57589. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  57590. /**
  57591. * Color the particle will have at the end of its lifetime.
  57592. */
  57593. this.colorDead = new BABYLON.Color4(0, 0, 0, 0);
  57594. /**
  57595. * The maximum number of particles to emit per frame until we reach the activeParticleCount value
  57596. */
  57597. this.emitRate = 100;
  57598. /**
  57599. * You can use gravity if you want to give an orientation to your particles.
  57600. */
  57601. this.gravity = BABYLON.Vector3.Zero();
  57602. /**
  57603. * Minimum power of emitting particles.
  57604. */
  57605. this.minEmitPower = 1;
  57606. /**
  57607. * Maximum power of emitting particles.
  57608. */
  57609. this.maxEmitPower = 1;
  57610. /**
  57611. * Minimum angular speed of emitting particles (Z-axis rotation for each particle).
  57612. */
  57613. this.minAngularSpeed = 0;
  57614. /**
  57615. * Maximum angular speed of emitting particles (Z-axis rotation for each particle).
  57616. */
  57617. this.maxAngularSpeed = 0;
  57618. /**
  57619. * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls
  57620. * to override the particles.
  57621. */
  57622. this.forceDepthWrite = false;
  57623. this.id = name;
  57624. this.name = name;
  57625. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  57626. this._engine = this._scene.getEngine();
  57627. var fullOptions = __assign({ capacity: 50000, randomTextureSize: this._engine.getCaps().maxTextureSize }, options);
  57628. this._capacity = fullOptions.capacity;
  57629. this._activeCount = fullOptions.capacity;
  57630. this._currentActiveCount = 0;
  57631. this._scene.particleSystems.push(this);
  57632. this._updateEffectOptions = {
  57633. attributes: ["position", "age", "life", "seed", "size", "color", "direction", "angle"],
  57634. uniformsNames: ["currentCount", "timeDelta", "generalRandoms", "emitterWM", "lifeTime", "color1", "color2", "sizeRange", "gravity", "emitPower",
  57635. "direction1", "direction2", "minEmitBox", "maxEmitBox", "radius", "directionRandomizer", "height", "coneAngle", "stopFactor",
  57636. "angleRange"],
  57637. uniformBuffersNames: [],
  57638. samplers: ["randomSampler"],
  57639. defines: "",
  57640. fallbacks: null,
  57641. onCompiled: null,
  57642. onError: null,
  57643. indexParameters: null,
  57644. maxSimultaneousLights: 0,
  57645. transformFeedbackVaryings: ["outPosition", "outAge", "outLife", "outSeed", "outSize", "outColor", "outDirection", "outAngle"]
  57646. };
  57647. // Random data
  57648. var maxTextureSize = Math.min(this._engine.getCaps().maxTextureSize, fullOptions.randomTextureSize);
  57649. var d = [];
  57650. for (var i = 0; i < maxTextureSize; ++i) {
  57651. d.push(Math.random());
  57652. d.push(Math.random());
  57653. d.push(Math.random());
  57654. d.push(Math.random());
  57655. }
  57656. 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);
  57657. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  57658. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  57659. this._randomTextureSize = maxTextureSize;
  57660. this.particleEmitterType = new BABYLON.BoxParticleEmitter();
  57661. }
  57662. Object.defineProperty(GPUParticleSystem, "IsSupported", {
  57663. /**
  57664. * Gets a boolean indicating if the GPU particles can be rendered on current browser
  57665. */
  57666. get: function () {
  57667. if (!BABYLON.Engine.LastCreatedEngine) {
  57668. return false;
  57669. }
  57670. return BABYLON.Engine.LastCreatedEngine.webGLVersion > 1;
  57671. },
  57672. enumerable: true,
  57673. configurable: true
  57674. });
  57675. Object.defineProperty(GPUParticleSystem.prototype, "direction1", {
  57676. /**
  57677. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  57678. * This only works when particleEmitterTyps is a BoxParticleEmitter
  57679. */
  57680. get: function () {
  57681. if (this.particleEmitterType.direction1) {
  57682. return this.particleEmitterType.direction1;
  57683. }
  57684. return BABYLON.Vector3.Zero();
  57685. },
  57686. set: function (value) {
  57687. if (this.particleEmitterType.direction1) {
  57688. this.particleEmitterType.direction1 = value;
  57689. }
  57690. },
  57691. enumerable: true,
  57692. configurable: true
  57693. });
  57694. Object.defineProperty(GPUParticleSystem.prototype, "direction2", {
  57695. /**
  57696. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  57697. * This only works when particleEmitterTyps is a BoxParticleEmitter
  57698. */
  57699. get: function () {
  57700. if (this.particleEmitterType.direction2) {
  57701. return this.particleEmitterType.direction2;
  57702. }
  57703. return BABYLON.Vector3.Zero();
  57704. },
  57705. set: function (value) {
  57706. if (this.particleEmitterType.direction2) {
  57707. this.particleEmitterType.direction2 = value;
  57708. }
  57709. },
  57710. enumerable: true,
  57711. configurable: true
  57712. });
  57713. Object.defineProperty(GPUParticleSystem.prototype, "minEmitBox", {
  57714. /**
  57715. * 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.
  57716. * This only works when particleEmitterTyps is a BoxParticleEmitter
  57717. */
  57718. get: function () {
  57719. if (this.particleEmitterType.minEmitBox) {
  57720. return this.particleEmitterType.minEmitBox;
  57721. }
  57722. return BABYLON.Vector3.Zero();
  57723. },
  57724. set: function (value) {
  57725. if (this.particleEmitterType.minEmitBox) {
  57726. this.particleEmitterType.minEmitBox = value;
  57727. }
  57728. },
  57729. enumerable: true,
  57730. configurable: true
  57731. });
  57732. Object.defineProperty(GPUParticleSystem.prototype, "maxEmitBox", {
  57733. /**
  57734. * 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.
  57735. * This only works when particleEmitterTyps is a BoxParticleEmitter
  57736. */
  57737. get: function () {
  57738. if (this.particleEmitterType.maxEmitBox) {
  57739. return this.particleEmitterType.maxEmitBox;
  57740. }
  57741. return BABYLON.Vector3.Zero();
  57742. },
  57743. set: function (value) {
  57744. if (this.particleEmitterType.maxEmitBox) {
  57745. this.particleEmitterType.maxEmitBox = value;
  57746. }
  57747. },
  57748. enumerable: true,
  57749. configurable: true
  57750. });
  57751. /**
  57752. * Gets the maximum number of particles active at the same time.
  57753. * @returns The max number of active particles.
  57754. */
  57755. GPUParticleSystem.prototype.getCapacity = function () {
  57756. return this._capacity;
  57757. };
  57758. Object.defineProperty(GPUParticleSystem.prototype, "activeParticleCount", {
  57759. /**
  57760. * Gets or set the number of active particles
  57761. */
  57762. get: function () {
  57763. return this._activeCount;
  57764. },
  57765. set: function (value) {
  57766. this._activeCount = Math.min(value, this._capacity);
  57767. },
  57768. enumerable: true,
  57769. configurable: true
  57770. });
  57771. /**
  57772. * Is this system ready to be used/rendered
  57773. * @return true if the system is ready
  57774. */
  57775. GPUParticleSystem.prototype.isReady = function () {
  57776. if (!this._updateEffect) {
  57777. this._recreateUpdateEffect();
  57778. this._recreateRenderEffect();
  57779. return false;
  57780. }
  57781. if (!this.emitter || !this._updateEffect.isReady() || !this._renderEffect.isReady() || !this.particleTexture || !this.particleTexture.isReady()) {
  57782. return false;
  57783. }
  57784. return true;
  57785. };
  57786. /**
  57787. * Gets Wether the system has been started.
  57788. * @returns True if it has been started, otherwise false.
  57789. */
  57790. GPUParticleSystem.prototype.isStarted = function () {
  57791. return this._started;
  57792. };
  57793. /**
  57794. * Starts the particle system and begins to emit.
  57795. */
  57796. GPUParticleSystem.prototype.start = function () {
  57797. this._started = true;
  57798. this._stopped = false;
  57799. };
  57800. /**
  57801. * Stops the particle system.
  57802. */
  57803. GPUParticleSystem.prototype.stop = function () {
  57804. this._stopped = true;
  57805. };
  57806. /**
  57807. * Remove all active particles
  57808. */
  57809. GPUParticleSystem.prototype.reset = function () {
  57810. this._releaseBuffers();
  57811. this._releaseVAOs();
  57812. this._currentActiveCount = 0;
  57813. this._targetIndex = 0;
  57814. };
  57815. /**
  57816. * Returns the string "GPUParticleSystem"
  57817. * @returns a string containing the class name
  57818. */
  57819. GPUParticleSystem.prototype.getClassName = function () {
  57820. return "GPUParticleSystem";
  57821. };
  57822. GPUParticleSystem.prototype._createUpdateVAO = function (source) {
  57823. var updateVertexBuffers = {};
  57824. updateVertexBuffers["position"] = source.createVertexBuffer("position", 0, 3);
  57825. updateVertexBuffers["age"] = source.createVertexBuffer("age", 3, 1);
  57826. updateVertexBuffers["life"] = source.createVertexBuffer("life", 4, 1);
  57827. updateVertexBuffers["seed"] = source.createVertexBuffer("seed", 5, 1);
  57828. updateVertexBuffers["size"] = source.createVertexBuffer("size", 6, 1);
  57829. updateVertexBuffers["color"] = source.createVertexBuffer("color", 7, 4);
  57830. updateVertexBuffers["direction"] = source.createVertexBuffer("direction", 11, 3);
  57831. updateVertexBuffers["angle"] = source.createVertexBuffer("angle", 14, 2);
  57832. var vao = this._engine.recordVertexArrayObject(updateVertexBuffers, null, this._updateEffect);
  57833. this._engine.bindArrayBuffer(null);
  57834. return vao;
  57835. };
  57836. GPUParticleSystem.prototype._createRenderVAO = function (source, spriteSource) {
  57837. var renderVertexBuffers = {};
  57838. renderVertexBuffers["position"] = source.createVertexBuffer("position", 0, 3, this._attributesStrideSize, true);
  57839. renderVertexBuffers["age"] = source.createVertexBuffer("age", 3, 1, this._attributesStrideSize, true);
  57840. renderVertexBuffers["life"] = source.createVertexBuffer("life", 4, 1, this._attributesStrideSize, true);
  57841. renderVertexBuffers["size"] = source.createVertexBuffer("size", 6, 1, this._attributesStrideSize, true);
  57842. renderVertexBuffers["color"] = source.createVertexBuffer("color", 7, 4, this._attributesStrideSize, true);
  57843. renderVertexBuffers["angle"] = source.createVertexBuffer("angle", 14, 2, this._attributesStrideSize, true);
  57844. renderVertexBuffers["offset"] = spriteSource.createVertexBuffer("offset", 0, 2);
  57845. renderVertexBuffers["uv"] = spriteSource.createVertexBuffer("uv", 2, 2);
  57846. var vao = this._engine.recordVertexArrayObject(renderVertexBuffers, null, this._renderEffect);
  57847. this._engine.bindArrayBuffer(null);
  57848. return vao;
  57849. };
  57850. GPUParticleSystem.prototype._initialize = function (force) {
  57851. if (force === void 0) { force = false; }
  57852. if (this._buffer0 && !force) {
  57853. return;
  57854. }
  57855. var engine = this._scene.getEngine();
  57856. var data = new Array();
  57857. for (var particleIndex = 0; particleIndex < this._capacity; particleIndex++) {
  57858. // position
  57859. data.push(0.0);
  57860. data.push(0.0);
  57861. data.push(0.0);
  57862. // Age and life
  57863. data.push(0.0); // create the particle as a dead one to create a new one at start
  57864. data.push(0.0);
  57865. // Seed
  57866. data.push(Math.random());
  57867. // Size
  57868. data.push(0.0);
  57869. // color
  57870. data.push(0.0);
  57871. data.push(0.0);
  57872. data.push(0.0);
  57873. data.push(0.0);
  57874. // direction
  57875. data.push(0.0);
  57876. data.push(0.0);
  57877. data.push(0.0);
  57878. // angle
  57879. data.push(0.0);
  57880. data.push(0.0);
  57881. }
  57882. // Sprite data
  57883. var spriteData = new Float32Array([0.5, 0.5, 1, 1,
  57884. -0.5, 0.5, 0, 1,
  57885. -0.5, -0.5, 0, 0,
  57886. 0.5, -0.5, 1, 0]);
  57887. // Buffers
  57888. this._buffer0 = new BABYLON.Buffer(engine, data, false, this._attributesStrideSize);
  57889. this._buffer1 = new BABYLON.Buffer(engine, data, false, this._attributesStrideSize);
  57890. this._spriteBuffer = new BABYLON.Buffer(engine, spriteData, false, 4);
  57891. // Update VAO
  57892. this._updateVAO = [];
  57893. this._updateVAO.push(this._createUpdateVAO(this._buffer0));
  57894. this._updateVAO.push(this._createUpdateVAO(this._buffer1));
  57895. // Render VAO
  57896. this._renderVAO = [];
  57897. this._renderVAO.push(this._createRenderVAO(this._buffer1, this._spriteBuffer));
  57898. this._renderVAO.push(this._createRenderVAO(this._buffer0, this._spriteBuffer));
  57899. // Links
  57900. this._sourceBuffer = this._buffer0;
  57901. this._targetBuffer = this._buffer1;
  57902. };
  57903. /** @hidden */
  57904. GPUParticleSystem.prototype._recreateUpdateEffect = function () {
  57905. var defines = this.particleEmitterType ? this.particleEmitterType.getEffectDefines() : "";
  57906. if (this._updateEffect && this._updateEffectOptions.defines === defines) {
  57907. return;
  57908. }
  57909. this._updateEffectOptions.defines = defines;
  57910. this._updateEffect = new BABYLON.Effect("gpuUpdateParticles", this._updateEffectOptions, this._scene.getEngine());
  57911. };
  57912. /** @hidden */
  57913. GPUParticleSystem.prototype._recreateRenderEffect = function () {
  57914. var defines = "";
  57915. if (this._scene.clipPlane) {
  57916. defines = "\n#define CLIPPLANE";
  57917. }
  57918. if (this._renderEffect && this._renderEffect.defines === defines) {
  57919. return;
  57920. }
  57921. this._renderEffect = new BABYLON.Effect("gpuRenderParticles", ["position", "age", "life", "size", "color", "offset", "uv", "angle"], ["view", "projection", "colorDead", "invView", "vClipPlane"], ["textureSampler"], this._scene.getEngine(), defines);
  57922. };
  57923. /**
  57924. * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
  57925. */
  57926. GPUParticleSystem.prototype.animate = function () {
  57927. this._timeDelta = this.updateSpeed * this._scene.getAnimationRatio();
  57928. this._actualFrame += this._timeDelta;
  57929. if (!this._stopped) {
  57930. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration) {
  57931. this.stop();
  57932. }
  57933. }
  57934. };
  57935. /**
  57936. * Renders the particle system in its current state.
  57937. * @returns the current number of particles
  57938. */
  57939. GPUParticleSystem.prototype.render = function () {
  57940. if (!this._started) {
  57941. return 0;
  57942. }
  57943. this._recreateUpdateEffect();
  57944. this._recreateRenderEffect();
  57945. if (!this.isReady()) {
  57946. return 0;
  57947. }
  57948. if (this._currentRenderId === this._scene.getRenderId()) {
  57949. return 0;
  57950. }
  57951. this._currentRenderId = this._scene.getRenderId();
  57952. // Get everything ready to render
  57953. this._initialize();
  57954. this._currentActiveCount = Math.min(this._activeCount, this._currentActiveCount + (this.emitRate * this._timeDelta) | 0);
  57955. // Enable update effect
  57956. this._engine.enableEffect(this._updateEffect);
  57957. this._engine.setState(false);
  57958. this._updateEffect.setFloat("currentCount", this._currentActiveCount);
  57959. this._updateEffect.setFloat("timeDelta", this._timeDelta);
  57960. this._updateEffect.setFloat("stopFactor", this._stopped ? 0 : 1);
  57961. this._updateEffect.setFloat3("generalRandoms", Math.random(), Math.random(), Math.random());
  57962. this._updateEffect.setTexture("randomSampler", this._randomTexture);
  57963. this._updateEffect.setFloat2("lifeTime", this.minLifeTime, this.maxLifeTime);
  57964. this._updateEffect.setFloat2("emitPower", this.minEmitPower, this.maxEmitPower);
  57965. this._updateEffect.setDirectColor4("color1", this.color1);
  57966. this._updateEffect.setDirectColor4("color2", this.color2);
  57967. this._updateEffect.setFloat2("sizeRange", this.minSize, this.maxSize);
  57968. this._updateEffect.setFloat2("angleRange", this.minAngularSpeed, this.maxAngularSpeed);
  57969. this._updateEffect.setVector3("gravity", this.gravity);
  57970. if (this.particleEmitterType) {
  57971. this.particleEmitterType.applyToShader(this._updateEffect);
  57972. }
  57973. var emitterWM;
  57974. if (this.emitter.position) {
  57975. var emitterMesh = this.emitter;
  57976. emitterWM = emitterMesh.getWorldMatrix();
  57977. }
  57978. else {
  57979. var emitterPosition = this.emitter;
  57980. emitterWM = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  57981. }
  57982. this._updateEffect.setMatrix("emitterWM", emitterWM);
  57983. // Bind source VAO
  57984. this._engine.bindVertexArrayObject(this._updateVAO[this._targetIndex], null);
  57985. // Update
  57986. this._engine.bindTransformFeedbackBuffer(this._targetBuffer.getBuffer());
  57987. this._engine.setRasterizerState(false);
  57988. this._engine.beginTransformFeedback();
  57989. this._engine.drawArraysType(BABYLON.Material.PointListDrawMode, 0, this._currentActiveCount);
  57990. this._engine.endTransformFeedback();
  57991. this._engine.setRasterizerState(true);
  57992. this._engine.bindTransformFeedbackBuffer(null);
  57993. // Enable render effect
  57994. this._engine.enableEffect(this._renderEffect);
  57995. var viewMatrix = this._scene.getViewMatrix();
  57996. this._renderEffect.setMatrix("view", viewMatrix);
  57997. this._renderEffect.setMatrix("projection", this._scene.getProjectionMatrix());
  57998. this._renderEffect.setTexture("textureSampler", this.particleTexture);
  57999. this._renderEffect.setDirectColor4("colorDead", this.colorDead);
  58000. if (this._scene.clipPlane) {
  58001. var clipPlane = this._scene.clipPlane;
  58002. var invView = viewMatrix.clone();
  58003. invView.invert();
  58004. this._renderEffect.setMatrix("invView", invView);
  58005. this._renderEffect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  58006. }
  58007. // Draw order
  58008. if (this.blendMode === BABYLON.ParticleSystem.BLENDMODE_ONEONE) {
  58009. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  58010. }
  58011. else {
  58012. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  58013. }
  58014. if (this.forceDepthWrite) {
  58015. this._engine.setDepthWrite(true);
  58016. }
  58017. // Bind source VAO
  58018. this._engine.bindVertexArrayObject(this._renderVAO[this._targetIndex], null);
  58019. // Render
  58020. this._engine.drawArraysType(BABYLON.Material.TriangleFanDrawMode, 0, 4, this._currentActiveCount);
  58021. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  58022. // Switch VAOs
  58023. this._targetIndex++;
  58024. if (this._targetIndex === 2) {
  58025. this._targetIndex = 0;
  58026. }
  58027. // Switch buffers
  58028. var tmpBuffer = this._sourceBuffer;
  58029. this._sourceBuffer = this._targetBuffer;
  58030. this._targetBuffer = tmpBuffer;
  58031. return this._currentActiveCount;
  58032. };
  58033. /**
  58034. * Rebuilds the particle system
  58035. */
  58036. GPUParticleSystem.prototype.rebuild = function () {
  58037. this._initialize(true);
  58038. };
  58039. GPUParticleSystem.prototype._releaseBuffers = function () {
  58040. if (this._buffer0) {
  58041. this._buffer0.dispose();
  58042. this._buffer0 = null;
  58043. }
  58044. if (this._buffer1) {
  58045. this._buffer1.dispose();
  58046. this._buffer1 = null;
  58047. }
  58048. if (this._spriteBuffer) {
  58049. this._spriteBuffer.dispose();
  58050. this._spriteBuffer = null;
  58051. }
  58052. };
  58053. GPUParticleSystem.prototype._releaseVAOs = function () {
  58054. if (!this._updateVAO) {
  58055. return;
  58056. }
  58057. for (var index = 0; index < this._updateVAO.length; index++) {
  58058. this._engine.releaseVertexArrayObject(this._updateVAO[index]);
  58059. }
  58060. this._updateVAO = [];
  58061. for (var index = 0; index < this._renderVAO.length; index++) {
  58062. this._engine.releaseVertexArrayObject(this._renderVAO[index]);
  58063. }
  58064. this._renderVAO = [];
  58065. };
  58066. /**
  58067. * Disposes the particle system and free the associated resources
  58068. * @param disposeTexture defines if the particule texture must be disposed as well (true by default)
  58069. */
  58070. GPUParticleSystem.prototype.dispose = function (disposeTexture) {
  58071. if (disposeTexture === void 0) { disposeTexture = true; }
  58072. var index = this._scene.particleSystems.indexOf(this);
  58073. if (index > -1) {
  58074. this._scene.particleSystems.splice(index, 1);
  58075. }
  58076. this._releaseBuffers();
  58077. this._releaseVAOs();
  58078. if (this._randomTexture) {
  58079. this._randomTexture.dispose();
  58080. this._randomTexture = null;
  58081. }
  58082. if (disposeTexture && this.particleTexture) {
  58083. this.particleTexture.dispose();
  58084. this.particleTexture = null;
  58085. }
  58086. // Callback
  58087. this.onDisposeObservable.notifyObservers(this);
  58088. this.onDisposeObservable.clear();
  58089. };
  58090. /**
  58091. * Clones the particle system.
  58092. * @param name The name of the cloned object
  58093. * @param newEmitter The new emitter to use
  58094. * @returns the cloned particle system
  58095. */
  58096. GPUParticleSystem.prototype.clone = function (name, newEmitter) {
  58097. var result = new GPUParticleSystem(name, { capacity: this._capacity, randomTextureSize: this._randomTextureSize }, this._scene);
  58098. BABYLON.Tools.DeepCopy(this, result);
  58099. if (newEmitter === undefined) {
  58100. newEmitter = this.emitter;
  58101. }
  58102. result.emitter = newEmitter;
  58103. if (this.particleTexture) {
  58104. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  58105. }
  58106. return result;
  58107. };
  58108. /**
  58109. * Serializes the particle system to a JSON object.
  58110. * @returns the JSON object
  58111. */
  58112. GPUParticleSystem.prototype.serialize = function () {
  58113. var serializationObject = {};
  58114. serializationObject.name = this.name;
  58115. serializationObject.id = this.id;
  58116. // Emitter
  58117. if (this.emitter.position) {
  58118. var emitterMesh = this.emitter;
  58119. serializationObject.emitterId = emitterMesh.id;
  58120. }
  58121. else {
  58122. var emitterPosition = this.emitter;
  58123. serializationObject.emitter = emitterPosition.asArray();
  58124. }
  58125. serializationObject.capacity = this.getCapacity();
  58126. if (this.particleTexture) {
  58127. serializationObject.textureName = this.particleTexture.name;
  58128. }
  58129. // Animations
  58130. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  58131. // Particle system
  58132. serializationObject.activeParticleCount = this.activeParticleCount;
  58133. serializationObject.randomTextureSize = this._randomTextureSize;
  58134. serializationObject.minSize = this.minSize;
  58135. serializationObject.maxSize = this.maxSize;
  58136. serializationObject.minEmitPower = this.minEmitPower;
  58137. serializationObject.maxEmitPower = this.maxEmitPower;
  58138. serializationObject.minLifeTime = this.minLifeTime;
  58139. serializationObject.maxLifeTime = this.maxLifeTime;
  58140. serializationObject.minAngularSpeed = this.minAngularSpeed;
  58141. serializationObject.maxAngularSpeed = this.maxAngularSpeed;
  58142. serializationObject.emitRate = this.emitRate;
  58143. serializationObject.gravity = this.gravity.asArray();
  58144. serializationObject.color1 = this.color1.asArray();
  58145. serializationObject.color2 = this.color2.asArray();
  58146. serializationObject.colorDead = this.colorDead.asArray();
  58147. serializationObject.updateSpeed = this.updateSpeed;
  58148. serializationObject.targetStopDuration = this.targetStopDuration;
  58149. serializationObject.blendMode = this.blendMode;
  58150. // Emitter
  58151. if (this.particleEmitterType) {
  58152. serializationObject.particleEmitterType = this.particleEmitterType.serialize();
  58153. }
  58154. return serializationObject;
  58155. };
  58156. /**
  58157. * Parses a JSON object to create a GPU particle system.
  58158. * @param parsedParticleSystem The JSON object to parse
  58159. * @param scene The scene to create the particle system in
  58160. * @param rootUrl The root url to use to load external dependencies like texture
  58161. * @returns the parsed GPU particle system
  58162. */
  58163. GPUParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  58164. var name = parsedParticleSystem.name;
  58165. var particleSystem = new GPUParticleSystem(name, { capacity: parsedParticleSystem.capacity, randomTextureSize: parsedParticleSystem.randomTextureSize }, scene);
  58166. if (parsedParticleSystem.id) {
  58167. particleSystem.id = parsedParticleSystem.id;
  58168. }
  58169. // Texture
  58170. if (parsedParticleSystem.textureName) {
  58171. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  58172. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  58173. }
  58174. // Emitter
  58175. if (parsedParticleSystem.emitterId) {
  58176. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  58177. }
  58178. else {
  58179. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  58180. }
  58181. // Animations
  58182. if (parsedParticleSystem.animations) {
  58183. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  58184. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  58185. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  58186. }
  58187. }
  58188. // Particle system
  58189. particleSystem.activeParticleCount = parsedParticleSystem.activeParticleCount;
  58190. particleSystem.minSize = parsedParticleSystem.minSize;
  58191. particleSystem.maxSize = parsedParticleSystem.maxSize;
  58192. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  58193. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  58194. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  58195. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  58196. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  58197. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  58198. particleSystem.emitRate = parsedParticleSystem.emitRate;
  58199. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  58200. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  58201. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  58202. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  58203. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  58204. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  58205. particleSystem.blendMode = parsedParticleSystem.blendMode;
  58206. // Emitter
  58207. if (parsedParticleSystem.particleEmitterType) {
  58208. var emitterType = void 0;
  58209. switch (parsedParticleSystem.particleEmitterType.type) {
  58210. case "SphereEmitter":
  58211. emitterType = new BABYLON.SphereParticleEmitter();
  58212. break;
  58213. case "SphereDirectedParticleEmitter":
  58214. emitterType = new BABYLON.SphereDirectedParticleEmitter();
  58215. break;
  58216. case "ConeEmitter":
  58217. emitterType = new BABYLON.ConeParticleEmitter();
  58218. break;
  58219. case "BoxEmitter":
  58220. default:
  58221. emitterType = new BABYLON.BoxParticleEmitter();
  58222. break;
  58223. }
  58224. emitterType.parse(parsedParticleSystem.particleEmitterType);
  58225. particleSystem.particleEmitterType = emitterType;
  58226. }
  58227. return particleSystem;
  58228. };
  58229. return GPUParticleSystem;
  58230. }());
  58231. BABYLON.GPUParticleSystem = GPUParticleSystem;
  58232. })(BABYLON || (BABYLON = {}));
  58233. //# sourceMappingURL=babylon.gpuParticleSystem.js.map
  58234. var BABYLON;
  58235. (function (BABYLON) {
  58236. /**
  58237. * Represents one particle of a solid particle system.
  58238. */
  58239. var SolidParticle = /** @class */ (function () {
  58240. /**
  58241. * Creates a Solid Particle object.
  58242. * Don't create particles manually, use instead the Solid Particle System internal tools like _addParticle()
  58243. * @param particleIndex (integer) is the particle index in the Solid Particle System pool. It's also the particle identifier.
  58244. * @param positionIndex (integer) is the starting index of the particle vertices in the SPS "positions" array.
  58245. * @param indiceIndex (integer) is the starting index of the particle indices in the SPS "indices" array.
  58246. * @param model (ModelShape) is a reference to the model shape on what the particle is designed.
  58247. * @param shapeId (integer) is the model shape identifier in the SPS.
  58248. * @param idxInShape (integer) is the index of the particle in the current model (ex: the 10th box of addShape(box, 30))
  58249. * @param modelBoundingInfo is the reference to the model BoundingInfo used for intersection computations.
  58250. */
  58251. function SolidParticle(particleIndex, positionIndex, indiceIndex, model, shapeId, idxInShape, sps, modelBoundingInfo) {
  58252. if (modelBoundingInfo === void 0) { modelBoundingInfo = null; }
  58253. /**
  58254. * particle global index
  58255. */
  58256. this.idx = 0;
  58257. /**
  58258. * The color of the particle
  58259. */
  58260. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  58261. /**
  58262. * The world space position of the particle.
  58263. */
  58264. this.position = BABYLON.Vector3.Zero();
  58265. /**
  58266. * The world space rotation of the particle. (Not use if rotationQuaternion is set)
  58267. */
  58268. this.rotation = BABYLON.Vector3.Zero();
  58269. /**
  58270. * The scaling of the particle.
  58271. */
  58272. this.scaling = BABYLON.Vector3.One();
  58273. /**
  58274. * The uvs of the particle.
  58275. */
  58276. this.uvs = new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  58277. /**
  58278. * The current speed of the particle.
  58279. */
  58280. this.velocity = BABYLON.Vector3.Zero();
  58281. /**
  58282. * The pivot point in the particle local space.
  58283. */
  58284. this.pivot = BABYLON.Vector3.Zero();
  58285. /**
  58286. * Must the particle be translated from its pivot point in its local space ?
  58287. * In this case, the pivot point is set at the origin of the particle local space and the particle is translated.
  58288. * Default : false
  58289. */
  58290. this.translateFromPivot = false;
  58291. /**
  58292. * Is the particle active or not ?
  58293. */
  58294. this.alive = true;
  58295. /**
  58296. * Is the particle visible or not ?
  58297. */
  58298. this.isVisible = true;
  58299. /**
  58300. * Index of this particle in the global "positions" array (Internal use)
  58301. */
  58302. this._pos = 0;
  58303. /**
  58304. * Index of this particle in the global "indices" array (Internal use)
  58305. */
  58306. this._ind = 0;
  58307. /**
  58308. * ModelShape id of this particle
  58309. */
  58310. this.shapeId = 0;
  58311. /**
  58312. * Index of the particle in its shape id (Internal use)
  58313. */
  58314. this.idxInShape = 0;
  58315. /**
  58316. * Still set as invisible in order to skip useless computations (Internal use)
  58317. */
  58318. this._stillInvisible = false;
  58319. /**
  58320. * Last computed particle rotation matrix
  58321. */
  58322. this._rotationMatrix = [1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0];
  58323. /**
  58324. * Parent particle Id, if any.
  58325. * Default null.
  58326. */
  58327. this.parentId = null;
  58328. /**
  58329. * Internal global position in the SPS.
  58330. */
  58331. this._globalPosition = BABYLON.Vector3.Zero();
  58332. this.idx = particleIndex;
  58333. this._pos = positionIndex;
  58334. this._ind = indiceIndex;
  58335. this._model = model;
  58336. this.shapeId = shapeId;
  58337. this.idxInShape = idxInShape;
  58338. this._sps = sps;
  58339. if (modelBoundingInfo) {
  58340. this._modelBoundingInfo = modelBoundingInfo;
  58341. this._boundingInfo = new BABYLON.BoundingInfo(modelBoundingInfo.minimum, modelBoundingInfo.maximum);
  58342. }
  58343. }
  58344. Object.defineProperty(SolidParticle.prototype, "scale", {
  58345. /**
  58346. * Legacy support, changed scale to scaling
  58347. */
  58348. get: function () {
  58349. return this.scaling;
  58350. },
  58351. /**
  58352. * Legacy support, changed scale to scaling
  58353. */
  58354. set: function (scale) {
  58355. this.scaling = scale;
  58356. },
  58357. enumerable: true,
  58358. configurable: true
  58359. });
  58360. Object.defineProperty(SolidParticle.prototype, "quaternion", {
  58361. /**
  58362. * Legacy support, changed quaternion to rotationQuaternion
  58363. */
  58364. get: function () {
  58365. return this.rotationQuaternion;
  58366. },
  58367. /**
  58368. * Legacy support, changed quaternion to rotationQuaternion
  58369. */
  58370. set: function (q) {
  58371. this.rotationQuaternion = q;
  58372. },
  58373. enumerable: true,
  58374. configurable: true
  58375. });
  58376. /**
  58377. * Returns a boolean. True if the particle intersects another particle or another mesh, else false.
  58378. * The intersection is computed on the particle bounding sphere and Axis Aligned Bounding Box (AABB)
  58379. * @param target is the object (solid particle or mesh) what the intersection is computed against.
  58380. * @returns true if it intersects
  58381. */
  58382. SolidParticle.prototype.intersectsMesh = function (target) {
  58383. if (!this._boundingInfo || !target._boundingInfo) {
  58384. return false;
  58385. }
  58386. if (this._sps._bSphereOnly) {
  58387. return BABYLON.BoundingSphere.Intersects(this._boundingInfo.boundingSphere, target._boundingInfo.boundingSphere);
  58388. }
  58389. return this._boundingInfo.intersects(target._boundingInfo, false);
  58390. };
  58391. return SolidParticle;
  58392. }());
  58393. BABYLON.SolidParticle = SolidParticle;
  58394. /**
  58395. * Represents the shape of the model used by one particle of a solid particle system.
  58396. * SPS internal tool, don't use it manually.
  58397. */
  58398. var ModelShape = /** @class */ (function () {
  58399. /**
  58400. * 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.
  58401. * SPS internal tool, don't use it manually.
  58402. * @hidden
  58403. */
  58404. function ModelShape(id, shape, indicesLength, shapeUV, posFunction, vtxFunction) {
  58405. /**
  58406. * length of the shape in the model indices array (internal use)
  58407. */
  58408. this._indicesLength = 0;
  58409. this.shapeID = id;
  58410. this._shape = shape;
  58411. this._indicesLength = indicesLength;
  58412. this._shapeUV = shapeUV;
  58413. this._positionFunction = posFunction;
  58414. this._vertexFunction = vtxFunction;
  58415. }
  58416. return ModelShape;
  58417. }());
  58418. BABYLON.ModelShape = ModelShape;
  58419. /**
  58420. * Represents a Depth Sorted Particle in the solid particle system.
  58421. */
  58422. var DepthSortedParticle = /** @class */ (function () {
  58423. function DepthSortedParticle() {
  58424. /**
  58425. * Index of the particle in the "indices" array
  58426. */
  58427. this.ind = 0;
  58428. /**
  58429. * Length of the particle shape in the "indices" array
  58430. */
  58431. this.indicesLength = 0;
  58432. /**
  58433. * Squared distance from the particle to the camera
  58434. */
  58435. this.sqDistance = 0.0;
  58436. }
  58437. return DepthSortedParticle;
  58438. }());
  58439. BABYLON.DepthSortedParticle = DepthSortedParticle;
  58440. })(BABYLON || (BABYLON = {}));
  58441. //# sourceMappingURL=babylon.solidParticle.js.map
  58442. var BABYLON;
  58443. (function (BABYLON) {
  58444. /**
  58445. * The SPS is a single updatable mesh. The solid particles are simply separate parts or faces fo this big mesh.
  58446. *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.
  58447. * The SPS is also a particle system. It provides some methods to manage the particles.
  58448. * However it is behavior agnostic. This means it has no emitter, no particle physics, no particle recycler. You have to implement your own behavior.
  58449. *
  58450. * Full documentation here : http://doc.babylonjs.com/overviews/Solid_Particle_System
  58451. */
  58452. var SolidParticleSystem = /** @class */ (function () {
  58453. /**
  58454. * Creates a SPS (Solid Particle System) object.
  58455. * @param name (String) is the SPS name, this will be the underlying mesh name.
  58456. * @param scene (Scene) is the scene in which the SPS is added.
  58457. * @param updatable (optional boolean, default true) : if the SPS must be updatable or immutable.
  58458. * @param isPickable (optional boolean, default false) : if the solid particles must be pickable.
  58459. * @param enableDepthSort (optional boolean, default false) : if the solid particles must be sorted in the geometry according to their distance to the camera.
  58460. * @param particleIntersection (optional boolean, default false) : if the solid particle intersections must be computed.
  58461. * @param boundingSphereOnly (optional boolean, default false) : if the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster).
  58462. * @param bSphereRadiusFactor (optional float, default 1.0) : a number to multiply the boundind sphere radius by in order to reduce it for instance.
  58463. * @example bSphereRadiusFactor = 1.0 / Math.sqrt(3.0) => the bounding sphere exactly matches a spherical mesh.
  58464. */
  58465. function SolidParticleSystem(name, scene, options) {
  58466. /**
  58467. * The SPS array of Solid Particle objects. Just access each particle as with any classic array.
  58468. * Example : var p = SPS.particles[i];
  58469. */
  58470. this.particles = new Array();
  58471. /**
  58472. * The SPS total number of particles. Read only. Use SPS.counter instead if you need to set your own value.
  58473. */
  58474. this.nbParticles = 0;
  58475. /**
  58476. * If the particles must ever face the camera (default false). Useful for planar particles.
  58477. */
  58478. this.billboard = false;
  58479. /**
  58480. * Recompute normals when adding a shape
  58481. */
  58482. this.recomputeNormals = true;
  58483. /**
  58484. * This a counter ofr your own usage. It's not set by any SPS functions.
  58485. */
  58486. this.counter = 0;
  58487. /**
  58488. * This empty object is intended to store some SPS specific or temporary values in order to lower the Garbage Collector activity.
  58489. * Please read : http://doc.babylonjs.com/overviews/Solid_Particle_System#garbage-collector-concerns
  58490. */
  58491. this.vars = {};
  58492. /**
  58493. * If the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster). (Internal use only)
  58494. */
  58495. this._bSphereOnly = false;
  58496. /**
  58497. * A number to multiply the boundind sphere radius by in order to reduce it for instance. (Internal use only)
  58498. */
  58499. this._bSphereRadiusFactor = 1.0;
  58500. this._positions = new Array();
  58501. this._indices = new Array();
  58502. this._normals = new Array();
  58503. this._colors = new Array();
  58504. this._uvs = new Array();
  58505. this._index = 0; // indices index
  58506. this._updatable = true;
  58507. this._pickable = false;
  58508. this._isVisibilityBoxLocked = false;
  58509. this._alwaysVisible = false;
  58510. this._depthSort = false;
  58511. this._shapeCounter = 0;
  58512. this._copy = new BABYLON.SolidParticle(0, 0, 0, null, 0, 0, this);
  58513. this._color = new BABYLON.Color4(0, 0, 0, 0);
  58514. this._computeParticleColor = true;
  58515. this._computeParticleTexture = true;
  58516. this._computeParticleRotation = true;
  58517. this._computeParticleVertex = false;
  58518. this._computeBoundingBox = false;
  58519. this._depthSortParticles = true;
  58520. this._cam_axisZ = BABYLON.Vector3.Zero();
  58521. this._cam_axisY = BABYLON.Vector3.Zero();
  58522. this._cam_axisX = BABYLON.Vector3.Zero();
  58523. this._axisZ = BABYLON.Axis.Z;
  58524. this._camDir = BABYLON.Vector3.Zero();
  58525. this._camInvertedPosition = BABYLON.Vector3.Zero();
  58526. this._rotMatrix = new BABYLON.Matrix();
  58527. this._invertMatrix = new BABYLON.Matrix();
  58528. this._rotated = BABYLON.Vector3.Zero();
  58529. this._quaternion = new BABYLON.Quaternion();
  58530. this._vertex = BABYLON.Vector3.Zero();
  58531. this._normal = BABYLON.Vector3.Zero();
  58532. this._yaw = 0.0;
  58533. this._pitch = 0.0;
  58534. this._roll = 0.0;
  58535. this._halfroll = 0.0;
  58536. this._halfpitch = 0.0;
  58537. this._halfyaw = 0.0;
  58538. this._sinRoll = 0.0;
  58539. this._cosRoll = 0.0;
  58540. this._sinPitch = 0.0;
  58541. this._cosPitch = 0.0;
  58542. this._sinYaw = 0.0;
  58543. this._cosYaw = 0.0;
  58544. this._mustUnrotateFixedNormals = false;
  58545. this._minimum = BABYLON.Vector3.Zero();
  58546. this._maximum = BABYLON.Vector3.Zero();
  58547. this._minBbox = BABYLON.Vector3.Zero();
  58548. this._maxBbox = BABYLON.Vector3.Zero();
  58549. this._particlesIntersect = false;
  58550. this._depthSortFunction = function (p1, p2) {
  58551. return (p2.sqDistance - p1.sqDistance);
  58552. };
  58553. this._needs32Bits = false;
  58554. this._pivotBackTranslation = BABYLON.Vector3.Zero();
  58555. this._scaledPivot = BABYLON.Vector3.Zero();
  58556. this._particleHasParent = false;
  58557. this.name = name;
  58558. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  58559. this._camera = scene.activeCamera;
  58560. this._pickable = options ? options.isPickable : false;
  58561. this._depthSort = options ? options.enableDepthSort : false;
  58562. this._particlesIntersect = options ? options.particleIntersection : false;
  58563. this._bSphereOnly = options ? options.boundingSphereOnly : false;
  58564. this._bSphereRadiusFactor = (options && options.bSphereRadiusFactor) ? options.bSphereRadiusFactor : 1.0;
  58565. if (options && options.updatable) {
  58566. this._updatable = options.updatable;
  58567. }
  58568. else {
  58569. this._updatable = true;
  58570. }
  58571. if (this._pickable) {
  58572. this.pickedParticles = [];
  58573. }
  58574. if (this._depthSort) {
  58575. this.depthSortedParticles = [];
  58576. }
  58577. }
  58578. /**
  58579. * Builds the SPS underlying mesh. Returns a standard Mesh.
  58580. * If no model shape was added to the SPS, the returned mesh is just a single triangular plane.
  58581. * @returns the created mesh
  58582. */
  58583. SolidParticleSystem.prototype.buildMesh = function () {
  58584. if (this.nbParticles === 0) {
  58585. var triangle = BABYLON.MeshBuilder.CreateDisc("", { radius: 1, tessellation: 3 }, this._scene);
  58586. this.addShape(triangle, 1);
  58587. triangle.dispose();
  58588. }
  58589. this._indices32 = (this._needs32Bits) ? new Uint32Array(this._indices) : new Uint16Array(this._indices);
  58590. this._positions32 = new Float32Array(this._positions);
  58591. this._uvs32 = new Float32Array(this._uvs);
  58592. this._colors32 = new Float32Array(this._colors);
  58593. if (this.recomputeNormals) {
  58594. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals);
  58595. }
  58596. this._normals32 = new Float32Array(this._normals);
  58597. this._fixedNormal32 = new Float32Array(this._normals);
  58598. if (this._mustUnrotateFixedNormals) { // the particles could be created already rotated in the mesh with a positionFunction
  58599. this._unrotateFixedNormals();
  58600. }
  58601. var vertexData = new BABYLON.VertexData();
  58602. vertexData.indices = (this._depthSort) ? this._indices : this._indices32;
  58603. vertexData.set(this._positions32, BABYLON.VertexBuffer.PositionKind);
  58604. vertexData.set(this._normals32, BABYLON.VertexBuffer.NormalKind);
  58605. if (this._uvs32.length > 0) {
  58606. vertexData.set(this._uvs32, BABYLON.VertexBuffer.UVKind);
  58607. }
  58608. if (this._colors32.length > 0) {
  58609. vertexData.set(this._colors32, BABYLON.VertexBuffer.ColorKind);
  58610. }
  58611. var mesh = new BABYLON.Mesh(this.name, this._scene);
  58612. vertexData.applyToMesh(mesh, this._updatable);
  58613. this.mesh = mesh;
  58614. this.mesh.isPickable = this._pickable;
  58615. // free memory
  58616. if (!this._depthSort) {
  58617. this._indices = null;
  58618. }
  58619. this._positions = null;
  58620. this._normals = null;
  58621. this._uvs = null;
  58622. this._colors = null;
  58623. if (!this._updatable) {
  58624. this.particles.length = 0;
  58625. }
  58626. return mesh;
  58627. };
  58628. /**
  58629. * Digests the mesh and generates as many solid particles in the system as wanted. Returns the SPS.
  58630. * These particles will have the same geometry than the mesh parts and will be positioned at the same localisation than the mesh original places.
  58631. * Thus the particles generated from `digest()` have their property `position` set yet.
  58632. * @param mesh ( Mesh ) is the mesh to be digested
  58633. * @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
  58634. * {delta} (optional integer, default 0) is the random extra number of facets per particle , each particle will have between `facetNb` and `facetNb + delta` facets
  58635. * {number} (optional positive integer) is the wanted number of particles : each particle is built with `mesh_total_facets / number` facets
  58636. * @returns the current SPS
  58637. */
  58638. SolidParticleSystem.prototype.digest = function (mesh, options) {
  58639. var size = (options && options.facetNb) || 1;
  58640. var number = (options && options.number) || 0;
  58641. var delta = (options && options.delta) || 0;
  58642. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  58643. var meshInd = mesh.getIndices();
  58644. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  58645. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  58646. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  58647. var f = 0; // facet counter
  58648. var totalFacets = meshInd.length / 3; // a facet is a triangle, so 3 indices
  58649. // compute size from number
  58650. if (number) {
  58651. number = (number > totalFacets) ? totalFacets : number;
  58652. size = Math.round(totalFacets / number);
  58653. delta = 0;
  58654. }
  58655. else {
  58656. size = (size > totalFacets) ? totalFacets : size;
  58657. }
  58658. var facetPos = []; // submesh positions
  58659. var facetInd = []; // submesh indices
  58660. var facetUV = []; // submesh UV
  58661. var facetCol = []; // submesh colors
  58662. var barycenter = BABYLON.Vector3.Zero();
  58663. var sizeO = size;
  58664. while (f < totalFacets) {
  58665. size = sizeO + Math.floor((1 + delta) * Math.random());
  58666. if (f > totalFacets - size) {
  58667. size = totalFacets - f;
  58668. }
  58669. // reset temp arrays
  58670. facetPos.length = 0;
  58671. facetInd.length = 0;
  58672. facetUV.length = 0;
  58673. facetCol.length = 0;
  58674. // iterate over "size" facets
  58675. var fi = 0;
  58676. for (var j = f * 3; j < (f + size) * 3; j++) {
  58677. facetInd.push(fi);
  58678. var i = meshInd[j];
  58679. facetPos.push(meshPos[i * 3], meshPos[i * 3 + 1], meshPos[i * 3 + 2]);
  58680. if (meshUV) {
  58681. facetUV.push(meshUV[i * 2], meshUV[i * 2 + 1]);
  58682. }
  58683. if (meshCol) {
  58684. facetCol.push(meshCol[i * 4], meshCol[i * 4 + 1], meshCol[i * 4 + 2], meshCol[i * 4 + 3]);
  58685. }
  58686. fi++;
  58687. }
  58688. // create a model shape for each single particle
  58689. var idx = this.nbParticles;
  58690. var shape = this._posToShape(facetPos);
  58691. var shapeUV = this._uvsToShapeUV(facetUV);
  58692. // compute the barycenter of the shape
  58693. var v;
  58694. for (v = 0; v < shape.length; v++) {
  58695. barycenter.addInPlace(shape[v]);
  58696. }
  58697. barycenter.scaleInPlace(1 / shape.length);
  58698. // shift the shape from its barycenter to the origin
  58699. for (v = 0; v < shape.length; v++) {
  58700. shape[v].subtractInPlace(barycenter);
  58701. }
  58702. var bInfo;
  58703. if (this._particlesIntersect) {
  58704. bInfo = new BABYLON.BoundingInfo(barycenter, barycenter);
  58705. }
  58706. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, size * 3, shapeUV, null, null);
  58707. // add the particle in the SPS
  58708. var currentPos = this._positions.length;
  58709. var currentInd = this._indices.length;
  58710. this._meshBuilder(this._index, shape, this._positions, facetInd, this._indices, facetUV, this._uvs, facetCol, this._colors, meshNor, this._normals, idx, 0, null);
  58711. this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, 0, bInfo);
  58712. // initialize the particle position
  58713. this.particles[this.nbParticles].position.addInPlace(barycenter);
  58714. this._index += shape.length;
  58715. idx++;
  58716. this.nbParticles++;
  58717. this._shapeCounter++;
  58718. f += size;
  58719. }
  58720. return this;
  58721. };
  58722. // unrotate the fixed normals in case the mesh was built with pre-rotated particles, ex : use of positionFunction in addShape()
  58723. SolidParticleSystem.prototype._unrotateFixedNormals = function () {
  58724. var index = 0;
  58725. var idx = 0;
  58726. for (var p = 0; p < this.particles.length; p++) {
  58727. this._particle = this.particles[p];
  58728. this._shape = this._particle._model._shape;
  58729. if (this._particle.rotationQuaternion) {
  58730. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  58731. }
  58732. else {
  58733. this._yaw = this._particle.rotation.y;
  58734. this._pitch = this._particle.rotation.x;
  58735. this._roll = this._particle.rotation.z;
  58736. this._quaternionRotationYPR();
  58737. }
  58738. this._quaternionToRotationMatrix();
  58739. this._rotMatrix.invertToRef(this._invertMatrix);
  58740. for (var pt = 0; pt < this._shape.length; pt++) {
  58741. idx = index + pt * 3;
  58742. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._normals32[idx], this._normals32[idx + 1], this._normals32[idx + 2], this._invertMatrix, this._normal);
  58743. this._fixedNormal32[idx] = this._normal.x;
  58744. this._fixedNormal32[idx + 1] = this._normal.y;
  58745. this._fixedNormal32[idx + 2] = this._normal.z;
  58746. }
  58747. index = idx + 3;
  58748. }
  58749. };
  58750. //reset copy
  58751. SolidParticleSystem.prototype._resetCopy = function () {
  58752. this._copy.position.x = 0;
  58753. this._copy.position.y = 0;
  58754. this._copy.position.z = 0;
  58755. this._copy.rotation.x = 0;
  58756. this._copy.rotation.y = 0;
  58757. this._copy.rotation.z = 0;
  58758. this._copy.rotationQuaternion = null;
  58759. this._copy.scaling.x = 1.0;
  58760. this._copy.scaling.y = 1.0;
  58761. this._copy.scaling.z = 1.0;
  58762. this._copy.uvs.x = 0;
  58763. this._copy.uvs.y = 0;
  58764. this._copy.uvs.z = 1.0;
  58765. this._copy.uvs.w = 1.0;
  58766. this._copy.color = null;
  58767. this._copy.translateFromPivot = false;
  58768. };
  58769. // _meshBuilder : inserts the shape model in the global SPS mesh
  58770. SolidParticleSystem.prototype._meshBuilder = function (p, shape, positions, meshInd, indices, meshUV, uvs, meshCol, colors, meshNor, normals, idx, idxInShape, options) {
  58771. var i;
  58772. var u = 0;
  58773. var c = 0;
  58774. var n = 0;
  58775. this._resetCopy();
  58776. if (options && options.positionFunction) { // call to custom positionFunction
  58777. options.positionFunction(this._copy, idx, idxInShape);
  58778. this._mustUnrotateFixedNormals = true;
  58779. }
  58780. if (this._copy.rotationQuaternion) {
  58781. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  58782. }
  58783. else {
  58784. this._yaw = this._copy.rotation.y;
  58785. this._pitch = this._copy.rotation.x;
  58786. this._roll = this._copy.rotation.z;
  58787. this._quaternionRotationYPR();
  58788. }
  58789. this._quaternionToRotationMatrix();
  58790. this._scaledPivot.x = this._copy.pivot.x * this._copy.scaling.x;
  58791. this._scaledPivot.y = this._copy.pivot.y * this._copy.scaling.y;
  58792. this._scaledPivot.z = this._copy.pivot.z * this._copy.scaling.z;
  58793. if (this._copy.translateFromPivot) {
  58794. this._pivotBackTranslation.copyFromFloats(0.0, 0.0, 0.0);
  58795. }
  58796. else {
  58797. this._pivotBackTranslation.copyFrom(this._scaledPivot);
  58798. }
  58799. for (i = 0; i < shape.length; i++) {
  58800. this._vertex.x = shape[i].x;
  58801. this._vertex.y = shape[i].y;
  58802. this._vertex.z = shape[i].z;
  58803. if (options && options.vertexFunction) {
  58804. options.vertexFunction(this._copy, this._vertex, i);
  58805. }
  58806. this._vertex.x *= this._copy.scaling.x;
  58807. this._vertex.y *= this._copy.scaling.y;
  58808. this._vertex.z *= this._copy.scaling.z;
  58809. this._vertex.x -= this._scaledPivot.x;
  58810. this._vertex.y -= this._scaledPivot.y;
  58811. this._vertex.z -= this._scaledPivot.z;
  58812. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  58813. this._rotated.addInPlace(this._pivotBackTranslation);
  58814. positions.push(this._copy.position.x + this._rotated.x, this._copy.position.y + this._rotated.y, this._copy.position.z + this._rotated.z);
  58815. if (meshUV) {
  58816. uvs.push((this._copy.uvs.z - this._copy.uvs.x) * meshUV[u] + this._copy.uvs.x, (this._copy.uvs.w - this._copy.uvs.y) * meshUV[u + 1] + this._copy.uvs.y);
  58817. u += 2;
  58818. }
  58819. if (this._copy.color) {
  58820. this._color = this._copy.color;
  58821. }
  58822. else if (meshCol && meshCol[c] !== undefined) {
  58823. this._color.r = meshCol[c];
  58824. this._color.g = meshCol[c + 1];
  58825. this._color.b = meshCol[c + 2];
  58826. this._color.a = meshCol[c + 3];
  58827. }
  58828. else {
  58829. this._color.r = 1.0;
  58830. this._color.g = 1.0;
  58831. this._color.b = 1.0;
  58832. this._color.a = 1.0;
  58833. }
  58834. colors.push(this._color.r, this._color.g, this._color.b, this._color.a);
  58835. c += 4;
  58836. if (!this.recomputeNormals && meshNor) {
  58837. this._normal.x = meshNor[n];
  58838. this._normal.y = meshNor[n + 1];
  58839. this._normal.z = meshNor[n + 2];
  58840. BABYLON.Vector3.TransformNormalToRef(this._normal, this._rotMatrix, this._normal);
  58841. normals.push(this._normal.x, this._normal.y, this._normal.z);
  58842. n += 3;
  58843. }
  58844. }
  58845. for (i = 0; i < meshInd.length; i++) {
  58846. var current_ind = p + meshInd[i];
  58847. indices.push(current_ind);
  58848. if (current_ind > 65535) {
  58849. this._needs32Bits = true;
  58850. }
  58851. }
  58852. if (this._pickable) {
  58853. var nbfaces = meshInd.length / 3;
  58854. for (i = 0; i < nbfaces; i++) {
  58855. this.pickedParticles.push({ idx: idx, faceId: i });
  58856. }
  58857. }
  58858. if (this._depthSort) {
  58859. this.depthSortedParticles.push(new BABYLON.DepthSortedParticle());
  58860. }
  58861. return this._copy;
  58862. };
  58863. // returns a shape array from positions array
  58864. SolidParticleSystem.prototype._posToShape = function (positions) {
  58865. var shape = [];
  58866. for (var i = 0; i < positions.length; i += 3) {
  58867. shape.push(new BABYLON.Vector3(positions[i], positions[i + 1], positions[i + 2]));
  58868. }
  58869. return shape;
  58870. };
  58871. // returns a shapeUV array from a Vector4 uvs
  58872. SolidParticleSystem.prototype._uvsToShapeUV = function (uvs) {
  58873. var shapeUV = [];
  58874. if (uvs) {
  58875. for (var i = 0; i < uvs.length; i++)
  58876. shapeUV.push(uvs[i]);
  58877. }
  58878. return shapeUV;
  58879. };
  58880. // adds a new particle object in the particles array
  58881. SolidParticleSystem.prototype._addParticle = function (idx, idxpos, idxind, model, shapeId, idxInShape, bInfo) {
  58882. if (bInfo === void 0) { bInfo = null; }
  58883. var sp = new BABYLON.SolidParticle(idx, idxpos, idxind, model, shapeId, idxInShape, this, bInfo);
  58884. this.particles.push(sp);
  58885. return sp;
  58886. };
  58887. /**
  58888. * Adds some particles to the SPS from the model shape. Returns the shape id.
  58889. * Please read the doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#create-an-immutable-sps
  58890. * @param mesh is any Mesh object that will be used as a model for the solid particles.
  58891. * @param nb (positive integer) the number of particles to be created from this model
  58892. * @param options {positionFunction} is an optional javascript function to called for each particle on SPS creation.
  58893. * {vertexFunction} is an optional javascript function to called for each vertex of each particle on SPS creation
  58894. * @returns the number of shapes in the system
  58895. */
  58896. SolidParticleSystem.prototype.addShape = function (mesh, nb, options) {
  58897. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  58898. var meshInd = mesh.getIndices();
  58899. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  58900. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  58901. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  58902. var bbInfo;
  58903. if (this._particlesIntersect) {
  58904. bbInfo = mesh.getBoundingInfo();
  58905. }
  58906. var shape = this._posToShape(meshPos);
  58907. var shapeUV = this._uvsToShapeUV(meshUV);
  58908. var posfunc = options ? options.positionFunction : null;
  58909. var vtxfunc = options ? options.vertexFunction : null;
  58910. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, meshInd.length, shapeUV, posfunc, vtxfunc);
  58911. // particles
  58912. var sp;
  58913. var currentCopy;
  58914. var idx = this.nbParticles;
  58915. for (var i = 0; i < nb; i++) {
  58916. var currentPos = this._positions.length;
  58917. var currentInd = this._indices.length;
  58918. currentCopy = this._meshBuilder(this._index, shape, this._positions, meshInd, this._indices, meshUV, this._uvs, meshCol, this._colors, meshNor, this._normals, idx, i, options);
  58919. if (this._updatable) {
  58920. sp = this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, i, bbInfo);
  58921. sp.position.copyFrom(currentCopy.position);
  58922. sp.rotation.copyFrom(currentCopy.rotation);
  58923. if (currentCopy.rotationQuaternion && sp.rotationQuaternion) {
  58924. sp.rotationQuaternion.copyFrom(currentCopy.rotationQuaternion);
  58925. }
  58926. if (currentCopy.color && sp.color) {
  58927. sp.color.copyFrom(currentCopy.color);
  58928. }
  58929. sp.scaling.copyFrom(currentCopy.scaling);
  58930. sp.uvs.copyFrom(currentCopy.uvs);
  58931. }
  58932. this._index += shape.length;
  58933. idx++;
  58934. }
  58935. this.nbParticles += nb;
  58936. this._shapeCounter++;
  58937. return this._shapeCounter - 1;
  58938. };
  58939. // rebuilds a particle back to its just built status : if needed, recomputes the custom positions and vertices
  58940. SolidParticleSystem.prototype._rebuildParticle = function (particle) {
  58941. this._resetCopy();
  58942. if (particle._model._positionFunction) { // recall to stored custom positionFunction
  58943. particle._model._positionFunction(this._copy, particle.idx, particle.idxInShape);
  58944. }
  58945. if (this._copy.rotationQuaternion) {
  58946. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  58947. }
  58948. else {
  58949. this._yaw = this._copy.rotation.y;
  58950. this._pitch = this._copy.rotation.x;
  58951. this._roll = this._copy.rotation.z;
  58952. this._quaternionRotationYPR();
  58953. }
  58954. this._quaternionToRotationMatrix();
  58955. this._scaledPivot.x = this._particle.pivot.x * this._particle.scaling.x;
  58956. this._scaledPivot.y = this._particle.pivot.y * this._particle.scaling.y;
  58957. this._scaledPivot.z = this._particle.pivot.z * this._particle.scaling.z;
  58958. if (this._copy.translateFromPivot) {
  58959. this._pivotBackTranslation.copyFromFloats(0.0, 0.0, 0.0);
  58960. }
  58961. else {
  58962. this._pivotBackTranslation.copyFrom(this._scaledPivot);
  58963. }
  58964. this._shape = particle._model._shape;
  58965. for (var pt = 0; pt < this._shape.length; pt++) {
  58966. this._vertex.x = this._shape[pt].x;
  58967. this._vertex.y = this._shape[pt].y;
  58968. this._vertex.z = this._shape[pt].z;
  58969. if (particle._model._vertexFunction) {
  58970. particle._model._vertexFunction(this._copy, this._vertex, pt); // recall to stored vertexFunction
  58971. }
  58972. this._vertex.x *= this._copy.scaling.x;
  58973. this._vertex.y *= this._copy.scaling.y;
  58974. this._vertex.z *= this._copy.scaling.z;
  58975. this._vertex.x -= this._scaledPivot.x;
  58976. this._vertex.y -= this._scaledPivot.y;
  58977. this._vertex.z -= this._scaledPivot.z;
  58978. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  58979. this._rotated.addInPlace(this._pivotBackTranslation);
  58980. this._positions32[particle._pos + pt * 3] = this._copy.position.x + this._rotated.x;
  58981. this._positions32[particle._pos + pt * 3 + 1] = this._copy.position.y + this._rotated.y;
  58982. this._positions32[particle._pos + pt * 3 + 2] = this._copy.position.z + this._rotated.z;
  58983. }
  58984. particle.position.x = 0.0;
  58985. particle.position.y = 0.0;
  58986. particle.position.z = 0.0;
  58987. particle.rotation.x = 0.0;
  58988. particle.rotation.y = 0.0;
  58989. particle.rotation.z = 0.0;
  58990. particle.rotationQuaternion = null;
  58991. particle.scaling.x = 1.0;
  58992. particle.scaling.y = 1.0;
  58993. particle.scaling.z = 1.0;
  58994. particle.uvs.x = 0.0;
  58995. particle.uvs.y = 0.0;
  58996. particle.uvs.z = 1.0;
  58997. particle.uvs.w = 1.0;
  58998. particle.pivot.x = 0.0;
  58999. particle.pivot.y = 0.0;
  59000. particle.pivot.z = 0.0;
  59001. particle.translateFromPivot = false;
  59002. particle.parentId = null;
  59003. };
  59004. /**
  59005. * Rebuilds the whole mesh and updates the VBO : custom positions and vertices are recomputed if needed.
  59006. * @returns the SPS.
  59007. */
  59008. SolidParticleSystem.prototype.rebuildMesh = function () {
  59009. for (var p = 0; p < this.particles.length; p++) {
  59010. this._rebuildParticle(this.particles[p]);
  59011. }
  59012. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  59013. return this;
  59014. };
  59015. /**
  59016. * Sets all the particles : this method actually really updates the mesh according to the particle positions, rotations, colors, textures, etc.
  59017. * This method calls `updateParticle()` for each particle of the SPS.
  59018. * For an animated SPS, it is usually called within the render loop.
  59019. * @param start The particle index in the particle array where to start to compute the particle property values _(default 0)_
  59020. * @param end The particle index in the particle array where to stop to compute the particle property values _(default nbParticle - 1)_
  59021. * @param update If the mesh must be finally updated on this call after all the particle computations _(default true)_
  59022. * @returns the SPS.
  59023. */
  59024. SolidParticleSystem.prototype.setParticles = function (start, end, update) {
  59025. if (start === void 0) { start = 0; }
  59026. if (end === void 0) { end = this.nbParticles - 1; }
  59027. if (update === void 0) { update = true; }
  59028. if (!this._updatable) {
  59029. return this;
  59030. }
  59031. // custom beforeUpdate
  59032. this.beforeUpdateParticles(start, end, update);
  59033. this._cam_axisX.x = 1.0;
  59034. this._cam_axisX.y = 0.0;
  59035. this._cam_axisX.z = 0.0;
  59036. this._cam_axisY.x = 0.0;
  59037. this._cam_axisY.y = 1.0;
  59038. this._cam_axisY.z = 0.0;
  59039. this._cam_axisZ.x = 0.0;
  59040. this._cam_axisZ.y = 0.0;
  59041. this._cam_axisZ.z = 1.0;
  59042. // cases when the World Matrix is to be computed first
  59043. if (this.billboard || this._depthSort) {
  59044. this.mesh.computeWorldMatrix(true);
  59045. this.mesh._worldMatrix.invertToRef(this._invertMatrix);
  59046. }
  59047. // if the particles will always face the camera
  59048. if (this.billboard) {
  59049. // compute the camera position and un-rotate it by the current mesh rotation
  59050. this._camera.getDirectionToRef(this._axisZ, this._camDir);
  59051. BABYLON.Vector3.TransformNormalToRef(this._camDir, this._invertMatrix, this._cam_axisZ);
  59052. this._cam_axisZ.normalize();
  59053. // same for camera up vector extracted from the cam view matrix
  59054. var view = this._camera.getViewMatrix(true);
  59055. BABYLON.Vector3.TransformNormalFromFloatsToRef(view.m[1], view.m[5], view.m[9], this._invertMatrix, this._cam_axisY);
  59056. BABYLON.Vector3.CrossToRef(this._cam_axisY, this._cam_axisZ, this._cam_axisX);
  59057. this._cam_axisY.normalize();
  59058. this._cam_axisX.normalize();
  59059. }
  59060. // if depthSort, compute the camera global position in the mesh local system
  59061. if (this._depthSort) {
  59062. BABYLON.Vector3.TransformCoordinatesToRef(this._camera.globalPosition, this._invertMatrix, this._camInvertedPosition); // then un-rotate the camera
  59063. }
  59064. BABYLON.Matrix.IdentityToRef(this._rotMatrix);
  59065. var idx = 0; // current position index in the global array positions32
  59066. var index = 0; // position start index in the global array positions32 of the current particle
  59067. var colidx = 0; // current color index in the global array colors32
  59068. var colorIndex = 0; // color start index in the global array colors32 of the current particle
  59069. var uvidx = 0; // current uv index in the global array uvs32
  59070. var uvIndex = 0; // uv start index in the global array uvs32 of the current particle
  59071. var pt = 0; // current index in the particle model shape
  59072. if (this.mesh.isFacetDataEnabled) {
  59073. this._computeBoundingBox = true;
  59074. }
  59075. end = (end >= this.nbParticles) ? this.nbParticles - 1 : end;
  59076. if (this._computeBoundingBox) {
  59077. if (start == 0 && end == this.nbParticles - 1) { // all the particles are updated, then recompute the BBox from scratch
  59078. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this._minimum);
  59079. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this._maximum);
  59080. }
  59081. else { // only some particles are updated, then use the current existing BBox basis. Note : it can only increase.
  59082. if (this.mesh._boundingInfo) {
  59083. this._minimum.copyFrom(this.mesh._boundingInfo.boundingBox.minimum);
  59084. this._maximum.copyFrom(this.mesh._boundingInfo.boundingBox.maximum);
  59085. }
  59086. }
  59087. }
  59088. // particle loop
  59089. index = this.particles[start]._pos;
  59090. var vpos = (index / 3) | 0;
  59091. colorIndex = vpos * 4;
  59092. uvIndex = vpos * 2;
  59093. for (var p = start; p <= end; p++) {
  59094. this._particle = this.particles[p];
  59095. this._shape = this._particle._model._shape;
  59096. this._shapeUV = this._particle._model._shapeUV;
  59097. // call to custom user function to update the particle properties
  59098. this.updateParticle(this._particle);
  59099. // camera-particle distance for depth sorting
  59100. if (this._depthSort && this._depthSortParticles) {
  59101. var dsp = this.depthSortedParticles[p];
  59102. dsp.ind = this._particle._ind;
  59103. dsp.indicesLength = this._particle._model._indicesLength;
  59104. dsp.sqDistance = BABYLON.Vector3.DistanceSquared(this._particle.position, this._camInvertedPosition);
  59105. }
  59106. // skip the computations for inactive or already invisible particles
  59107. if (!this._particle.alive || (this._particle._stillInvisible && !this._particle.isVisible)) {
  59108. // increment indexes for the next particle
  59109. pt = this._shape.length;
  59110. index += pt * 3;
  59111. colorIndex += pt * 4;
  59112. uvIndex += pt * 2;
  59113. continue;
  59114. }
  59115. if (this._particle.isVisible) {
  59116. this._particle._stillInvisible = false; // un-mark permanent invisibility
  59117. this._particleHasParent = (this._particle.parentId !== null);
  59118. this._scaledPivot.x = this._particle.pivot.x * this._particle.scaling.x;
  59119. this._scaledPivot.y = this._particle.pivot.y * this._particle.scaling.y;
  59120. this._scaledPivot.z = this._particle.pivot.z * this._particle.scaling.z;
  59121. // particle rotation matrix
  59122. if (this.billboard) {
  59123. this._particle.rotation.x = 0.0;
  59124. this._particle.rotation.y = 0.0;
  59125. }
  59126. if (this._computeParticleRotation || this.billboard) {
  59127. if (this._particle.rotationQuaternion) {
  59128. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  59129. }
  59130. else {
  59131. this._yaw = this._particle.rotation.y;
  59132. this._pitch = this._particle.rotation.x;
  59133. this._roll = this._particle.rotation.z;
  59134. this._quaternionRotationYPR();
  59135. }
  59136. this._quaternionToRotationMatrix();
  59137. }
  59138. if (this._particleHasParent) {
  59139. this._parent = this.particles[this._particle.parentId];
  59140. this._rotated.x = this._particle.position.x * this._parent._rotationMatrix[0] + this._particle.position.y * this._parent._rotationMatrix[3] + this._particle.position.z * this._parent._rotationMatrix[6];
  59141. this._rotated.y = this._particle.position.x * this._parent._rotationMatrix[1] + this._particle.position.y * this._parent._rotationMatrix[4] + this._particle.position.z * this._parent._rotationMatrix[7];
  59142. this._rotated.z = this._particle.position.x * this._parent._rotationMatrix[2] + this._particle.position.y * this._parent._rotationMatrix[5] + this._particle.position.z * this._parent._rotationMatrix[8];
  59143. this._particle._globalPosition.x = this._parent._globalPosition.x + this._rotated.x;
  59144. this._particle._globalPosition.y = this._parent._globalPosition.y + this._rotated.y;
  59145. this._particle._globalPosition.z = this._parent._globalPosition.z + this._rotated.z;
  59146. if (this._computeParticleRotation || this.billboard) {
  59147. this._particle._rotationMatrix[0] = this._rotMatrix.m[0] * this._parent._rotationMatrix[0] + this._rotMatrix.m[1] * this._parent._rotationMatrix[3] + this._rotMatrix.m[2] * this._parent._rotationMatrix[6];
  59148. this._particle._rotationMatrix[1] = this._rotMatrix.m[0] * this._parent._rotationMatrix[1] + this._rotMatrix.m[1] * this._parent._rotationMatrix[4] + this._rotMatrix.m[2] * this._parent._rotationMatrix[7];
  59149. this._particle._rotationMatrix[2] = this._rotMatrix.m[0] * this._parent._rotationMatrix[2] + this._rotMatrix.m[1] * this._parent._rotationMatrix[5] + this._rotMatrix.m[2] * this._parent._rotationMatrix[8];
  59150. this._particle._rotationMatrix[3] = this._rotMatrix.m[4] * this._parent._rotationMatrix[0] + this._rotMatrix.m[5] * this._parent._rotationMatrix[3] + this._rotMatrix.m[6] * this._parent._rotationMatrix[6];
  59151. this._particle._rotationMatrix[4] = this._rotMatrix.m[4] * this._parent._rotationMatrix[1] + this._rotMatrix.m[5] * this._parent._rotationMatrix[4] + this._rotMatrix.m[6] * this._parent._rotationMatrix[7];
  59152. this._particle._rotationMatrix[5] = this._rotMatrix.m[4] * this._parent._rotationMatrix[2] + this._rotMatrix.m[5] * this._parent._rotationMatrix[5] + this._rotMatrix.m[6] * this._parent._rotationMatrix[8];
  59153. this._particle._rotationMatrix[6] = this._rotMatrix.m[8] * this._parent._rotationMatrix[0] + this._rotMatrix.m[9] * this._parent._rotationMatrix[3] + this._rotMatrix.m[10] * this._parent._rotationMatrix[6];
  59154. this._particle._rotationMatrix[7] = this._rotMatrix.m[8] * this._parent._rotationMatrix[1] + this._rotMatrix.m[9] * this._parent._rotationMatrix[4] + this._rotMatrix.m[10] * this._parent._rotationMatrix[7];
  59155. this._particle._rotationMatrix[8] = this._rotMatrix.m[8] * this._parent._rotationMatrix[2] + this._rotMatrix.m[9] * this._parent._rotationMatrix[5] + this._rotMatrix.m[10] * this._parent._rotationMatrix[8];
  59156. }
  59157. }
  59158. else {
  59159. this._particle._globalPosition.x = this._particle.position.x;
  59160. this._particle._globalPosition.y = this._particle.position.y;
  59161. this._particle._globalPosition.z = this._particle.position.z;
  59162. if (this._computeParticleRotation || this.billboard) {
  59163. this._particle._rotationMatrix[0] = this._rotMatrix.m[0];
  59164. this._particle._rotationMatrix[1] = this._rotMatrix.m[1];
  59165. this._particle._rotationMatrix[2] = this._rotMatrix.m[2];
  59166. this._particle._rotationMatrix[3] = this._rotMatrix.m[4];
  59167. this._particle._rotationMatrix[4] = this._rotMatrix.m[5];
  59168. this._particle._rotationMatrix[5] = this._rotMatrix.m[6];
  59169. this._particle._rotationMatrix[6] = this._rotMatrix.m[8];
  59170. this._particle._rotationMatrix[7] = this._rotMatrix.m[9];
  59171. this._particle._rotationMatrix[8] = this._rotMatrix.m[10];
  59172. }
  59173. }
  59174. if (this._particle.translateFromPivot) {
  59175. this._pivotBackTranslation.x = 0.0;
  59176. this._pivotBackTranslation.y = 0.0;
  59177. this._pivotBackTranslation.z = 0.0;
  59178. }
  59179. else {
  59180. this._pivotBackTranslation.x = this._scaledPivot.x;
  59181. this._pivotBackTranslation.y = this._scaledPivot.y;
  59182. this._pivotBackTranslation.z = this._scaledPivot.z;
  59183. }
  59184. // particle vertex loop
  59185. for (pt = 0; pt < this._shape.length; pt++) {
  59186. idx = index + pt * 3;
  59187. colidx = colorIndex + pt * 4;
  59188. uvidx = uvIndex + pt * 2;
  59189. this._vertex.x = this._shape[pt].x;
  59190. this._vertex.y = this._shape[pt].y;
  59191. this._vertex.z = this._shape[pt].z;
  59192. if (this._computeParticleVertex) {
  59193. this.updateParticleVertex(this._particle, this._vertex, pt);
  59194. }
  59195. // positions
  59196. this._vertex.x *= this._particle.scaling.x;
  59197. this._vertex.y *= this._particle.scaling.y;
  59198. this._vertex.z *= this._particle.scaling.z;
  59199. this._vertex.x -= this._scaledPivot.x;
  59200. this._vertex.y -= this._scaledPivot.y;
  59201. this._vertex.z -= this._scaledPivot.z;
  59202. this._rotated.x = this._vertex.x * this._particle._rotationMatrix[0] + this._vertex.y * this._particle._rotationMatrix[3] + this._vertex.z * this._particle._rotationMatrix[6];
  59203. this._rotated.y = this._vertex.x * this._particle._rotationMatrix[1] + this._vertex.y * this._particle._rotationMatrix[4] + this._vertex.z * this._particle._rotationMatrix[7];
  59204. this._rotated.z = this._vertex.x * this._particle._rotationMatrix[2] + this._vertex.y * this._particle._rotationMatrix[5] + this._vertex.z * this._particle._rotationMatrix[8];
  59205. this._rotated.x += this._pivotBackTranslation.x;
  59206. this._rotated.y += this._pivotBackTranslation.y;
  59207. this._rotated.z += this._pivotBackTranslation.z;
  59208. this._positions32[idx] = this._particle._globalPosition.x + this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  59209. this._positions32[idx + 1] = this._particle._globalPosition.y + this._cam_axisX.y * this._rotated.x + this._cam_axisY.y * this._rotated.y + this._cam_axisZ.y * this._rotated.z;
  59210. this._positions32[idx + 2] = this._particle._globalPosition.z + this._cam_axisX.z * this._rotated.x + this._cam_axisY.z * this._rotated.y + this._cam_axisZ.z * this._rotated.z;
  59211. if (this._computeBoundingBox) {
  59212. if (this._positions32[idx] < this._minimum.x) {
  59213. this._minimum.x = this._positions32[idx];
  59214. }
  59215. if (this._positions32[idx] > this._maximum.x) {
  59216. this._maximum.x = this._positions32[idx];
  59217. }
  59218. if (this._positions32[idx + 1] < this._minimum.y) {
  59219. this._minimum.y = this._positions32[idx + 1];
  59220. }
  59221. if (this._positions32[idx + 1] > this._maximum.y) {
  59222. this._maximum.y = this._positions32[idx + 1];
  59223. }
  59224. if (this._positions32[idx + 2] < this._minimum.z) {
  59225. this._minimum.z = this._positions32[idx + 2];
  59226. }
  59227. if (this._positions32[idx + 2] > this._maximum.z) {
  59228. this._maximum.z = this._positions32[idx + 2];
  59229. }
  59230. }
  59231. // normals : if the particles can't be morphed then just rotate the normals, what is much more faster than ComputeNormals()
  59232. if (!this._computeParticleVertex) {
  59233. this._normal.x = this._fixedNormal32[idx];
  59234. this._normal.y = this._fixedNormal32[idx + 1];
  59235. this._normal.z = this._fixedNormal32[idx + 2];
  59236. this._rotated.x = this._normal.x * this._particle._rotationMatrix[0] + this._normal.y * this._particle._rotationMatrix[3] + this._normal.z * this._particle._rotationMatrix[6];
  59237. this._rotated.y = this._normal.x * this._particle._rotationMatrix[1] + this._normal.y * this._particle._rotationMatrix[4] + this._normal.z * this._particle._rotationMatrix[7];
  59238. this._rotated.z = this._normal.x * this._particle._rotationMatrix[2] + this._normal.y * this._particle._rotationMatrix[5] + this._normal.z * this._particle._rotationMatrix[8];
  59239. this._normals32[idx] = this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  59240. this._normals32[idx + 1] = this._cam_axisX.y * this._rotated.x + this._cam_axisY.y * this._rotated.y + this._cam_axisZ.y * this._rotated.z;
  59241. this._normals32[idx + 2] = this._cam_axisX.z * this._rotated.x + this._cam_axisY.z * this._rotated.y + this._cam_axisZ.z * this._rotated.z;
  59242. }
  59243. if (this._computeParticleColor && this._particle.color) {
  59244. this._colors32[colidx] = this._particle.color.r;
  59245. this._colors32[colidx + 1] = this._particle.color.g;
  59246. this._colors32[colidx + 2] = this._particle.color.b;
  59247. this._colors32[colidx + 3] = this._particle.color.a;
  59248. }
  59249. if (this._computeParticleTexture) {
  59250. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  59251. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  59252. }
  59253. }
  59254. }
  59255. // particle just set invisible : scaled to zero and positioned at the origin
  59256. else {
  59257. this._particle._stillInvisible = true; // mark the particle as invisible
  59258. for (pt = 0; pt < this._shape.length; pt++) {
  59259. idx = index + pt * 3;
  59260. colidx = colorIndex + pt * 4;
  59261. uvidx = uvIndex + pt * 2;
  59262. this._positions32[idx] = 0.0;
  59263. this._positions32[idx + 1] = 0.0;
  59264. this._positions32[idx + 2] = 0.0;
  59265. this._normals32[idx] = 0.0;
  59266. this._normals32[idx + 1] = 0.0;
  59267. this._normals32[idx + 2] = 0.0;
  59268. if (this._computeParticleColor && this._particle.color) {
  59269. this._colors32[colidx] = this._particle.color.r;
  59270. this._colors32[colidx + 1] = this._particle.color.g;
  59271. this._colors32[colidx + 2] = this._particle.color.b;
  59272. this._colors32[colidx + 3] = this._particle.color.a;
  59273. }
  59274. if (this._computeParticleTexture) {
  59275. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  59276. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  59277. }
  59278. }
  59279. }
  59280. // if the particle intersections must be computed : update the bbInfo
  59281. if (this._particlesIntersect) {
  59282. var bInfo = this._particle._boundingInfo;
  59283. var bBox = bInfo.boundingBox;
  59284. var bSphere = bInfo.boundingSphere;
  59285. if (!this._bSphereOnly) {
  59286. // place, scale and rotate the particle bbox within the SPS local system, then update it
  59287. for (var b = 0; b < bBox.vectors.length; b++) {
  59288. this._vertex.x = this._particle._modelBoundingInfo.boundingBox.vectors[b].x * this._particle.scaling.x;
  59289. this._vertex.y = this._particle._modelBoundingInfo.boundingBox.vectors[b].y * this._particle.scaling.y;
  59290. this._vertex.z = this._particle._modelBoundingInfo.boundingBox.vectors[b].z * this._particle.scaling.z;
  59291. this._rotated.x = this._vertex.x * this._particle._rotationMatrix[0] + this._vertex.y * this._particle._rotationMatrix[3] + this._vertex.z * this._particle._rotationMatrix[6];
  59292. this._rotated.y = this._vertex.x * this._particle._rotationMatrix[1] + this._vertex.y * this._particle._rotationMatrix[4] + this._vertex.z * this._particle._rotationMatrix[7];
  59293. this._rotated.z = this._vertex.x * this._particle._rotationMatrix[2] + this._vertex.y * this._particle._rotationMatrix[5] + this._vertex.z * this._particle._rotationMatrix[8];
  59294. bBox.vectors[b].x = this._particle.position.x + this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  59295. bBox.vectors[b].y = this._particle.position.y + this._cam_axisX.y * this._rotated.x + this._cam_axisY.y * this._rotated.y + this._cam_axisZ.y * this._rotated.z;
  59296. bBox.vectors[b].z = this._particle.position.z + this._cam_axisX.z * this._rotated.x + this._cam_axisY.z * this._rotated.y + this._cam_axisZ.z * this._rotated.z;
  59297. }
  59298. bBox._update(this.mesh._worldMatrix);
  59299. }
  59300. // place and scale the particle bouding sphere in the SPS local system, then update it
  59301. this._minBbox.x = this._particle._modelBoundingInfo.minimum.x * this._particle.scaling.x;
  59302. this._minBbox.y = this._particle._modelBoundingInfo.minimum.y * this._particle.scaling.y;
  59303. this._minBbox.z = this._particle._modelBoundingInfo.minimum.z * this._particle.scaling.z;
  59304. this._maxBbox.x = this._particle._modelBoundingInfo.maximum.x * this._particle.scaling.x;
  59305. this._maxBbox.y = this._particle._modelBoundingInfo.maximum.y * this._particle.scaling.y;
  59306. this._maxBbox.z = this._particle._modelBoundingInfo.maximum.z * this._particle.scaling.z;
  59307. bSphere.center.x = this._particle._globalPosition.x + (this._minBbox.x + this._maxBbox.x) * 0.5;
  59308. bSphere.center.y = this._particle._globalPosition.y + (this._minBbox.y + this._maxBbox.y) * 0.5;
  59309. bSphere.center.z = this._particle._globalPosition.z + (this._minBbox.z + this._maxBbox.z) * 0.5;
  59310. bSphere.radius = this._bSphereRadiusFactor * 0.5 * Math.sqrt((this._maxBbox.x - this._minBbox.x) * (this._maxBbox.x - this._minBbox.x) + (this._maxBbox.y - this._minBbox.y) * (this._maxBbox.y - this._minBbox.y) + (this._maxBbox.z - this._minBbox.z) * (this._maxBbox.z - this._minBbox.z));
  59311. bSphere._update(this.mesh._worldMatrix);
  59312. }
  59313. // increment indexes for the next particle
  59314. index = idx + 3;
  59315. colorIndex = colidx + 4;
  59316. uvIndex = uvidx + 2;
  59317. }
  59318. // if the VBO must be updated
  59319. if (update) {
  59320. if (this._computeParticleColor) {
  59321. this.mesh.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this._colors32, false, false);
  59322. }
  59323. if (this._computeParticleTexture) {
  59324. this.mesh.updateVerticesData(BABYLON.VertexBuffer.UVKind, this._uvs32, false, false);
  59325. }
  59326. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  59327. if (!this.mesh.areNormalsFrozen || this.mesh.isFacetDataEnabled) {
  59328. if (this._computeParticleVertex || this.mesh.isFacetDataEnabled) {
  59329. // recompute the normals only if the particles can be morphed, update then also the normal reference array _fixedNormal32[]
  59330. var params = this.mesh.isFacetDataEnabled ? this.mesh.getFacetDataParameters() : null;
  59331. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals32, params);
  59332. for (var i = 0; i < this._normals32.length; i++) {
  59333. this._fixedNormal32[i] = this._normals32[i];
  59334. }
  59335. }
  59336. if (!this.mesh.areNormalsFrozen) {
  59337. this.mesh.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this._normals32, false, false);
  59338. }
  59339. }
  59340. if (this._depthSort && this._depthSortParticles) {
  59341. this.depthSortedParticles.sort(this._depthSortFunction);
  59342. var dspl = this.depthSortedParticles.length;
  59343. var sorted = 0;
  59344. var lind = 0;
  59345. var sind = 0;
  59346. var sid = 0;
  59347. for (sorted = 0; sorted < dspl; sorted++) {
  59348. lind = this.depthSortedParticles[sorted].indicesLength;
  59349. sind = this.depthSortedParticles[sorted].ind;
  59350. for (var i = 0; i < lind; i++) {
  59351. this._indices32[sid] = this._indices[sind + i];
  59352. sid++;
  59353. }
  59354. }
  59355. this.mesh.updateIndices(this._indices32);
  59356. }
  59357. }
  59358. if (this._computeBoundingBox) {
  59359. this.mesh._boundingInfo = new BABYLON.BoundingInfo(this._minimum, this._maximum);
  59360. this.mesh._boundingInfo.update(this.mesh._worldMatrix);
  59361. }
  59362. this.afterUpdateParticles(start, end, update);
  59363. return this;
  59364. };
  59365. SolidParticleSystem.prototype._quaternionRotationYPR = function () {
  59366. this._halfroll = this._roll * 0.5;
  59367. this._halfpitch = this._pitch * 0.5;
  59368. this._halfyaw = this._yaw * 0.5;
  59369. this._sinRoll = Math.sin(this._halfroll);
  59370. this._cosRoll = Math.cos(this._halfroll);
  59371. this._sinPitch = Math.sin(this._halfpitch);
  59372. this._cosPitch = Math.cos(this._halfpitch);
  59373. this._sinYaw = Math.sin(this._halfyaw);
  59374. this._cosYaw = Math.cos(this._halfyaw);
  59375. this._quaternion.x = this._cosYaw * this._sinPitch * this._cosRoll + this._sinYaw * this._cosPitch * this._sinRoll;
  59376. this._quaternion.y = this._sinYaw * this._cosPitch * this._cosRoll - this._cosYaw * this._sinPitch * this._sinRoll;
  59377. this._quaternion.z = this._cosYaw * this._cosPitch * this._sinRoll - this._sinYaw * this._sinPitch * this._cosRoll;
  59378. this._quaternion.w = this._cosYaw * this._cosPitch * this._cosRoll + this._sinYaw * this._sinPitch * this._sinRoll;
  59379. };
  59380. SolidParticleSystem.prototype._quaternionToRotationMatrix = function () {
  59381. this._rotMatrix.m[0] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.z * this._quaternion.z));
  59382. this._rotMatrix.m[1] = 2.0 * (this._quaternion.x * this._quaternion.y + this._quaternion.z * this._quaternion.w);
  59383. this._rotMatrix.m[2] = 2.0 * (this._quaternion.z * this._quaternion.x - this._quaternion.y * this._quaternion.w);
  59384. this._rotMatrix.m[3] = 0;
  59385. this._rotMatrix.m[4] = 2.0 * (this._quaternion.x * this._quaternion.y - this._quaternion.z * this._quaternion.w);
  59386. this._rotMatrix.m[5] = 1.0 - (2.0 * (this._quaternion.z * this._quaternion.z + this._quaternion.x * this._quaternion.x));
  59387. this._rotMatrix.m[6] = 2.0 * (this._quaternion.y * this._quaternion.z + this._quaternion.x * this._quaternion.w);
  59388. this._rotMatrix.m[7] = 0;
  59389. this._rotMatrix.m[8] = 2.0 * (this._quaternion.z * this._quaternion.x + this._quaternion.y * this._quaternion.w);
  59390. this._rotMatrix.m[9] = 2.0 * (this._quaternion.y * this._quaternion.z - this._quaternion.x * this._quaternion.w);
  59391. this._rotMatrix.m[10] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.x * this._quaternion.x));
  59392. this._rotMatrix.m[11] = 0;
  59393. this._rotMatrix.m[12] = 0;
  59394. this._rotMatrix.m[13] = 0;
  59395. this._rotMatrix.m[14] = 0;
  59396. this._rotMatrix.m[15] = 1.0;
  59397. };
  59398. /**
  59399. * Disposes the SPS.
  59400. */
  59401. SolidParticleSystem.prototype.dispose = function () {
  59402. this.mesh.dispose();
  59403. this.vars = null;
  59404. // drop references to internal big arrays for the GC
  59405. this._positions = null;
  59406. this._indices = null;
  59407. this._normals = null;
  59408. this._uvs = null;
  59409. this._colors = null;
  59410. this._indices32 = null;
  59411. this._positions32 = null;
  59412. this._normals32 = null;
  59413. this._fixedNormal32 = null;
  59414. this._uvs32 = null;
  59415. this._colors32 = null;
  59416. this.pickedParticles = null;
  59417. };
  59418. /**
  59419. * Visibilty helper : Recomputes the visible size according to the mesh bounding box
  59420. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  59421. * @returns the SPS.
  59422. */
  59423. SolidParticleSystem.prototype.refreshVisibleSize = function () {
  59424. if (!this._isVisibilityBoxLocked) {
  59425. this.mesh.refreshBoundingInfo();
  59426. }
  59427. return this;
  59428. };
  59429. /**
  59430. * Visibility helper : Sets the size of a visibility box, this sets the underlying mesh bounding box.
  59431. * @param size the size (float) of the visibility box
  59432. * note : this doesn't lock the SPS mesh bounding box.
  59433. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  59434. */
  59435. SolidParticleSystem.prototype.setVisibilityBox = function (size) {
  59436. var vis = size / 2;
  59437. this.mesh._boundingInfo = new BABYLON.BoundingInfo(new BABYLON.Vector3(-vis, -vis, -vis), new BABYLON.Vector3(vis, vis, vis));
  59438. };
  59439. Object.defineProperty(SolidParticleSystem.prototype, "isAlwaysVisible", {
  59440. /**
  59441. * Gets whether the SPS as always visible or not
  59442. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  59443. */
  59444. get: function () {
  59445. return this._alwaysVisible;
  59446. },
  59447. /**
  59448. * Sets the SPS as always visible or not
  59449. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  59450. */
  59451. set: function (val) {
  59452. this._alwaysVisible = val;
  59453. this.mesh.alwaysSelectAsActiveMesh = val;
  59454. },
  59455. enumerable: true,
  59456. configurable: true
  59457. });
  59458. Object.defineProperty(SolidParticleSystem.prototype, "isVisibilityBoxLocked", {
  59459. /**
  59460. * Gets if the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  59461. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  59462. */
  59463. get: function () {
  59464. return this._isVisibilityBoxLocked;
  59465. },
  59466. /**
  59467. * Sets the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  59468. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  59469. */
  59470. set: function (val) {
  59471. this._isVisibilityBoxLocked = val;
  59472. var boundingInfo = this.mesh.getBoundingInfo();
  59473. boundingInfo.isLocked = val;
  59474. },
  59475. enumerable: true,
  59476. configurable: true
  59477. });
  59478. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleRotation", {
  59479. /**
  59480. * Gets if `setParticles()` computes the particle rotations or not.
  59481. * Default value : true. The SPS is faster when it's set to false.
  59482. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  59483. */
  59484. get: function () {
  59485. return this._computeParticleRotation;
  59486. },
  59487. /**
  59488. * Tells to `setParticles()` to compute the particle rotations or not.
  59489. * Default value : true. The SPS is faster when it's set to false.
  59490. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  59491. */
  59492. set: function (val) {
  59493. this._computeParticleRotation = val;
  59494. },
  59495. enumerable: true,
  59496. configurable: true
  59497. });
  59498. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleColor", {
  59499. /**
  59500. * Gets if `setParticles()` computes the particle colors or not.
  59501. * Default value : true. The SPS is faster when it's set to false.
  59502. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  59503. */
  59504. get: function () {
  59505. return this._computeParticleColor;
  59506. },
  59507. /**
  59508. * Tells to `setParticles()` to compute the particle colors or not.
  59509. * Default value : true. The SPS is faster when it's set to false.
  59510. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  59511. */
  59512. set: function (val) {
  59513. this._computeParticleColor = val;
  59514. },
  59515. enumerable: true,
  59516. configurable: true
  59517. });
  59518. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleTexture", {
  59519. /**
  59520. * Gets if `setParticles()` computes the particle textures or not.
  59521. * Default value : true. The SPS is faster when it's set to false.
  59522. * Note : the particle textures are stored values, so setting `computeParticleTexture` to false will keep yet the last colors set.
  59523. */
  59524. get: function () {
  59525. return this._computeParticleTexture;
  59526. },
  59527. set: function (val) {
  59528. this._computeParticleTexture = val;
  59529. },
  59530. enumerable: true,
  59531. configurable: true
  59532. });
  59533. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleVertex", {
  59534. /**
  59535. * Gets if `setParticles()` calls the vertex function for each vertex of each particle, or not.
  59536. * Default value : false. The SPS is faster when it's set to false.
  59537. * Note : the particle custom vertex positions aren't stored values.
  59538. */
  59539. get: function () {
  59540. return this._computeParticleVertex;
  59541. },
  59542. /**
  59543. * Tells to `setParticles()` to call the vertex function for each vertex of each particle, or not.
  59544. * Default value : false. The SPS is faster when it's set to false.
  59545. * Note : the particle custom vertex positions aren't stored values.
  59546. */
  59547. set: function (val) {
  59548. this._computeParticleVertex = val;
  59549. },
  59550. enumerable: true,
  59551. configurable: true
  59552. });
  59553. Object.defineProperty(SolidParticleSystem.prototype, "computeBoundingBox", {
  59554. /**
  59555. * Gets if `setParticles()` computes or not the mesh bounding box when computing the particle positions.
  59556. */
  59557. get: function () {
  59558. return this._computeBoundingBox;
  59559. },
  59560. /**
  59561. * Tells to `setParticles()` to compute or not the mesh bounding box when computing the particle positions.
  59562. */
  59563. set: function (val) {
  59564. this._computeBoundingBox = val;
  59565. },
  59566. enumerable: true,
  59567. configurable: true
  59568. });
  59569. Object.defineProperty(SolidParticleSystem.prototype, "depthSortParticles", {
  59570. /**
  59571. * Gets if `setParticles()` sorts or not the distance between each particle and the camera.
  59572. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  59573. * Default : `true`
  59574. */
  59575. get: function () {
  59576. return this._depthSortParticles;
  59577. },
  59578. /**
  59579. * Tells to `setParticles()` to sort or not the distance between each particle and the camera.
  59580. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  59581. * Default : `true`
  59582. */
  59583. set: function (val) {
  59584. this._depthSortParticles = val;
  59585. },
  59586. enumerable: true,
  59587. configurable: true
  59588. });
  59589. // =======================================================================
  59590. // Particle behavior logic
  59591. // these following methods may be overwritten by the user to fit his needs
  59592. /**
  59593. * This function does nothing. It may be overwritten to set all the particle first values.
  59594. * The SPS doesn't call this function, you may have to call it by your own.
  59595. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  59596. */
  59597. SolidParticleSystem.prototype.initParticles = function () {
  59598. };
  59599. /**
  59600. * This function does nothing. It may be overwritten to recycle a particle.
  59601. * The SPS doesn't call this function, you may have to call it by your own.
  59602. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  59603. * @param particle The particle to recycle
  59604. * @returns the recycled particle
  59605. */
  59606. SolidParticleSystem.prototype.recycleParticle = function (particle) {
  59607. return particle;
  59608. };
  59609. /**
  59610. * Updates a particle : this function should be overwritten by the user.
  59611. * It is called on each particle by `setParticles()`. This is the place to code each particle behavior.
  59612. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  59613. * @example : just set a particle position or velocity and recycle conditions
  59614. * @param particle The particle to update
  59615. * @returns the updated particle
  59616. */
  59617. SolidParticleSystem.prototype.updateParticle = function (particle) {
  59618. return particle;
  59619. };
  59620. /**
  59621. * Updates a vertex of a particle : it can be overwritten by the user.
  59622. * This will be called on each vertex particle by `setParticles()` if `computeParticleVertex` is set to true only.
  59623. * @param particle the current particle
  59624. * @param vertex the current index of the current particle
  59625. * @param pt the index of the current vertex in the particle shape
  59626. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#update-each-particle-shape
  59627. * @example : just set a vertex particle position
  59628. * @returns the updated vertex
  59629. */
  59630. SolidParticleSystem.prototype.updateParticleVertex = function (particle, vertex, pt) {
  59631. return vertex;
  59632. };
  59633. /**
  59634. * This will be called before any other treatment by `setParticles()` and will be passed three parameters.
  59635. * This does nothing and may be overwritten by the user.
  59636. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  59637. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  59638. * @param update the boolean update value actually passed to setParticles()
  59639. */
  59640. SolidParticleSystem.prototype.beforeUpdateParticles = function (start, stop, update) {
  59641. };
  59642. /**
  59643. * This will be called by `setParticles()` after all the other treatments and just before the actual mesh update.
  59644. * This will be passed three parameters.
  59645. * This does nothing and may be overwritten by the user.
  59646. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  59647. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  59648. * @param update the boolean update value actually passed to setParticles()
  59649. */
  59650. SolidParticleSystem.prototype.afterUpdateParticles = function (start, stop, update) {
  59651. };
  59652. return SolidParticleSystem;
  59653. }());
  59654. BABYLON.SolidParticleSystem = SolidParticleSystem;
  59655. })(BABYLON || (BABYLON = {}));
  59656. //# sourceMappingURL=babylon.solidParticleSystem.js.map
  59657. var BABYLON;
  59658. (function (BABYLON) {
  59659. var ShaderMaterial = /** @class */ (function (_super) {
  59660. __extends(ShaderMaterial, _super);
  59661. function ShaderMaterial(name, scene, shaderPath, options) {
  59662. var _this = _super.call(this, name, scene) || this;
  59663. _this._textures = {};
  59664. _this._textureArrays = {};
  59665. _this._floats = {};
  59666. _this._ints = {};
  59667. _this._floatsArrays = {};
  59668. _this._colors3 = {};
  59669. _this._colors3Arrays = {};
  59670. _this._colors4 = {};
  59671. _this._vectors2 = {};
  59672. _this._vectors3 = {};
  59673. _this._vectors4 = {};
  59674. _this._matrices = {};
  59675. _this._matrices3x3 = {};
  59676. _this._matrices2x2 = {};
  59677. _this._vectors2Arrays = {};
  59678. _this._vectors3Arrays = {};
  59679. _this._cachedWorldViewMatrix = new BABYLON.Matrix();
  59680. _this._shaderPath = shaderPath;
  59681. options.needAlphaBlending = options.needAlphaBlending || false;
  59682. options.needAlphaTesting = options.needAlphaTesting || false;
  59683. options.attributes = options.attributes || ["position", "normal", "uv"];
  59684. options.uniforms = options.uniforms || ["worldViewProjection"];
  59685. options.uniformBuffers = options.uniformBuffers || [];
  59686. options.samplers = options.samplers || [];
  59687. options.defines = options.defines || [];
  59688. _this._options = options;
  59689. return _this;
  59690. }
  59691. ShaderMaterial.prototype.getClassName = function () {
  59692. return "ShaderMaterial";
  59693. };
  59694. ShaderMaterial.prototype.needAlphaBlending = function () {
  59695. return this._options.needAlphaBlending;
  59696. };
  59697. ShaderMaterial.prototype.needAlphaTesting = function () {
  59698. return this._options.needAlphaTesting;
  59699. };
  59700. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  59701. if (this._options.uniforms.indexOf(uniformName) === -1) {
  59702. this._options.uniforms.push(uniformName);
  59703. }
  59704. };
  59705. ShaderMaterial.prototype.setTexture = function (name, texture) {
  59706. if (this._options.samplers.indexOf(name) === -1) {
  59707. this._options.samplers.push(name);
  59708. }
  59709. this._textures[name] = texture;
  59710. return this;
  59711. };
  59712. ShaderMaterial.prototype.setTextureArray = function (name, textures) {
  59713. if (this._options.samplers.indexOf(name) === -1) {
  59714. this._options.samplers.push(name);
  59715. }
  59716. this._checkUniform(name);
  59717. this._textureArrays[name] = textures;
  59718. return this;
  59719. };
  59720. ShaderMaterial.prototype.setFloat = function (name, value) {
  59721. this._checkUniform(name);
  59722. this._floats[name] = value;
  59723. return this;
  59724. };
  59725. ShaderMaterial.prototype.setInt = function (name, value) {
  59726. this._checkUniform(name);
  59727. this._ints[name] = value;
  59728. return this;
  59729. };
  59730. ShaderMaterial.prototype.setFloats = function (name, value) {
  59731. this._checkUniform(name);
  59732. this._floatsArrays[name] = value;
  59733. return this;
  59734. };
  59735. ShaderMaterial.prototype.setColor3 = function (name, value) {
  59736. this._checkUniform(name);
  59737. this._colors3[name] = value;
  59738. return this;
  59739. };
  59740. ShaderMaterial.prototype.setColor3Array = function (name, value) {
  59741. this._checkUniform(name);
  59742. this._colors3Arrays[name] = value.reduce(function (arr, color) {
  59743. color.toArray(arr, arr.length);
  59744. return arr;
  59745. }, []);
  59746. return this;
  59747. };
  59748. ShaderMaterial.prototype.setColor4 = function (name, value) {
  59749. this._checkUniform(name);
  59750. this._colors4[name] = value;
  59751. return this;
  59752. };
  59753. ShaderMaterial.prototype.setVector2 = function (name, value) {
  59754. this._checkUniform(name);
  59755. this._vectors2[name] = value;
  59756. return this;
  59757. };
  59758. ShaderMaterial.prototype.setVector3 = function (name, value) {
  59759. this._checkUniform(name);
  59760. this._vectors3[name] = value;
  59761. return this;
  59762. };
  59763. ShaderMaterial.prototype.setVector4 = function (name, value) {
  59764. this._checkUniform(name);
  59765. this._vectors4[name] = value;
  59766. return this;
  59767. };
  59768. ShaderMaterial.prototype.setMatrix = function (name, value) {
  59769. this._checkUniform(name);
  59770. this._matrices[name] = value;
  59771. return this;
  59772. };
  59773. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  59774. this._checkUniform(name);
  59775. this._matrices3x3[name] = value;
  59776. return this;
  59777. };
  59778. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  59779. this._checkUniform(name);
  59780. this._matrices2x2[name] = value;
  59781. return this;
  59782. };
  59783. ShaderMaterial.prototype.setArray2 = function (name, value) {
  59784. this._checkUniform(name);
  59785. this._vectors2Arrays[name] = value;
  59786. return this;
  59787. };
  59788. ShaderMaterial.prototype.setArray3 = function (name, value) {
  59789. this._checkUniform(name);
  59790. this._vectors3Arrays[name] = value;
  59791. return this;
  59792. };
  59793. ShaderMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  59794. if (!mesh) {
  59795. return true;
  59796. }
  59797. if (this._effect && (this._effect.defines.indexOf("#define INSTANCES") !== -1) !== useInstances) {
  59798. return false;
  59799. }
  59800. return false;
  59801. };
  59802. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  59803. var scene = this.getScene();
  59804. var engine = scene.getEngine();
  59805. if (!this.checkReadyOnEveryCall) {
  59806. if (this._renderId === scene.getRenderId()) {
  59807. if (this._checkCache(scene, mesh, useInstances)) {
  59808. return true;
  59809. }
  59810. }
  59811. }
  59812. // Instances
  59813. var defines = [];
  59814. var attribs = [];
  59815. var fallbacks = new BABYLON.EffectFallbacks();
  59816. if (useInstances) {
  59817. defines.push("#define INSTANCES");
  59818. }
  59819. for (var index = 0; index < this._options.defines.length; index++) {
  59820. defines.push(this._options.defines[index]);
  59821. }
  59822. for (var index = 0; index < this._options.attributes.length; index++) {
  59823. attribs.push(this._options.attributes[index]);
  59824. }
  59825. if (mesh && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  59826. attribs.push(BABYLON.VertexBuffer.ColorKind);
  59827. defines.push("#define VERTEXCOLOR");
  59828. }
  59829. // Bones
  59830. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  59831. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  59832. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  59833. if (mesh.numBoneInfluencers > 4) {
  59834. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  59835. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  59836. }
  59837. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  59838. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  59839. fallbacks.addCPUSkinningFallback(0, mesh);
  59840. if (this._options.uniforms.indexOf("mBones") === -1) {
  59841. this._options.uniforms.push("mBones");
  59842. }
  59843. }
  59844. else {
  59845. defines.push("#define NUM_BONE_INFLUENCERS 0");
  59846. }
  59847. // Textures
  59848. for (var name in this._textures) {
  59849. if (!this._textures[name].isReady()) {
  59850. return false;
  59851. }
  59852. }
  59853. // Alpha test
  59854. if (mesh && this._shouldTurnAlphaTestOn(mesh)) {
  59855. defines.push("#define ALPHATEST");
  59856. }
  59857. var previousEffect = this._effect;
  59858. var join = defines.join("\n");
  59859. this._effect = engine.createEffect(this._shaderPath, {
  59860. attributes: attribs,
  59861. uniformsNames: this._options.uniforms,
  59862. uniformBuffersNames: this._options.uniformBuffers,
  59863. samplers: this._options.samplers,
  59864. defines: join,
  59865. fallbacks: fallbacks,
  59866. onCompiled: this.onCompiled,
  59867. onError: this.onError
  59868. }, engine);
  59869. if (!this._effect.isReady()) {
  59870. return false;
  59871. }
  59872. if (previousEffect !== this._effect) {
  59873. scene.resetCachedMaterial();
  59874. }
  59875. this._renderId = scene.getRenderId();
  59876. return true;
  59877. };
  59878. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  59879. var scene = this.getScene();
  59880. if (!this._effect) {
  59881. return;
  59882. }
  59883. if (this._options.uniforms.indexOf("world") !== -1) {
  59884. this._effect.setMatrix("world", world);
  59885. }
  59886. if (this._options.uniforms.indexOf("worldView") !== -1) {
  59887. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  59888. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  59889. }
  59890. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  59891. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  59892. }
  59893. };
  59894. ShaderMaterial.prototype.bind = function (world, mesh) {
  59895. // Std values
  59896. this.bindOnlyWorldMatrix(world);
  59897. if (this._effect && this.getScene().getCachedMaterial() !== this) {
  59898. if (this._options.uniforms.indexOf("view") !== -1) {
  59899. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  59900. }
  59901. if (this._options.uniforms.indexOf("projection") !== -1) {
  59902. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  59903. }
  59904. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  59905. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  59906. }
  59907. // Bones
  59908. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  59909. var name;
  59910. // Texture
  59911. for (name in this._textures) {
  59912. this._effect.setTexture(name, this._textures[name]);
  59913. }
  59914. // Texture arrays
  59915. for (name in this._textureArrays) {
  59916. this._effect.setTextureArray(name, this._textureArrays[name]);
  59917. }
  59918. // Int
  59919. for (name in this._ints) {
  59920. this._effect.setInt(name, this._ints[name]);
  59921. }
  59922. // Float
  59923. for (name in this._floats) {
  59924. this._effect.setFloat(name, this._floats[name]);
  59925. }
  59926. // Floats
  59927. for (name in this._floatsArrays) {
  59928. this._effect.setArray(name, this._floatsArrays[name]);
  59929. }
  59930. // Color3
  59931. for (name in this._colors3) {
  59932. this._effect.setColor3(name, this._colors3[name]);
  59933. }
  59934. for (name in this._colors3Arrays) {
  59935. this._effect.setArray3(name, this._colors3Arrays[name]);
  59936. }
  59937. // Color4
  59938. for (name in this._colors4) {
  59939. var color = this._colors4[name];
  59940. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  59941. }
  59942. // Vector2
  59943. for (name in this._vectors2) {
  59944. this._effect.setVector2(name, this._vectors2[name]);
  59945. }
  59946. // Vector3
  59947. for (name in this._vectors3) {
  59948. this._effect.setVector3(name, this._vectors3[name]);
  59949. }
  59950. // Vector4
  59951. for (name in this._vectors4) {
  59952. this._effect.setVector4(name, this._vectors4[name]);
  59953. }
  59954. // Matrix
  59955. for (name in this._matrices) {
  59956. this._effect.setMatrix(name, this._matrices[name]);
  59957. }
  59958. // Matrix 3x3
  59959. for (name in this._matrices3x3) {
  59960. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  59961. }
  59962. // Matrix 2x2
  59963. for (name in this._matrices2x2) {
  59964. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  59965. }
  59966. // Vector2Array
  59967. for (name in this._vectors2Arrays) {
  59968. this._effect.setArray2(name, this._vectors2Arrays[name]);
  59969. }
  59970. // Vector3Array
  59971. for (name in this._vectors3Arrays) {
  59972. this._effect.setArray3(name, this._vectors3Arrays[name]);
  59973. }
  59974. }
  59975. this._afterBind(mesh);
  59976. };
  59977. ShaderMaterial.prototype.getActiveTextures = function () {
  59978. var activeTextures = _super.prototype.getActiveTextures.call(this);
  59979. for (var name in this._textures) {
  59980. activeTextures.push(this._textures[name]);
  59981. }
  59982. for (var name in this._textureArrays) {
  59983. var array = this._textureArrays[name];
  59984. for (var index = 0; index < array.length; index++) {
  59985. activeTextures.push(array[index]);
  59986. }
  59987. }
  59988. return activeTextures;
  59989. };
  59990. ShaderMaterial.prototype.hasTexture = function (texture) {
  59991. if (_super.prototype.hasTexture.call(this, texture)) {
  59992. return true;
  59993. }
  59994. for (var name in this._textures) {
  59995. if (this._textures[name] === texture) {
  59996. return true;
  59997. }
  59998. }
  59999. for (var name in this._textureArrays) {
  60000. var array = this._textureArrays[name];
  60001. for (var index = 0; index < array.length; index++) {
  60002. if (array[index] === texture) {
  60003. return true;
  60004. }
  60005. }
  60006. }
  60007. return false;
  60008. };
  60009. ShaderMaterial.prototype.clone = function (name) {
  60010. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  60011. return newShaderMaterial;
  60012. };
  60013. ShaderMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  60014. if (forceDisposeTextures) {
  60015. var name;
  60016. for (name in this._textures) {
  60017. this._textures[name].dispose();
  60018. }
  60019. for (name in this._textureArrays) {
  60020. var array = this._textureArrays[name];
  60021. for (var index = 0; index < array.length; index++) {
  60022. array[index].dispose();
  60023. }
  60024. }
  60025. }
  60026. this._textures = {};
  60027. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  60028. };
  60029. ShaderMaterial.prototype.serialize = function () {
  60030. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  60031. serializationObject.customType = "BABYLON.ShaderMaterial";
  60032. serializationObject.options = this._options;
  60033. serializationObject.shaderPath = this._shaderPath;
  60034. var name;
  60035. // Texture
  60036. serializationObject.textures = {};
  60037. for (name in this._textures) {
  60038. serializationObject.textures[name] = this._textures[name].serialize();
  60039. }
  60040. // Texture arrays
  60041. serializationObject.textureArrays = {};
  60042. for (name in this._textureArrays) {
  60043. serializationObject.textureArrays[name] = [];
  60044. var array = this._textureArrays[name];
  60045. for (var index = 0; index < array.length; index++) {
  60046. serializationObject.textureArrays[name].push(array[index].serialize());
  60047. }
  60048. }
  60049. // Float
  60050. serializationObject.floats = {};
  60051. for (name in this._floats) {
  60052. serializationObject.floats[name] = this._floats[name];
  60053. }
  60054. // Float s
  60055. serializationObject.FloatArrays = {};
  60056. for (name in this._floatsArrays) {
  60057. serializationObject.FloatArrays[name] = this._floatsArrays[name];
  60058. }
  60059. // Color3
  60060. serializationObject.colors3 = {};
  60061. for (name in this._colors3) {
  60062. serializationObject.colors3[name] = this._colors3[name].asArray();
  60063. }
  60064. // Color3 array
  60065. serializationObject.colors3Arrays = {};
  60066. for (name in this._colors3Arrays) {
  60067. serializationObject.colors3Arrays[name] = this._colors3Arrays[name];
  60068. }
  60069. // Color4
  60070. serializationObject.colors4 = {};
  60071. for (name in this._colors4) {
  60072. serializationObject.colors4[name] = this._colors4[name].asArray();
  60073. }
  60074. // Vector2
  60075. serializationObject.vectors2 = {};
  60076. for (name in this._vectors2) {
  60077. serializationObject.vectors2[name] = this._vectors2[name].asArray();
  60078. }
  60079. // Vector3
  60080. serializationObject.vectors3 = {};
  60081. for (name in this._vectors3) {
  60082. serializationObject.vectors3[name] = this._vectors3[name].asArray();
  60083. }
  60084. // Vector4
  60085. serializationObject.vectors4 = {};
  60086. for (name in this._vectors4) {
  60087. serializationObject.vectors4[name] = this._vectors4[name].asArray();
  60088. }
  60089. // Matrix
  60090. serializationObject.matrices = {};
  60091. for (name in this._matrices) {
  60092. serializationObject.matrices[name] = this._matrices[name].asArray();
  60093. }
  60094. // Matrix 3x3
  60095. serializationObject.matrices3x3 = {};
  60096. for (name in this._matrices3x3) {
  60097. serializationObject.matrices3x3[name] = this._matrices3x3[name];
  60098. }
  60099. // Matrix 2x2
  60100. serializationObject.matrices2x2 = {};
  60101. for (name in this._matrices2x2) {
  60102. serializationObject.matrices2x2[name] = this._matrices2x2[name];
  60103. }
  60104. // Vector2Array
  60105. serializationObject.vectors2Arrays = {};
  60106. for (name in this._vectors2Arrays) {
  60107. serializationObject.vectors2Arrays[name] = this._vectors2Arrays[name];
  60108. }
  60109. // Vector3Array
  60110. serializationObject.vectors3Arrays = {};
  60111. for (name in this._vectors3Arrays) {
  60112. serializationObject.vectors3Arrays[name] = this._vectors3Arrays[name];
  60113. }
  60114. return serializationObject;
  60115. };
  60116. ShaderMaterial.Parse = function (source, scene, rootUrl) {
  60117. var material = BABYLON.SerializationHelper.Parse(function () { return new ShaderMaterial(source.name, scene, source.shaderPath, source.options); }, source, scene, rootUrl);
  60118. var name;
  60119. // Texture
  60120. for (name in source.textures) {
  60121. material.setTexture(name, BABYLON.Texture.Parse(source.textures[name], scene, rootUrl));
  60122. }
  60123. // Texture arrays
  60124. for (name in source.textureArrays) {
  60125. var array = source.textureArrays[name];
  60126. var textureArray = new Array();
  60127. for (var index = 0; index < array.length; index++) {
  60128. textureArray.push(BABYLON.Texture.Parse(array[index], scene, rootUrl));
  60129. }
  60130. material.setTextureArray(name, textureArray);
  60131. }
  60132. // Float
  60133. for (name in source.floats) {
  60134. material.setFloat(name, source.floats[name]);
  60135. }
  60136. // Float s
  60137. for (name in source.floatsArrays) {
  60138. material.setFloats(name, source.floatsArrays[name]);
  60139. }
  60140. // Color3
  60141. for (name in source.colors3) {
  60142. material.setColor3(name, BABYLON.Color3.FromArray(source.colors3[name]));
  60143. }
  60144. // Color3 arrays
  60145. for (name in source.colors3Arrays) {
  60146. var colors = source.colors3Arrays[name].reduce(function (arr, num, i) {
  60147. if (i % 3 === 0) {
  60148. arr.push([num]);
  60149. }
  60150. else {
  60151. arr[arr.length - 1].push(num);
  60152. }
  60153. return arr;
  60154. }, []).map(function (color) { return BABYLON.Color3.FromArray(color); });
  60155. material.setColor3Array(name, colors);
  60156. }
  60157. // Color4
  60158. for (name in source.colors4) {
  60159. material.setColor4(name, BABYLON.Color4.FromArray(source.colors4[name]));
  60160. }
  60161. // Vector2
  60162. for (name in source.vectors2) {
  60163. material.setVector2(name, BABYLON.Vector2.FromArray(source.vectors2[name]));
  60164. }
  60165. // Vector3
  60166. for (name in source.vectors3) {
  60167. material.setVector3(name, BABYLON.Vector3.FromArray(source.vectors3[name]));
  60168. }
  60169. // Vector4
  60170. for (name in source.vectors4) {
  60171. material.setVector4(name, BABYLON.Vector4.FromArray(source.vectors4[name]));
  60172. }
  60173. // Matrix
  60174. for (name in source.matrices) {
  60175. material.setMatrix(name, BABYLON.Matrix.FromArray(source.matrices[name]));
  60176. }
  60177. // Matrix 3x3
  60178. for (name in source.matrices3x3) {
  60179. material.setMatrix3x3(name, source.matrices3x3[name]);
  60180. }
  60181. // Matrix 2x2
  60182. for (name in source.matrices2x2) {
  60183. material.setMatrix2x2(name, source.matrices2x2[name]);
  60184. }
  60185. // Vector2Array
  60186. for (name in source.vectors2Arrays) {
  60187. material.setArray2(name, source.vectors2Arrays[name]);
  60188. }
  60189. // Vector3Array
  60190. for (name in source.vectors3Arrays) {
  60191. material.setArray3(name, source.vectors3Arrays[name]);
  60192. }
  60193. return material;
  60194. };
  60195. return ShaderMaterial;
  60196. }(BABYLON.Material));
  60197. BABYLON.ShaderMaterial = ShaderMaterial;
  60198. })(BABYLON || (BABYLON = {}));
  60199. //# sourceMappingURL=babylon.shaderMaterial.js.map
  60200. var BABYLON;
  60201. (function (BABYLON) {
  60202. var GroundMesh = /** @class */ (function (_super) {
  60203. __extends(GroundMesh, _super);
  60204. function GroundMesh(name, scene) {
  60205. var _this = _super.call(this, name, scene) || this;
  60206. _this.generateOctree = false;
  60207. return _this;
  60208. }
  60209. GroundMesh.prototype.getClassName = function () {
  60210. return "GroundMesh";
  60211. };
  60212. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  60213. get: function () {
  60214. return Math.min(this._subdivisionsX, this._subdivisionsY);
  60215. },
  60216. enumerable: true,
  60217. configurable: true
  60218. });
  60219. Object.defineProperty(GroundMesh.prototype, "subdivisionsX", {
  60220. get: function () {
  60221. return this._subdivisionsX;
  60222. },
  60223. enumerable: true,
  60224. configurable: true
  60225. });
  60226. Object.defineProperty(GroundMesh.prototype, "subdivisionsY", {
  60227. get: function () {
  60228. return this._subdivisionsY;
  60229. },
  60230. enumerable: true,
  60231. configurable: true
  60232. });
  60233. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  60234. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  60235. this._subdivisionsX = chunksCount;
  60236. this._subdivisionsY = chunksCount;
  60237. this.subdivide(chunksCount);
  60238. this.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  60239. };
  60240. /**
  60241. * Returns a height (y) value in the Worl system :
  60242. * the ground altitude at the coordinates (x, z) expressed in the World system.
  60243. * Returns the ground y position if (x, z) are outside the ground surface.
  60244. */
  60245. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  60246. var world = this.getWorldMatrix();
  60247. var invMat = BABYLON.Tmp.Matrix[5];
  60248. world.invertToRef(invMat);
  60249. var tmpVect = BABYLON.Tmp.Vector3[8];
  60250. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, invMat, tmpVect); // transform x,z in the mesh local space
  60251. x = tmpVect.x;
  60252. z = tmpVect.z;
  60253. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  60254. return this.position.y;
  60255. }
  60256. if (!this._heightQuads || this._heightQuads.length == 0) {
  60257. this._initHeightQuads();
  60258. this._computeHeightQuads();
  60259. }
  60260. var facet = this._getFacetAt(x, z);
  60261. var y = -(facet.x * x + facet.z * z + facet.w) / facet.y;
  60262. // return y in the World system
  60263. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(0.0, y, 0.0, world, tmpVect);
  60264. return tmpVect.y;
  60265. };
  60266. /**
  60267. * Returns a normalized vector (Vector3) orthogonal to the ground
  60268. * at the ground coordinates (x, z) expressed in the World system.
  60269. * Returns Vector3(0.0, 1.0, 0.0) if (x, z) are outside the ground surface.
  60270. */
  60271. GroundMesh.prototype.getNormalAtCoordinates = function (x, z) {
  60272. var normal = new BABYLON.Vector3(0.0, 1.0, 0.0);
  60273. this.getNormalAtCoordinatesToRef(x, z, normal);
  60274. return normal;
  60275. };
  60276. /**
  60277. * Updates the Vector3 passed a reference with a normalized vector orthogonal to the ground
  60278. * at the ground coordinates (x, z) expressed in the World system.
  60279. * Doesn't uptade the reference Vector3 if (x, z) are outside the ground surface.
  60280. * Returns the GroundMesh.
  60281. */
  60282. GroundMesh.prototype.getNormalAtCoordinatesToRef = function (x, z, ref) {
  60283. var world = this.getWorldMatrix();
  60284. var tmpMat = BABYLON.Tmp.Matrix[5];
  60285. world.invertToRef(tmpMat);
  60286. var tmpVect = BABYLON.Tmp.Vector3[8];
  60287. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, tmpMat, tmpVect); // transform x,z in the mesh local space
  60288. x = tmpVect.x;
  60289. z = tmpVect.z;
  60290. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  60291. return this;
  60292. }
  60293. if (!this._heightQuads || this._heightQuads.length == 0) {
  60294. this._initHeightQuads();
  60295. this._computeHeightQuads();
  60296. }
  60297. var facet = this._getFacetAt(x, z);
  60298. BABYLON.Vector3.TransformNormalFromFloatsToRef(facet.x, facet.y, facet.z, world, ref);
  60299. return this;
  60300. };
  60301. /**
  60302. * Force the heights to be recomputed for getHeightAtCoordinates() or getNormalAtCoordinates()
  60303. * if the ground has been updated.
  60304. * This can be used in the render loop.
  60305. * Returns the GroundMesh.
  60306. */
  60307. GroundMesh.prototype.updateCoordinateHeights = function () {
  60308. if (!this._heightQuads || this._heightQuads.length == 0) {
  60309. this._initHeightQuads();
  60310. }
  60311. this._computeHeightQuads();
  60312. return this;
  60313. };
  60314. // Returns the element "facet" from the heightQuads array relative to (x, z) local coordinates
  60315. GroundMesh.prototype._getFacetAt = function (x, z) {
  60316. // retrieve col and row from x, z coordinates in the ground local system
  60317. var col = Math.floor((x + this._maxX) * this._subdivisionsX / this._width);
  60318. var row = Math.floor(-(z + this._maxZ) * this._subdivisionsY / this._height + this._subdivisionsY);
  60319. var quad = this._heightQuads[row * this._subdivisionsX + col];
  60320. var facet;
  60321. if (z < quad.slope.x * x + quad.slope.y) {
  60322. facet = quad.facet1;
  60323. }
  60324. else {
  60325. facet = quad.facet2;
  60326. }
  60327. return facet;
  60328. };
  60329. // Creates and populates the heightMap array with "facet" elements :
  60330. // a quad is two triangular facets separated by a slope, so a "facet" element is 1 slope + 2 facets
  60331. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  60332. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  60333. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  60334. // Returns the GroundMesh.
  60335. GroundMesh.prototype._initHeightQuads = function () {
  60336. var subdivisionsX = this._subdivisionsX;
  60337. var subdivisionsY = this._subdivisionsY;
  60338. this._heightQuads = new Array();
  60339. for (var row = 0; row < subdivisionsY; row++) {
  60340. for (var col = 0; col < subdivisionsX; col++) {
  60341. 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) };
  60342. this._heightQuads[row * subdivisionsX + col] = quad;
  60343. }
  60344. }
  60345. return this;
  60346. };
  60347. // Compute each quad element values and update the the heightMap array :
  60348. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  60349. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  60350. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  60351. // Returns the GroundMesh.
  60352. GroundMesh.prototype._computeHeightQuads = function () {
  60353. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  60354. if (!positions) {
  60355. return this;
  60356. }
  60357. var v1 = BABYLON.Tmp.Vector3[3];
  60358. var v2 = BABYLON.Tmp.Vector3[2];
  60359. var v3 = BABYLON.Tmp.Vector3[1];
  60360. var v4 = BABYLON.Tmp.Vector3[0];
  60361. var v1v2 = BABYLON.Tmp.Vector3[4];
  60362. var v1v3 = BABYLON.Tmp.Vector3[5];
  60363. var v1v4 = BABYLON.Tmp.Vector3[6];
  60364. var norm1 = BABYLON.Tmp.Vector3[7];
  60365. var norm2 = BABYLON.Tmp.Vector3[8];
  60366. var i = 0;
  60367. var j = 0;
  60368. var k = 0;
  60369. var cd = 0; // 2D slope coefficient : z = cd * x + h
  60370. var h = 0;
  60371. var d1 = 0; // facet plane equation : ax + by + cz + d = 0
  60372. var d2 = 0;
  60373. var subdivisionsX = this._subdivisionsX;
  60374. var subdivisionsY = this._subdivisionsY;
  60375. for (var row = 0; row < subdivisionsY; row++) {
  60376. for (var col = 0; col < subdivisionsX; col++) {
  60377. i = col * 3;
  60378. j = row * (subdivisionsX + 1) * 3;
  60379. k = (row + 1) * (subdivisionsX + 1) * 3;
  60380. v1.x = positions[j + i];
  60381. v1.y = positions[j + i + 1];
  60382. v1.z = positions[j + i + 2];
  60383. v2.x = positions[j + i + 3];
  60384. v2.y = positions[j + i + 4];
  60385. v2.z = positions[j + i + 5];
  60386. v3.x = positions[k + i];
  60387. v3.y = positions[k + i + 1];
  60388. v3.z = positions[k + i + 2];
  60389. v4.x = positions[k + i + 3];
  60390. v4.y = positions[k + i + 4];
  60391. v4.z = positions[k + i + 5];
  60392. // 2D slope V1V4
  60393. cd = (v4.z - v1.z) / (v4.x - v1.x);
  60394. h = v1.z - cd * v1.x; // v1 belongs to the slope
  60395. // facet equations :
  60396. // we compute each facet normal vector
  60397. // the equation of the facet plane is : norm.x * x + norm.y * y + norm.z * z + d = 0
  60398. // we compute the value d by applying the equation to v1 which belongs to the plane
  60399. // then we store the facet equation in a Vector4
  60400. v2.subtractToRef(v1, v1v2);
  60401. v3.subtractToRef(v1, v1v3);
  60402. v4.subtractToRef(v1, v1v4);
  60403. BABYLON.Vector3.CrossToRef(v1v4, v1v3, norm1); // caution : CrossToRef uses the Tmp class
  60404. BABYLON.Vector3.CrossToRef(v1v2, v1v4, norm2);
  60405. norm1.normalize();
  60406. norm2.normalize();
  60407. d1 = -(norm1.x * v1.x + norm1.y * v1.y + norm1.z * v1.z);
  60408. d2 = -(norm2.x * v2.x + norm2.y * v2.y + norm2.z * v2.z);
  60409. var quad = this._heightQuads[row * subdivisionsX + col];
  60410. quad.slope.copyFromFloats(cd, h);
  60411. quad.facet1.copyFromFloats(norm1.x, norm1.y, norm1.z, d1);
  60412. quad.facet2.copyFromFloats(norm2.x, norm2.y, norm2.z, d2);
  60413. }
  60414. }
  60415. return this;
  60416. };
  60417. GroundMesh.prototype.serialize = function (serializationObject) {
  60418. _super.prototype.serialize.call(this, serializationObject);
  60419. serializationObject.subdivisionsX = this._subdivisionsX;
  60420. serializationObject.subdivisionsY = this._subdivisionsY;
  60421. serializationObject.minX = this._minX;
  60422. serializationObject.maxX = this._maxX;
  60423. serializationObject.minZ = this._minZ;
  60424. serializationObject.maxZ = this._maxZ;
  60425. serializationObject.width = this._width;
  60426. serializationObject.height = this._height;
  60427. };
  60428. GroundMesh.Parse = function (parsedMesh, scene) {
  60429. var result = new GroundMesh(parsedMesh.name, scene);
  60430. result._subdivisionsX = parsedMesh.subdivisionsX || 1;
  60431. result._subdivisionsY = parsedMesh.subdivisionsY || 1;
  60432. result._minX = parsedMesh.minX;
  60433. result._maxX = parsedMesh.maxX;
  60434. result._minZ = parsedMesh.minZ;
  60435. result._maxZ = parsedMesh.maxZ;
  60436. result._width = parsedMesh.width;
  60437. result._height = parsedMesh.height;
  60438. return result;
  60439. };
  60440. return GroundMesh;
  60441. }(BABYLON.Mesh));
  60442. BABYLON.GroundMesh = GroundMesh;
  60443. })(BABYLON || (BABYLON = {}));
  60444. //# sourceMappingURL=babylon.groundMesh.js.map
  60445. var BABYLON;
  60446. (function (BABYLON) {
  60447. /**
  60448. * Creates an instance based on a source mesh.
  60449. */
  60450. var InstancedMesh = /** @class */ (function (_super) {
  60451. __extends(InstancedMesh, _super);
  60452. function InstancedMesh(name, source) {
  60453. var _this = _super.call(this, name, source.getScene()) || this;
  60454. source.instances.push(_this);
  60455. _this._sourceMesh = source;
  60456. _this.position.copyFrom(source.position);
  60457. _this.rotation.copyFrom(source.rotation);
  60458. _this.scaling.copyFrom(source.scaling);
  60459. if (source.rotationQuaternion) {
  60460. _this.rotationQuaternion = source.rotationQuaternion.clone();
  60461. }
  60462. _this.infiniteDistance = source.infiniteDistance;
  60463. _this.setPivotMatrix(source.getPivotMatrix());
  60464. _this.refreshBoundingInfo();
  60465. _this._syncSubMeshes();
  60466. return _this;
  60467. }
  60468. /**
  60469. * Returns the string "InstancedMesh".
  60470. */
  60471. InstancedMesh.prototype.getClassName = function () {
  60472. return "InstancedMesh";
  60473. };
  60474. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  60475. // Methods
  60476. get: function () {
  60477. return this._sourceMesh.receiveShadows;
  60478. },
  60479. enumerable: true,
  60480. configurable: true
  60481. });
  60482. Object.defineProperty(InstancedMesh.prototype, "material", {
  60483. get: function () {
  60484. return this._sourceMesh.material;
  60485. },
  60486. enumerable: true,
  60487. configurable: true
  60488. });
  60489. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  60490. get: function () {
  60491. return this._sourceMesh.visibility;
  60492. },
  60493. enumerable: true,
  60494. configurable: true
  60495. });
  60496. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  60497. get: function () {
  60498. return this._sourceMesh.skeleton;
  60499. },
  60500. enumerable: true,
  60501. configurable: true
  60502. });
  60503. Object.defineProperty(InstancedMesh.prototype, "renderingGroupId", {
  60504. get: function () {
  60505. return this._sourceMesh.renderingGroupId;
  60506. },
  60507. set: function (value) {
  60508. if (!this._sourceMesh || value === this._sourceMesh.renderingGroupId) {
  60509. return;
  60510. }
  60511. //no-op with warning
  60512. BABYLON.Tools.Warn("Note - setting renderingGroupId of an instanced mesh has no effect on the scene");
  60513. },
  60514. enumerable: true,
  60515. configurable: true
  60516. });
  60517. /**
  60518. * Returns the total number of vertices (integer).
  60519. */
  60520. InstancedMesh.prototype.getTotalVertices = function () {
  60521. return this._sourceMesh.getTotalVertices();
  60522. };
  60523. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  60524. get: function () {
  60525. return this._sourceMesh;
  60526. },
  60527. enumerable: true,
  60528. configurable: true
  60529. });
  60530. /**
  60531. * Is this node ready to be used/rendered
  60532. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  60533. * @return {boolean} is it ready
  60534. */
  60535. InstancedMesh.prototype.isReady = function (completeCheck) {
  60536. if (completeCheck === void 0) { completeCheck = false; }
  60537. return this._sourceMesh.isReady(completeCheck, true);
  60538. };
  60539. /**
  60540. * Returns a float array or a Float32Array of the requested kind of data : positons, normals, uvs, etc.
  60541. */
  60542. InstancedMesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  60543. return this._sourceMesh.getVerticesData(kind, copyWhenShared);
  60544. };
  60545. /**
  60546. * Sets the vertex data of the mesh geometry for the requested `kind`.
  60547. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  60548. * The `data` are either a numeric array either a Float32Array.
  60549. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  60550. * 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).
  60551. * Note that a new underlying VertexBuffer object is created each call.
  60552. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  60553. *
  60554. * Possible `kind` values :
  60555. * - BABYLON.VertexBuffer.PositionKind
  60556. * - BABYLON.VertexBuffer.UVKind
  60557. * - BABYLON.VertexBuffer.UV2Kind
  60558. * - BABYLON.VertexBuffer.UV3Kind
  60559. * - BABYLON.VertexBuffer.UV4Kind
  60560. * - BABYLON.VertexBuffer.UV5Kind
  60561. * - BABYLON.VertexBuffer.UV6Kind
  60562. * - BABYLON.VertexBuffer.ColorKind
  60563. * - BABYLON.VertexBuffer.MatricesIndicesKind
  60564. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  60565. * - BABYLON.VertexBuffer.MatricesWeightsKind
  60566. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  60567. *
  60568. * Returns the Mesh.
  60569. */
  60570. InstancedMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  60571. if (this.sourceMesh) {
  60572. this.sourceMesh.setVerticesData(kind, data, updatable, stride);
  60573. }
  60574. return this.sourceMesh;
  60575. };
  60576. /**
  60577. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  60578. * If the mesh has no geometry, it is simply returned as it is.
  60579. * The `data` are either a numeric array either a Float32Array.
  60580. * No new underlying VertexBuffer object is created.
  60581. * 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.
  60582. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  60583. *
  60584. * Possible `kind` values :
  60585. * - BABYLON.VertexBuffer.PositionKind
  60586. * - BABYLON.VertexBuffer.UVKind
  60587. * - BABYLON.VertexBuffer.UV2Kind
  60588. * - BABYLON.VertexBuffer.UV3Kind
  60589. * - BABYLON.VertexBuffer.UV4Kind
  60590. * - BABYLON.VertexBuffer.UV5Kind
  60591. * - BABYLON.VertexBuffer.UV6Kind
  60592. * - BABYLON.VertexBuffer.ColorKind
  60593. * - BABYLON.VertexBuffer.MatricesIndicesKind
  60594. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  60595. * - BABYLON.VertexBuffer.MatricesWeightsKind
  60596. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  60597. *
  60598. * Returns the Mesh.
  60599. */
  60600. InstancedMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  60601. if (this.sourceMesh) {
  60602. this.sourceMesh.updateVerticesData(kind, data, updateExtends, makeItUnique);
  60603. }
  60604. return this.sourceMesh;
  60605. };
  60606. /**
  60607. * Sets the mesh indices.
  60608. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  60609. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  60610. * This method creates a new index buffer each call.
  60611. * Returns the Mesh.
  60612. */
  60613. InstancedMesh.prototype.setIndices = function (indices, totalVertices) {
  60614. if (totalVertices === void 0) { totalVertices = null; }
  60615. if (this.sourceMesh) {
  60616. this.sourceMesh.setIndices(indices, totalVertices);
  60617. }
  60618. return this.sourceMesh;
  60619. };
  60620. /**
  60621. * Boolean : True if the mesh owns the requested kind of data.
  60622. */
  60623. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  60624. return this._sourceMesh.isVerticesDataPresent(kind);
  60625. };
  60626. /**
  60627. * Returns an array of indices (IndicesArray).
  60628. */
  60629. InstancedMesh.prototype.getIndices = function () {
  60630. return this._sourceMesh.getIndices();
  60631. };
  60632. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  60633. get: function () {
  60634. return this._sourceMesh._positions;
  60635. },
  60636. enumerable: true,
  60637. configurable: true
  60638. });
  60639. /**
  60640. * Sets a new updated BoundingInfo to the mesh.
  60641. * Returns the mesh.
  60642. */
  60643. InstancedMesh.prototype.refreshBoundingInfo = function () {
  60644. var meshBB = this._sourceMesh.getBoundingInfo();
  60645. this._boundingInfo = new BABYLON.BoundingInfo(meshBB.minimum.clone(), meshBB.maximum.clone());
  60646. this._updateBoundingInfo();
  60647. return this;
  60648. };
  60649. InstancedMesh.prototype._preActivate = function () {
  60650. if (this._currentLOD) {
  60651. this._currentLOD._preActivate();
  60652. }
  60653. return this;
  60654. };
  60655. InstancedMesh.prototype._activate = function (renderId) {
  60656. if (this._currentLOD) {
  60657. this._currentLOD._registerInstanceForRenderId(this, renderId);
  60658. }
  60659. return this;
  60660. };
  60661. /**
  60662. * Returns the current associated LOD AbstractMesh.
  60663. */
  60664. InstancedMesh.prototype.getLOD = function (camera) {
  60665. if (!camera) {
  60666. return this;
  60667. }
  60668. var boundingInfo = this.getBoundingInfo();
  60669. this._currentLOD = this.sourceMesh.getLOD(camera, boundingInfo.boundingSphere);
  60670. if (this._currentLOD === this.sourceMesh) {
  60671. return this;
  60672. }
  60673. return this._currentLOD;
  60674. };
  60675. InstancedMesh.prototype._syncSubMeshes = function () {
  60676. this.releaseSubMeshes();
  60677. if (this._sourceMesh.subMeshes) {
  60678. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  60679. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  60680. }
  60681. }
  60682. return this;
  60683. };
  60684. InstancedMesh.prototype._generatePointsArray = function () {
  60685. return this._sourceMesh._generatePointsArray();
  60686. };
  60687. /**
  60688. * Creates a new InstancedMesh from the current mesh.
  60689. * - name (string) : the cloned mesh name
  60690. * - newParent (optional Node) : the optional Node to parent the clone to.
  60691. * - doNotCloneChildren (optional boolean, default `false`) : if `true` the model children aren't cloned.
  60692. *
  60693. * Returns the clone.
  60694. */
  60695. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  60696. var result = this._sourceMesh.createInstance(name);
  60697. // Deep copy
  60698. BABYLON.Tools.DeepCopy(this, result, ["name", "subMeshes", "uniqueId"], []);
  60699. // Bounding info
  60700. this.refreshBoundingInfo();
  60701. // Parent
  60702. if (newParent) {
  60703. result.parent = newParent;
  60704. }
  60705. if (!doNotCloneChildren) {
  60706. // Children
  60707. for (var index = 0; index < this.getScene().meshes.length; index++) {
  60708. var mesh = this.getScene().meshes[index];
  60709. if (mesh.parent === this) {
  60710. mesh.clone(mesh.name, result);
  60711. }
  60712. }
  60713. }
  60714. result.computeWorldMatrix(true);
  60715. return result;
  60716. };
  60717. /**
  60718. * Disposes the InstancedMesh.
  60719. * Returns nothing.
  60720. */
  60721. InstancedMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  60722. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  60723. // Remove from mesh
  60724. var index = this._sourceMesh.instances.indexOf(this);
  60725. this._sourceMesh.instances.splice(index, 1);
  60726. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  60727. };
  60728. return InstancedMesh;
  60729. }(BABYLON.AbstractMesh));
  60730. BABYLON.InstancedMesh = InstancedMesh;
  60731. })(BABYLON || (BABYLON = {}));
  60732. //# sourceMappingURL=babylon.instancedMesh.js.map
  60733. var BABYLON;
  60734. (function (BABYLON) {
  60735. var LinesMesh = /** @class */ (function (_super) {
  60736. __extends(LinesMesh, _super);
  60737. function LinesMesh(name, scene, parent, source, doNotCloneChildren, useVertexColor, useVertexAlpha) {
  60738. if (scene === void 0) { scene = null; }
  60739. if (parent === void 0) { parent = null; }
  60740. var _this = _super.call(this, name, scene, parent, source, doNotCloneChildren) || this;
  60741. _this.useVertexColor = useVertexColor;
  60742. _this.useVertexAlpha = useVertexAlpha;
  60743. _this.color = new BABYLON.Color3(1, 1, 1);
  60744. _this.alpha = 1;
  60745. if (source) {
  60746. _this.color = source.color.clone();
  60747. _this.alpha = source.alpha;
  60748. _this.useVertexColor = source.useVertexColor;
  60749. _this.useVertexAlpha = source.useVertexAlpha;
  60750. }
  60751. _this._intersectionThreshold = 0.1;
  60752. var defines = [];
  60753. var options = {
  60754. attributes: [BABYLON.VertexBuffer.PositionKind],
  60755. uniforms: ["world", "viewProjection"],
  60756. needAlphaBlending: true,
  60757. defines: defines
  60758. };
  60759. if (useVertexAlpha === false) {
  60760. options.needAlphaBlending = false;
  60761. }
  60762. if (!useVertexColor) {
  60763. options.uniforms.push("color");
  60764. }
  60765. else {
  60766. options.defines.push("#define VERTEXCOLOR");
  60767. options.attributes.push(BABYLON.VertexBuffer.ColorKind);
  60768. }
  60769. _this._colorShader = new BABYLON.ShaderMaterial("colorShader", _this.getScene(), "color", options);
  60770. return _this;
  60771. }
  60772. Object.defineProperty(LinesMesh.prototype, "intersectionThreshold", {
  60773. /**
  60774. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  60775. * This margin is expressed in world space coordinates, so its value may vary.
  60776. * Default value is 0.1
  60777. * @returns the intersection Threshold value.
  60778. */
  60779. get: function () {
  60780. return this._intersectionThreshold;
  60781. },
  60782. /**
  60783. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  60784. * This margin is expressed in world space coordinates, so its value may vary.
  60785. * @param value the new threshold to apply
  60786. */
  60787. set: function (value) {
  60788. if (this._intersectionThreshold === value) {
  60789. return;
  60790. }
  60791. this._intersectionThreshold = value;
  60792. if (this.geometry) {
  60793. this.geometry.boundingBias = new BABYLON.Vector2(0, value);
  60794. }
  60795. },
  60796. enumerable: true,
  60797. configurable: true
  60798. });
  60799. /**
  60800. * Returns the string "LineMesh"
  60801. */
  60802. LinesMesh.prototype.getClassName = function () {
  60803. return "LinesMesh";
  60804. };
  60805. Object.defineProperty(LinesMesh.prototype, "material", {
  60806. get: function () {
  60807. return this._colorShader;
  60808. },
  60809. set: function (value) {
  60810. // Do nothing
  60811. },
  60812. enumerable: true,
  60813. configurable: true
  60814. });
  60815. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  60816. get: function () {
  60817. return false;
  60818. },
  60819. enumerable: true,
  60820. configurable: true
  60821. });
  60822. LinesMesh.prototype.createInstance = function (name) {
  60823. throw new Error("LinesMeshes do not support createInstance.");
  60824. };
  60825. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  60826. if (!this._geometry) {
  60827. return this;
  60828. }
  60829. // VBOs
  60830. this._geometry._bind(this._colorShader.getEffect());
  60831. // Color
  60832. if (!this.useVertexColor) {
  60833. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  60834. }
  60835. return this;
  60836. };
  60837. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  60838. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  60839. return this;
  60840. }
  60841. var engine = this.getScene().getEngine();
  60842. // Draw order
  60843. engine.drawElementsType(BABYLON.Material.LineListDrawMode, subMesh.indexStart, subMesh.indexCount);
  60844. return this;
  60845. };
  60846. LinesMesh.prototype.dispose = function (doNotRecurse) {
  60847. this._colorShader.dispose();
  60848. _super.prototype.dispose.call(this, doNotRecurse);
  60849. };
  60850. /**
  60851. * Returns a new LineMesh object cloned from the current one.
  60852. */
  60853. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  60854. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  60855. };
  60856. return LinesMesh;
  60857. }(BABYLON.Mesh));
  60858. BABYLON.LinesMesh = LinesMesh;
  60859. })(BABYLON || (BABYLON = {}));
  60860. //# sourceMappingURL=babylon.linesMesh.js.map
  60861. var BABYLON;
  60862. (function (BABYLON) {
  60863. /**
  60864. * Class containing static functions to help procedurally build meshes
  60865. */
  60866. var MeshBuilder = /** @class */ (function () {
  60867. function MeshBuilder() {
  60868. }
  60869. MeshBuilder.updateSideOrientation = function (orientation) {
  60870. if (orientation == BABYLON.Mesh.DOUBLESIDE) {
  60871. return BABYLON.Mesh.DOUBLESIDE;
  60872. }
  60873. if (orientation === undefined || orientation === null) {
  60874. return BABYLON.Mesh.FRONTSIDE;
  60875. }
  60876. return orientation;
  60877. };
  60878. /**
  60879. * Creates a box mesh
  60880. * * The parameter `size` sets the size (float) of each box side (default 1)
  60881. * * You can set some different box dimensions by using the parameters `width`, `height` and `depth` (all by default have the same value than `size`)
  60882. * * 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)
  60883. * * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  60884. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60885. * * 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
  60886. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60887. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#box
  60888. * @param name defines the name of the mesh
  60889. * @param options defines the options used to create the mesh
  60890. * @param scene defines the hosting scene
  60891. * @returns the box mesh
  60892. */
  60893. MeshBuilder.CreateBox = function (name, options, scene) {
  60894. if (scene === void 0) { scene = null; }
  60895. var box = new BABYLON.Mesh(name, scene);
  60896. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60897. box._originalBuilderSideOrientation = options.sideOrientation;
  60898. var vertexData = BABYLON.VertexData.CreateBox(options);
  60899. vertexData.applyToMesh(box, options.updatable);
  60900. return box;
  60901. };
  60902. /**
  60903. * Creates a sphere mesh
  60904. * * The parameter `diameter` sets the diameter size (float) of the sphere (default 1)
  60905. * * You can set some different sphere dimensions, for instance to build an ellipsoid, by using the parameters `diameterX`, `diameterY` and `diameterZ` (all by default have the same value than `diameter`)
  60906. * * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32)
  60907. * * 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
  60908. * * 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)
  60909. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60910. * * 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
  60911. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60912. * @param name defines the name of the mesh
  60913. * @param options defines the options used to create the mesh
  60914. * @param scene defines the hosting scene
  60915. * @returns the sphere mesh
  60916. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#sphere
  60917. */
  60918. MeshBuilder.CreateSphere = function (name, options, scene) {
  60919. var sphere = new BABYLON.Mesh(name, scene);
  60920. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60921. sphere._originalBuilderSideOrientation = options.sideOrientation;
  60922. var vertexData = BABYLON.VertexData.CreateSphere(options);
  60923. vertexData.applyToMesh(sphere, options.updatable);
  60924. return sphere;
  60925. };
  60926. /**
  60927. * Creates a plane polygonal mesh. By default, this is a disc
  60928. * * The parameter `radius` sets the radius size (float) of the polygon (default 0.5)
  60929. * * 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
  60930. * * 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
  60931. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60932. * * 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
  60933. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60934. * @param name defines the name of the mesh
  60935. * @param options defines the options used to create the mesh
  60936. * @param scene defines the hosting scene
  60937. * @returns the plane polygonal mesh
  60938. * @see http://doc.babylonjs.com/how_to/set_shapes#disc-or-regular-polygon
  60939. */
  60940. MeshBuilder.CreateDisc = function (name, options, scene) {
  60941. if (scene === void 0) { scene = null; }
  60942. var disc = new BABYLON.Mesh(name, scene);
  60943. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60944. disc._originalBuilderSideOrientation = options.sideOrientation;
  60945. var vertexData = BABYLON.VertexData.CreateDisc(options);
  60946. vertexData.applyToMesh(disc, options.updatable);
  60947. return disc;
  60948. };
  60949. /**
  60950. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided
  60951. * * The parameter `radius` sets the radius size (float) of the icosphere (default 1)
  60952. * * 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`)
  60953. * * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size
  60954. * * 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
  60955. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60956. * * 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
  60957. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60958. * @param name defines the name of the mesh
  60959. * @param options defines the options used to create the mesh
  60960. * @param scene defines the hosting scene
  60961. * @returns the icosahedron mesh
  60962. * @see http://doc.babylonjs.com/how_to/polyhedra_shapes#icosphere
  60963. */
  60964. MeshBuilder.CreateIcoSphere = function (name, options, scene) {
  60965. var sphere = new BABYLON.Mesh(name, scene);
  60966. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60967. sphere._originalBuilderSideOrientation = options.sideOrientation;
  60968. var vertexData = BABYLON.VertexData.CreateIcoSphere(options);
  60969. vertexData.applyToMesh(sphere, options.updatable);
  60970. return sphere;
  60971. };
  60972. ;
  60973. /**
  60974. * Creates a ribbon mesh. The ribbon is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters
  60975. * * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry
  60976. * * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array
  60977. * * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array
  60978. * * 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
  60979. * * 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
  60980. * * 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
  60981. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60982. * * 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
  60983. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  60984. * * 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
  60985. * * The parameters `colors` is an optional flat array of `Color4` to set/update each ribbon vertex with its own custom color values
  60986. * * 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
  60987. * * Moreover, you can use the parameter `color` with `instance` (to update the ribbon), only if you previously used it at creation time
  60988. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60989. * @param name defines the name of the mesh
  60990. * @param options defines the options used to create the mesh
  60991. * @param scene defines the hosting scene
  60992. * @returns the ribbon mesh
  60993. * @see http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  60994. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  60995. */
  60996. MeshBuilder.CreateRibbon = function (name, options, scene) {
  60997. if (scene === void 0) { scene = null; }
  60998. var pathArray = options.pathArray;
  60999. var closeArray = options.closeArray;
  61000. var closePath = options.closePath;
  61001. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61002. var instance = options.instance;
  61003. var updatable = options.updatable;
  61004. if (instance) { // existing ribbon instance update
  61005. // positionFunction : ribbon case
  61006. // only pathArray and sideOrientation parameters are taken into account for positions update
  61007. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, BABYLON.Tmp.Vector3[0]); // minimum
  61008. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, BABYLON.Tmp.Vector3[1]);
  61009. var positionFunction = function (positions) {
  61010. var minlg = pathArray[0].length;
  61011. var i = 0;
  61012. var ns = (instance._originalBuilderSideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  61013. for (var si = 1; si <= ns; si++) {
  61014. for (var p = 0; p < pathArray.length; p++) {
  61015. var path = pathArray[p];
  61016. var l = path.length;
  61017. minlg = (minlg < l) ? minlg : l;
  61018. var j = 0;
  61019. while (j < minlg) {
  61020. positions[i] = path[j].x;
  61021. positions[i + 1] = path[j].y;
  61022. positions[i + 2] = path[j].z;
  61023. if (path[j].x < BABYLON.Tmp.Vector3[0].x) {
  61024. BABYLON.Tmp.Vector3[0].x = path[j].x;
  61025. }
  61026. if (path[j].x > BABYLON.Tmp.Vector3[1].x) {
  61027. BABYLON.Tmp.Vector3[1].x = path[j].x;
  61028. }
  61029. if (path[j].y < BABYLON.Tmp.Vector3[0].y) {
  61030. BABYLON.Tmp.Vector3[0].y = path[j].y;
  61031. }
  61032. if (path[j].y > BABYLON.Tmp.Vector3[1].y) {
  61033. BABYLON.Tmp.Vector3[1].y = path[j].y;
  61034. }
  61035. if (path[j].z < BABYLON.Tmp.Vector3[0].z) {
  61036. BABYLON.Tmp.Vector3[0].z = path[j].z;
  61037. }
  61038. if (path[j].z > BABYLON.Tmp.Vector3[1].z) {
  61039. BABYLON.Tmp.Vector3[1].z = path[j].z;
  61040. }
  61041. j++;
  61042. i += 3;
  61043. }
  61044. if (instance._closePath) {
  61045. positions[i] = path[0].x;
  61046. positions[i + 1] = path[0].y;
  61047. positions[i + 2] = path[0].z;
  61048. i += 3;
  61049. }
  61050. }
  61051. }
  61052. };
  61053. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  61054. positionFunction(positions);
  61055. instance._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Vector3[1]);
  61056. instance._boundingInfo.update(instance._worldMatrix);
  61057. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  61058. if (options.colors) {
  61059. var colors = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  61060. for (var c = 0; c < options.colors.length; c++) {
  61061. colors[c * 4] = options.colors[c].r;
  61062. colors[c * 4 + 1] = options.colors[c].g;
  61063. colors[c * 4 + 2] = options.colors[c].b;
  61064. colors[c * 4 + 3] = options.colors[c].a;
  61065. }
  61066. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, colors, false, false);
  61067. }
  61068. if (options.uvs) {
  61069. var uvs = instance.getVerticesData(BABYLON.VertexBuffer.UVKind);
  61070. for (var i = 0; i < options.uvs.length; i++) {
  61071. uvs[i * 2] = options.uvs[i].x;
  61072. uvs[i * 2 + 1] = options.uvs[i].y;
  61073. }
  61074. instance.updateVerticesData(BABYLON.VertexBuffer.UVKind, uvs, false, false);
  61075. }
  61076. if (!instance.areNormalsFrozen || instance.isFacetDataEnabled) {
  61077. var indices = instance.getIndices();
  61078. var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  61079. var params = instance.isFacetDataEnabled ? instance.getFacetDataParameters() : null;
  61080. BABYLON.VertexData.ComputeNormals(positions, indices, normals, params);
  61081. if (instance._closePath) {
  61082. var indexFirst = 0;
  61083. var indexLast = 0;
  61084. for (var p = 0; p < pathArray.length; p++) {
  61085. indexFirst = instance._idx[p] * 3;
  61086. if (p + 1 < pathArray.length) {
  61087. indexLast = (instance._idx[p + 1] - 1) * 3;
  61088. }
  61089. else {
  61090. indexLast = normals.length - 3;
  61091. }
  61092. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  61093. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  61094. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  61095. normals[indexLast] = normals[indexFirst];
  61096. normals[indexLast + 1] = normals[indexFirst + 1];
  61097. normals[indexLast + 2] = normals[indexFirst + 2];
  61098. }
  61099. }
  61100. if (!(instance.areNormalsFrozen)) {
  61101. instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  61102. }
  61103. }
  61104. return instance;
  61105. }
  61106. else { // new ribbon creation
  61107. var ribbon = new BABYLON.Mesh(name, scene);
  61108. ribbon._originalBuilderSideOrientation = sideOrientation;
  61109. var vertexData = BABYLON.VertexData.CreateRibbon(options);
  61110. if (closePath) {
  61111. ribbon._idx = vertexData._idx;
  61112. }
  61113. ribbon._closePath = closePath;
  61114. ribbon._closeArray = closeArray;
  61115. vertexData.applyToMesh(ribbon, updatable);
  61116. return ribbon;
  61117. }
  61118. };
  61119. /**
  61120. * Creates a cylinder or a cone mesh
  61121. * * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  61122. * * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  61123. * * 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.
  61124. * * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  61125. * * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  61126. * * The parameter `hasRings` (boolean, default false) makes the subdivisions independent from each other, so they become different faces.
  61127. * * The parameter `enclose` (boolean, default false) adds two extra faces per subdivision to a sliced cylinder to close it around its height axis.
  61128. * * The parameter `arc` (float, default 1) is the ratio (max 1) to apply to the circumference to slice the cylinder.
  61129. * * 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).
  61130. * * 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
  61131. * * Now, if the cylinder has 5 independent subdivisions (hasRings = true), n equals : top face + 5 stripe surfaces + bottom face = 2 + 5 = 7
  61132. * * 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
  61133. * * 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.
  61134. * * If `enclose` is false, a ring surface is one element.
  61135. * * If `enclose` is true, a ring surface is 3 successive elements in the array : the tubular surface, then the two closing faces.
  61136. * * 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
  61137. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61138. * * 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
  61139. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  61140. * @param name defines the name of the mesh
  61141. * @param options defines the options used to create the mesh
  61142. * @param scene defines the hosting scene
  61143. * @returns the cylinder mesh
  61144. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#cylinder-or-cone
  61145. */
  61146. MeshBuilder.CreateCylinder = function (name, options, scene) {
  61147. var cylinder = new BABYLON.Mesh(name, scene);
  61148. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61149. cylinder._originalBuilderSideOrientation = options.sideOrientation;
  61150. var vertexData = BABYLON.VertexData.CreateCylinder(options);
  61151. vertexData.applyToMesh(cylinder, options.updatable);
  61152. return cylinder;
  61153. };
  61154. /**
  61155. * Creates a torus mesh
  61156. * * The parameter `diameter` sets the diameter size (float) of the torus (default 1)
  61157. * * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5)
  61158. * * The parameter `tessellation` sets the number of torus sides (postive integer, default 16)
  61159. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61160. * * 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
  61161. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  61162. * @param name defines the name of the mesh
  61163. * @param options defines the options used to create the mesh
  61164. * @param scene defines the hosting scene
  61165. * @returns the torus mesh
  61166. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus
  61167. */
  61168. MeshBuilder.CreateTorus = function (name, options, scene) {
  61169. var torus = new BABYLON.Mesh(name, scene);
  61170. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61171. torus._originalBuilderSideOrientation = options.sideOrientation;
  61172. var vertexData = BABYLON.VertexData.CreateTorus(options);
  61173. vertexData.applyToMesh(torus, options.updatable);
  61174. return torus;
  61175. };
  61176. /**
  61177. * Creates a torus knot mesh
  61178. * * The parameter `radius` sets the global radius size (float) of the torus knot (default 2)
  61179. * * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32)
  61180. * * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32)
  61181. * * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3)
  61182. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61183. * * 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
  61184. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  61185. * @param name defines the name of the mesh
  61186. * @param options defines the options used to create the mesh
  61187. * @param scene defines the hosting scene
  61188. * @returns the torus knot mesh
  61189. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus-knot
  61190. */
  61191. MeshBuilder.CreateTorusKnot = function (name, options, scene) {
  61192. var torusKnot = new BABYLON.Mesh(name, scene);
  61193. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61194. torusKnot._originalBuilderSideOrientation = options.sideOrientation;
  61195. var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
  61196. vertexData.applyToMesh(torusKnot, options.updatable);
  61197. return torusKnot;
  61198. };
  61199. /**
  61200. * Creates a line system mesh. A line system is a pool of many lines gathered in a single mesh
  61201. * * 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
  61202. * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineSystem to this static function
  61203. * * The parameter `lines` is an array of lines, each line being an array of successive Vector3
  61204. * * The optional parameter `instance` is an instance of an existing LineSystem object to be updated with the passed `lines` parameter
  61205. * * The optional parameter `colors` is an array of line colors, each line colors being an array of successive Color4, one per line point
  61206. * * The optional parameter `useVertexAlpha` is to be set to `false` (default `true`) when you don't need the alpha blending (faster)
  61207. * * 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
  61208. * * When updating an instance, remember that only line point positions can change, not the number of points, neither the number of lines
  61209. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61210. * @see http://doc.babylonjs.com/how_to/parametric_shapes#line-system
  61211. * @param name defines the name of the new line system
  61212. * @param options defines the options used to create the line system
  61213. * @param scene defines the hosting scene
  61214. * @returns a new line system mesh
  61215. */
  61216. MeshBuilder.CreateLineSystem = function (name, options, scene) {
  61217. var instance = options.instance;
  61218. var lines = options.lines;
  61219. var colors = options.colors;
  61220. if (instance) { // lines update
  61221. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  61222. var vertexColor;
  61223. var lineColors;
  61224. if (colors) {
  61225. vertexColor = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  61226. }
  61227. var i = 0;
  61228. var c = 0;
  61229. for (var l = 0; l < lines.length; l++) {
  61230. var points = lines[l];
  61231. for (var p = 0; p < points.length; p++) {
  61232. positions[i] = points[p].x;
  61233. positions[i + 1] = points[p].y;
  61234. positions[i + 2] = points[p].z;
  61235. if (colors && vertexColor) {
  61236. lineColors = colors[l];
  61237. vertexColor[c] = lineColors[p].r;
  61238. vertexColor[c + 1] = lineColors[p].g;
  61239. vertexColor[c + 2] = lineColors[p].b;
  61240. vertexColor[c + 3] = lineColors[p].a;
  61241. c += 4;
  61242. }
  61243. i += 3;
  61244. }
  61245. }
  61246. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  61247. if (colors && vertexColor) {
  61248. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, vertexColor, false, false);
  61249. }
  61250. return instance;
  61251. }
  61252. // line system creation
  61253. var useVertexColor = (colors) ? true : false;
  61254. var lineSystem = new BABYLON.LinesMesh(name, scene, null, undefined, undefined, useVertexColor, options.useVertexAlpha);
  61255. var vertexData = BABYLON.VertexData.CreateLineSystem(options);
  61256. vertexData.applyToMesh(lineSystem, options.updatable);
  61257. return lineSystem;
  61258. };
  61259. /**
  61260. * Creates a line mesh
  61261. * 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
  61262. * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function
  61263. * * The parameter `points` is an array successive Vector3
  61264. * * 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
  61265. * * The optional parameter `colors` is an array of successive Color4, one per line point
  61266. * * The optional parameter `useVertexAlpha` is to be set to `false` (default `true`) when you don't need alpha blending (faster)
  61267. * * When updating an instance, remember that only point positions can change, not the number of points
  61268. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61269. * @see http://doc.babylonjs.com/how_to/parametric_shapes#lines
  61270. * @param name defines the name of the new line system
  61271. * @param options defines the options used to create the line system
  61272. * @param scene defines the hosting scene
  61273. * @returns a new line mesh
  61274. */
  61275. MeshBuilder.CreateLines = function (name, options, scene) {
  61276. if (scene === void 0) { scene = null; }
  61277. var colors = (options.colors) ? [options.colors] : null;
  61278. var lines = MeshBuilder.CreateLineSystem(name, { lines: [options.points], updatable: options.updatable, instance: options.instance, colors: colors, useVertexAlpha: options.useVertexAlpha }, scene);
  61279. return lines;
  61280. };
  61281. /**
  61282. * Creates a dashed line mesh
  61283. * * 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
  61284. * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function
  61285. * * The parameter `points` is an array successive Vector3
  61286. * * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200)
  61287. * * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3)
  61288. * * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1)
  61289. * * 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
  61290. * * When updating an instance, remember that only point positions can change, not the number of points
  61291. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61292. * @param name defines the name of the mesh
  61293. * @param options defines the options used to create the mesh
  61294. * @param scene defines the hosting scene
  61295. * @returns the dashed line mesh
  61296. * @see http://doc.babylonjs.com/how_to/parametric_shapes#dashed-lines
  61297. */
  61298. MeshBuilder.CreateDashedLines = function (name, options, scene) {
  61299. if (scene === void 0) { scene = null; }
  61300. var points = options.points;
  61301. var instance = options.instance;
  61302. var gapSize = options.gapSize || 1;
  61303. var dashSize = options.dashSize || 3;
  61304. if (instance) { // dashed lines update
  61305. var positionFunction = function (positions) {
  61306. var curvect = BABYLON.Vector3.Zero();
  61307. var nbSeg = positions.length / 6;
  61308. var lg = 0;
  61309. var nb = 0;
  61310. var shft = 0;
  61311. var dashshft = 0;
  61312. var curshft = 0;
  61313. var p = 0;
  61314. var i = 0;
  61315. var j = 0;
  61316. for (i = 0; i < points.length - 1; i++) {
  61317. points[i + 1].subtractToRef(points[i], curvect);
  61318. lg += curvect.length();
  61319. }
  61320. shft = lg / nbSeg;
  61321. dashshft = instance.dashSize * shft / (instance.dashSize + instance.gapSize);
  61322. for (i = 0; i < points.length - 1; i++) {
  61323. points[i + 1].subtractToRef(points[i], curvect);
  61324. nb = Math.floor(curvect.length() / shft);
  61325. curvect.normalize();
  61326. j = 0;
  61327. while (j < nb && p < positions.length) {
  61328. curshft = shft * j;
  61329. positions[p] = points[i].x + curshft * curvect.x;
  61330. positions[p + 1] = points[i].y + curshft * curvect.y;
  61331. positions[p + 2] = points[i].z + curshft * curvect.z;
  61332. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  61333. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  61334. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  61335. p += 6;
  61336. j++;
  61337. }
  61338. }
  61339. while (p < positions.length) {
  61340. positions[p] = points[i].x;
  61341. positions[p + 1] = points[i].y;
  61342. positions[p + 2] = points[i].z;
  61343. p += 3;
  61344. }
  61345. };
  61346. instance.updateMeshPositions(positionFunction, false);
  61347. return instance;
  61348. }
  61349. // dashed lines creation
  61350. var dashedLines = new BABYLON.LinesMesh(name, scene);
  61351. var vertexData = BABYLON.VertexData.CreateDashedLines(options);
  61352. vertexData.applyToMesh(dashedLines, options.updatable);
  61353. dashedLines.dashSize = dashSize;
  61354. dashedLines.gapSize = gapSize;
  61355. return dashedLines;
  61356. };
  61357. /**
  61358. * 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.
  61359. * * 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.
  61360. * * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  61361. * * 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.
  61362. * * The parameter `scale` (float, default 1) is the value to scale the shape.
  61363. * * 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
  61364. * * 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
  61365. * * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  61366. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61367. * * 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
  61368. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  61369. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  61370. * @param name defines the name of the mesh
  61371. * @param options defines the options used to create the mesh
  61372. * @param scene defines the hosting scene
  61373. * @returns the extruded shape mesh
  61374. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  61375. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  61376. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  61377. */
  61378. MeshBuilder.ExtrudeShape = function (name, options, scene) {
  61379. if (scene === void 0) { scene = null; }
  61380. var path = options.path;
  61381. var shape = options.shape;
  61382. var scale = options.scale || 1;
  61383. var rotation = options.rotation || 0;
  61384. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  61385. var updatable = options.updatable;
  61386. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61387. var instance = options.instance || null;
  61388. var invertUV = options.invertUV || false;
  61389. 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);
  61390. };
  61391. /**
  61392. * Creates an custom extruded shape mesh.
  61393. * The custom extrusion is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters.
  61394. * * 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.
  61395. * * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  61396. * * 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
  61397. * * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  61398. * * 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
  61399. * * It must returns a float value that will be the scale value applied to the shape on each path point
  61400. * * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`
  61401. * * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`
  61402. * * 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
  61403. * * 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
  61404. * * Remember you can only change the shape or path point positions, not their number when updating an extruded shape
  61405. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61406. * * 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
  61407. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  61408. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61409. * @param name defines the name of the mesh
  61410. * @param options defines the options used to create the mesh
  61411. * @param scene defines the hosting scene
  61412. * @returns the custom extruded shape mesh
  61413. * @see http://doc.babylonjs.com/how_to/parametric_shapes#custom-extruded-shapes
  61414. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  61415. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  61416. */
  61417. MeshBuilder.ExtrudeShapeCustom = function (name, options, scene) {
  61418. var path = options.path;
  61419. var shape = options.shape;
  61420. var scaleFunction = options.scaleFunction || (function () { return 1; });
  61421. var rotationFunction = options.rotationFunction || (function () { return 0; });
  61422. var ribbonCloseArray = options.ribbonCloseArray || false;
  61423. var ribbonClosePath = options.ribbonClosePath || false;
  61424. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  61425. var updatable = options.updatable;
  61426. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61427. var instance = options.instance;
  61428. var invertUV = options.invertUV || false;
  61429. 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);
  61430. };
  61431. /**
  61432. * Creates lathe mesh.
  61433. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe
  61434. * * 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
  61435. * * The parameter `radius` (positive float, default 1) is the radius value of the lathe
  61436. * * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe
  61437. * * 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
  61438. * * The parameter `closed` (boolean, default true) opens/closes the lathe circumference. This should be set to false when used with the parameter "arc"
  61439. * * 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
  61440. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61441. * * 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
  61442. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  61443. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61444. * @param name defines the name of the mesh
  61445. * @param options defines the options used to create the mesh
  61446. * @param scene defines the hosting scene
  61447. * @returns the lathe mesh
  61448. * @see http://doc.babylonjs.com/how_to/parametric_shapes#lathe
  61449. */
  61450. MeshBuilder.CreateLathe = function (name, options, scene) {
  61451. var arc = options.arc ? ((options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc) : 1.0;
  61452. var closed = (options.closed === undefined) ? true : options.closed;
  61453. var shape = options.shape;
  61454. var radius = options.radius || 1;
  61455. var tessellation = options.tessellation || 64;
  61456. var updatable = options.updatable;
  61457. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61458. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  61459. var pi2 = Math.PI * 2;
  61460. var paths = new Array();
  61461. var invertUV = options.invertUV || false;
  61462. var i = 0;
  61463. var p = 0;
  61464. var step = pi2 / tessellation * arc;
  61465. var rotated;
  61466. var path = new Array();
  61467. for (i = 0; i <= tessellation; i++) {
  61468. var path = [];
  61469. if (cap == BABYLON.Mesh.CAP_START || cap == BABYLON.Mesh.CAP_ALL) {
  61470. path.push(new BABYLON.Vector3(0, shape[0].y, 0));
  61471. path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[0].x * radius, shape[0].y, Math.sin(i * step) * shape[0].x * radius));
  61472. }
  61473. for (p = 0; p < shape.length; p++) {
  61474. rotated = new BABYLON.Vector3(Math.cos(i * step) * shape[p].x * radius, shape[p].y, Math.sin(i * step) * shape[p].x * radius);
  61475. path.push(rotated);
  61476. }
  61477. if (cap == BABYLON.Mesh.CAP_END || cap == BABYLON.Mesh.CAP_ALL) {
  61478. 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));
  61479. path.push(new BABYLON.Vector3(0, shape[shape.length - 1].y, 0));
  61480. }
  61481. paths.push(path);
  61482. }
  61483. // lathe ribbon
  61484. var lathe = MeshBuilder.CreateRibbon(name, { pathArray: paths, closeArray: closed, sideOrientation: sideOrientation, updatable: updatable, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  61485. return lathe;
  61486. };
  61487. /**
  61488. * Creates a plane mesh
  61489. * * The parameter `size` sets the size (float) of both sides of the plane at once (default 1)
  61490. * * You can set some different plane dimensions by using the parameters `width` and `height` (both by default have the same value than `size`)
  61491. * * The parameter `sourcePlane` is a Plane instance. It builds a mesh plane from a Math plane
  61492. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61493. * * 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
  61494. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61495. * @param name defines the name of the mesh
  61496. * @param options defines the options used to create the mesh
  61497. * @param scene defines the hosting scene
  61498. * @returns the plane mesh
  61499. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  61500. */
  61501. MeshBuilder.CreatePlane = function (name, options, scene) {
  61502. var plane = new BABYLON.Mesh(name, scene);
  61503. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61504. plane._originalBuilderSideOrientation = options.sideOrientation;
  61505. var vertexData = BABYLON.VertexData.CreatePlane(options);
  61506. vertexData.applyToMesh(plane, options.updatable);
  61507. if (options.sourcePlane) {
  61508. plane.translate(options.sourcePlane.normal, options.sourcePlane.d);
  61509. var product = Math.acos(BABYLON.Vector3.Dot(options.sourcePlane.normal, BABYLON.Axis.Z));
  61510. var vectorProduct = BABYLON.Vector3.Cross(BABYLON.Axis.Z, options.sourcePlane.normal);
  61511. plane.rotate(vectorProduct, product);
  61512. }
  61513. return plane;
  61514. };
  61515. /**
  61516. * Creates a ground mesh
  61517. * * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground
  61518. * * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side
  61519. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61520. * @param name defines the name of the mesh
  61521. * @param options defines the options used to create the mesh
  61522. * @param scene defines the hosting scene
  61523. * @returns the ground mesh
  61524. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  61525. */
  61526. MeshBuilder.CreateGround = function (name, options, scene) {
  61527. var ground = new BABYLON.GroundMesh(name, scene);
  61528. ground._setReady(false);
  61529. ground._subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  61530. ground._subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  61531. ground._width = options.width || 1;
  61532. ground._height = options.height || 1;
  61533. ground._maxX = ground._width / 2;
  61534. ground._maxZ = ground._height / 2;
  61535. ground._minX = -ground._maxX;
  61536. ground._minZ = -ground._maxZ;
  61537. var vertexData = BABYLON.VertexData.CreateGround(options);
  61538. vertexData.applyToMesh(ground, options.updatable);
  61539. ground._setReady(true);
  61540. return ground;
  61541. };
  61542. /**
  61543. * Creates a tiled ground mesh
  61544. * * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates
  61545. * * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates
  61546. * * 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
  61547. * * 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
  61548. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  61549. * @param name defines the name of the mesh
  61550. * @param options defines the options used to create the mesh
  61551. * @param scene defines the hosting scene
  61552. * @returns the tiled ground mesh
  61553. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tiled-ground
  61554. */
  61555. MeshBuilder.CreateTiledGround = function (name, options, scene) {
  61556. var tiledGround = new BABYLON.Mesh(name, scene);
  61557. var vertexData = BABYLON.VertexData.CreateTiledGround(options);
  61558. vertexData.applyToMesh(tiledGround, options.updatable);
  61559. return tiledGround;
  61560. };
  61561. /**
  61562. * Creates a ground mesh from a height map
  61563. * * The parameter `url` sets the URL of the height map image resource.
  61564. * * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  61565. * * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  61566. * * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  61567. * * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  61568. * * 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.
  61569. * * 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).
  61570. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  61571. * @param name defines the name of the mesh
  61572. * @param url defines the url to the height map
  61573. * @param options defines the options used to create the mesh
  61574. * @param scene defines the hosting scene
  61575. * @returns the ground mesh
  61576. * @see http://doc.babylonjs.com/babylon101/height_map
  61577. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#ground-from-a-height-map
  61578. */
  61579. MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) {
  61580. var width = options.width || 10.0;
  61581. var height = options.height || 10.0;
  61582. var subdivisions = options.subdivisions || 1 | 0;
  61583. var minHeight = options.minHeight || 0.0;
  61584. var maxHeight = options.maxHeight || 1.0;
  61585. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  61586. var updatable = options.updatable;
  61587. var onReady = options.onReady;
  61588. var ground = new BABYLON.GroundMesh(name, scene);
  61589. ground._subdivisionsX = subdivisions;
  61590. ground._subdivisionsY = subdivisions;
  61591. ground._width = width;
  61592. ground._height = height;
  61593. ground._maxX = ground._width / 2.0;
  61594. ground._maxZ = ground._height / 2.0;
  61595. ground._minX = -ground._maxX;
  61596. ground._minZ = -ground._maxZ;
  61597. ground._setReady(false);
  61598. var onload = function (img) {
  61599. // Getting height map data
  61600. var canvas = document.createElement("canvas");
  61601. var context = canvas.getContext("2d");
  61602. if (!context) {
  61603. throw new Error("Unable to get 2d context for CreateGroundFromHeightMap");
  61604. }
  61605. if (scene.isDisposed) {
  61606. return;
  61607. }
  61608. var bufferWidth = img.width;
  61609. var bufferHeight = img.height;
  61610. canvas.width = bufferWidth;
  61611. canvas.height = bufferHeight;
  61612. context.drawImage(img, 0, 0);
  61613. // Create VertexData from map data
  61614. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  61615. var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
  61616. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
  61617. width: width, height: height,
  61618. subdivisions: subdivisions,
  61619. minHeight: minHeight, maxHeight: maxHeight, colorFilter: filter,
  61620. buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight
  61621. });
  61622. vertexData.applyToMesh(ground, updatable);
  61623. //execute ready callback, if set
  61624. if (onReady) {
  61625. onReady(ground);
  61626. }
  61627. ground._setReady(true);
  61628. };
  61629. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  61630. return ground;
  61631. };
  61632. /**
  61633. * Creates a polygon mesh
  61634. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh
  61635. * * 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
  61636. * * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61637. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61638. * * 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)
  61639. * * Remember you can only change the shape positions, not their number when updating a polygon
  61640. * @param name defines the name of the mesh
  61641. * @param options defines the options used to create the mesh
  61642. * @param scene defines the hosting scene
  61643. * @returns the polygon mesh
  61644. */
  61645. MeshBuilder.CreatePolygon = function (name, options, scene) {
  61646. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61647. var shape = options.shape;
  61648. var holes = options.holes || [];
  61649. var depth = options.depth || 0;
  61650. var contours = [];
  61651. var hole = [];
  61652. for (var i = 0; i < shape.length; i++) {
  61653. contours[i] = new BABYLON.Vector2(shape[i].x, shape[i].z);
  61654. }
  61655. var epsilon = 0.00000001;
  61656. if (contours[0].equalsWithEpsilon(contours[contours.length - 1], epsilon)) {
  61657. contours.pop();
  61658. }
  61659. var polygonTriangulation = new BABYLON.PolygonMeshBuilder(name, contours, scene);
  61660. for (var hNb = 0; hNb < holes.length; hNb++) {
  61661. hole = [];
  61662. for (var hPoint = 0; hPoint < holes[hNb].length; hPoint++) {
  61663. hole.push(new BABYLON.Vector2(holes[hNb][hPoint].x, holes[hNb][hPoint].z));
  61664. }
  61665. polygonTriangulation.addHole(hole);
  61666. }
  61667. var polygon = polygonTriangulation.build(options.updatable, depth);
  61668. polygon._originalBuilderSideOrientation = options.sideOrientation;
  61669. var vertexData = BABYLON.VertexData.CreatePolygon(polygon, options.sideOrientation, options.faceUV, options.faceColors, options.frontUVs, options.backUVs);
  61670. vertexData.applyToMesh(polygon, options.updatable);
  61671. return polygon;
  61672. };
  61673. ;
  61674. /**
  61675. * Creates an extruded polygon mesh, with depth in the Y direction.
  61676. * * 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)
  61677. * @see http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  61678. * @param name defines the name of the mesh
  61679. * @param options defines the options used to create the mesh
  61680. * @param scene defines the hosting scene
  61681. * @returns the polygon mesh
  61682. */
  61683. MeshBuilder.ExtrudePolygon = function (name, options, scene) {
  61684. return MeshBuilder.CreatePolygon(name, options, scene);
  61685. };
  61686. ;
  61687. /**
  61688. * Creates a tube mesh.
  61689. * The tube is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters
  61690. * * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube
  61691. * * The parameter `radius` (positive float, default 1) sets the tube radius size
  61692. * * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface
  61693. * * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`
  61694. * * 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)
  61695. * * The parameter `arc` (positive float, maximum 1, default 1) is the ratio to apply to the tube circumference : 2 x PI x arc
  61696. * * 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
  61697. * * 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
  61698. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61699. * * 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
  61700. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  61701. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61702. * @param name defines the name of the mesh
  61703. * @param options defines the options used to create the mesh
  61704. * @param scene defines the hosting scene
  61705. * @returns the tube mesh
  61706. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  61707. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tube
  61708. */
  61709. MeshBuilder.CreateTube = function (name, options, scene) {
  61710. var path = options.path;
  61711. var instance = options.instance;
  61712. var radius = 1.0;
  61713. if (instance) {
  61714. radius = instance.radius;
  61715. }
  61716. if (options.radius !== undefined) {
  61717. radius = options.radius;
  61718. }
  61719. ;
  61720. var tessellation = options.tessellation || 64 | 0;
  61721. var radiusFunction = options.radiusFunction || null;
  61722. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  61723. var invertUV = options.invertUV || false;
  61724. var updatable = options.updatable;
  61725. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61726. options.arc = options.arc && (options.arc <= 0.0 || options.arc > 1.0) ? 1.0 : options.arc || 1.0;
  61727. // tube geometry
  61728. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
  61729. var tangents = path3D.getTangents();
  61730. var normals = path3D.getNormals();
  61731. var distances = path3D.getDistances();
  61732. var pi2 = Math.PI * 2;
  61733. var step = pi2 / tessellation * arc;
  61734. var returnRadius = function () { return radius; };
  61735. var radiusFunctionFinal = radiusFunction || returnRadius;
  61736. var circlePath;
  61737. var rad;
  61738. var normal;
  61739. var rotated;
  61740. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  61741. var index = (cap === BABYLON.Mesh._NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  61742. for (var i = 0; i < path.length; i++) {
  61743. rad = radiusFunctionFinal(i, distances[i]); // current radius
  61744. circlePath = Array(); // current circle array
  61745. normal = normals[i]; // current normal
  61746. for (var t = 0; t < tessellation; t++) {
  61747. BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  61748. rotated = circlePath[t] ? circlePath[t] : BABYLON.Vector3.Zero();
  61749. BABYLON.Vector3.TransformCoordinatesToRef(normal, rotationMatrix, rotated);
  61750. rotated.scaleInPlace(rad).addInPlace(path[i]);
  61751. circlePath[t] = rotated;
  61752. }
  61753. circlePaths[index] = circlePath;
  61754. index++;
  61755. }
  61756. // cap
  61757. var capPath = function (nbPoints, pathIndex) {
  61758. var pointCap = Array();
  61759. for (var i = 0; i < nbPoints; i++) {
  61760. pointCap.push(path[pathIndex]);
  61761. }
  61762. return pointCap;
  61763. };
  61764. switch (cap) {
  61765. case BABYLON.Mesh.NO_CAP:
  61766. break;
  61767. case BABYLON.Mesh.CAP_START:
  61768. circlePaths[0] = capPath(tessellation, 0);
  61769. circlePaths[1] = circlePaths[2].slice(0);
  61770. break;
  61771. case BABYLON.Mesh.CAP_END:
  61772. circlePaths[index] = circlePaths[index - 1].slice(0);
  61773. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  61774. break;
  61775. case BABYLON.Mesh.CAP_ALL:
  61776. circlePaths[0] = capPath(tessellation, 0);
  61777. circlePaths[1] = circlePaths[2].slice(0);
  61778. circlePaths[index] = circlePaths[index - 1].slice(0);
  61779. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  61780. break;
  61781. default:
  61782. break;
  61783. }
  61784. return circlePaths;
  61785. };
  61786. var path3D;
  61787. var pathArray;
  61788. if (instance) { // tube update
  61789. var arc = options.arc || instance.arc;
  61790. path3D = (instance.path3D).update(path);
  61791. pathArray = tubePathArray(path, path3D, instance.pathArray, radius, instance.tessellation, radiusFunction, instance.cap, arc);
  61792. instance = MeshBuilder.CreateRibbon("", { pathArray: pathArray, instance: instance });
  61793. instance.path3D = path3D;
  61794. instance.pathArray = pathArray;
  61795. instance.arc = arc;
  61796. instance.radius = radius;
  61797. return instance;
  61798. }
  61799. // tube creation
  61800. path3D = new BABYLON.Path3D(path);
  61801. var newPathArray = new Array();
  61802. cap = (cap < 0 || cap > 3) ? 0 : cap;
  61803. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
  61804. var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  61805. tube.pathArray = pathArray;
  61806. tube.path3D = path3D;
  61807. tube.tessellation = tessellation;
  61808. tube.cap = cap;
  61809. tube.arc = options.arc;
  61810. tube.radius = radius;
  61811. return tube;
  61812. };
  61813. /**
  61814. * Creates a polyhedron mesh
  61815. * * 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
  61816. * * The parameter `size` (positive float, default 1) sets the polygon size
  61817. * * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value)
  61818. * * 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`
  61819. * * 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
  61820. * * 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)`)
  61821. * * 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
  61822. * * 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
  61823. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61824. * * 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
  61825. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61826. * @param name defines the name of the mesh
  61827. * @param options defines the options used to create the mesh
  61828. * @param scene defines the hosting scene
  61829. * @returns the polyhedron mesh
  61830. * @see http://doc.babylonjs.com/how_to/polyhedra_shapes
  61831. */
  61832. MeshBuilder.CreatePolyhedron = function (name, options, scene) {
  61833. var polyhedron = new BABYLON.Mesh(name, scene);
  61834. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61835. polyhedron._originalBuilderSideOrientation = options.sideOrientation;
  61836. var vertexData = BABYLON.VertexData.CreatePolyhedron(options);
  61837. vertexData.applyToMesh(polyhedron, options.updatable);
  61838. return polyhedron;
  61839. };
  61840. /**
  61841. * Creates a decal mesh.
  61842. * 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
  61843. * * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates
  61844. * * The parameter `normal` (Vector3, default `Vector3.Up`) sets the normal of the mesh where the decal is applied onto in World coordinates
  61845. * * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling
  61846. * * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal
  61847. * @param name defines the name of the mesh
  61848. * @param sourceMesh defines the mesh where the decal must be applied
  61849. * @param options defines the options used to create the mesh
  61850. * @param scene defines the hosting scene
  61851. * @returns the decal mesh
  61852. * @see http://doc.babylonjs.com/how_to/decals
  61853. */
  61854. MeshBuilder.CreateDecal = function (name, sourceMesh, options) {
  61855. var indices = sourceMesh.getIndices();
  61856. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  61857. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  61858. var position = options.position || BABYLON.Vector3.Zero();
  61859. var normal = options.normal || BABYLON.Vector3.Up();
  61860. var size = options.size || BABYLON.Vector3.One();
  61861. var angle = options.angle || 0;
  61862. // Getting correct rotation
  61863. if (!normal) {
  61864. var target = new BABYLON.Vector3(0, 0, 1);
  61865. var camera = sourceMesh.getScene().activeCamera;
  61866. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  61867. normal = camera.globalPosition.subtract(cameraWorldTarget);
  61868. }
  61869. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  61870. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  61871. var pitch = Math.atan2(normal.y, len);
  61872. // Matrix
  61873. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  61874. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  61875. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  61876. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  61877. var vertexData = new BABYLON.VertexData();
  61878. vertexData.indices = [];
  61879. vertexData.positions = [];
  61880. vertexData.normals = [];
  61881. vertexData.uvs = [];
  61882. var currentVertexDataIndex = 0;
  61883. var extractDecalVector3 = function (indexId) {
  61884. var result = new BABYLON.PositionNormalVertex();
  61885. if (!indices || !positions || !normals) {
  61886. return result;
  61887. }
  61888. var vertexId = indices[indexId];
  61889. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  61890. // Send vector to decal local world
  61891. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  61892. // Get normal
  61893. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  61894. result.normal = BABYLON.Vector3.TransformNormal(result.normal, transformMatrix);
  61895. return result;
  61896. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  61897. var clip = function (vertices, axis) {
  61898. if (vertices.length === 0) {
  61899. return vertices;
  61900. }
  61901. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  61902. var clipVertices = function (v0, v1) {
  61903. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  61904. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  61905. };
  61906. var result = new Array();
  61907. for (var index = 0; index < vertices.length; index += 3) {
  61908. var v1Out;
  61909. var v2Out;
  61910. var v3Out;
  61911. var total = 0;
  61912. var nV1 = null;
  61913. var nV2 = null;
  61914. var nV3 = null;
  61915. var nV4 = null;
  61916. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  61917. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  61918. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  61919. v1Out = d1 > 0;
  61920. v2Out = d2 > 0;
  61921. v3Out = d3 > 0;
  61922. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  61923. switch (total) {
  61924. case 0:
  61925. result.push(vertices[index]);
  61926. result.push(vertices[index + 1]);
  61927. result.push(vertices[index + 2]);
  61928. break;
  61929. case 1:
  61930. if (v1Out) {
  61931. nV1 = vertices[index + 1];
  61932. nV2 = vertices[index + 2];
  61933. nV3 = clipVertices(vertices[index], nV1);
  61934. nV4 = clipVertices(vertices[index], nV2);
  61935. }
  61936. if (v2Out) {
  61937. nV1 = vertices[index];
  61938. nV2 = vertices[index + 2];
  61939. nV3 = clipVertices(vertices[index + 1], nV1);
  61940. nV4 = clipVertices(vertices[index + 1], nV2);
  61941. result.push(nV3);
  61942. result.push(nV2.clone());
  61943. result.push(nV1.clone());
  61944. result.push(nV2.clone());
  61945. result.push(nV3.clone());
  61946. result.push(nV4);
  61947. break;
  61948. }
  61949. if (v3Out) {
  61950. nV1 = vertices[index];
  61951. nV2 = vertices[index + 1];
  61952. nV3 = clipVertices(vertices[index + 2], nV1);
  61953. nV4 = clipVertices(vertices[index + 2], nV2);
  61954. }
  61955. if (nV1 && nV2 && nV3 && nV4) {
  61956. result.push(nV1.clone());
  61957. result.push(nV2.clone());
  61958. result.push(nV3);
  61959. result.push(nV4);
  61960. result.push(nV3.clone());
  61961. result.push(nV2.clone());
  61962. }
  61963. break;
  61964. case 2:
  61965. if (!v1Out) {
  61966. nV1 = vertices[index].clone();
  61967. nV2 = clipVertices(nV1, vertices[index + 1]);
  61968. nV3 = clipVertices(nV1, vertices[index + 2]);
  61969. result.push(nV1);
  61970. result.push(nV2);
  61971. result.push(nV3);
  61972. }
  61973. if (!v2Out) {
  61974. nV1 = vertices[index + 1].clone();
  61975. nV2 = clipVertices(nV1, vertices[index + 2]);
  61976. nV3 = clipVertices(nV1, vertices[index]);
  61977. result.push(nV1);
  61978. result.push(nV2);
  61979. result.push(nV3);
  61980. }
  61981. if (!v3Out) {
  61982. nV1 = vertices[index + 2].clone();
  61983. nV2 = clipVertices(nV1, vertices[index]);
  61984. nV3 = clipVertices(nV1, vertices[index + 1]);
  61985. result.push(nV1);
  61986. result.push(nV2);
  61987. result.push(nV3);
  61988. }
  61989. break;
  61990. case 3:
  61991. break;
  61992. }
  61993. }
  61994. return result;
  61995. };
  61996. for (var index = 0; index < indices.length; index += 3) {
  61997. var faceVertices = new Array();
  61998. faceVertices.push(extractDecalVector3(index));
  61999. faceVertices.push(extractDecalVector3(index + 1));
  62000. faceVertices.push(extractDecalVector3(index + 2));
  62001. // Clip
  62002. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  62003. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  62004. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  62005. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  62006. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  62007. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  62008. if (faceVertices.length === 0) {
  62009. continue;
  62010. }
  62011. // Add UVs and get back to world
  62012. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  62013. var vertex = faceVertices[vIndex];
  62014. //TODO check for Int32Array | Uint32Array | Uint16Array
  62015. vertexData.indices.push(currentVertexDataIndex);
  62016. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  62017. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  62018. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  62019. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  62020. currentVertexDataIndex++;
  62021. }
  62022. }
  62023. // Return mesh
  62024. var decal = new BABYLON.Mesh(name, sourceMesh.getScene());
  62025. vertexData.applyToMesh(decal);
  62026. decal.position = position.clone();
  62027. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  62028. return decal;
  62029. };
  62030. // Privates
  62031. MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance, invertUV, frontUVs, backUVs) {
  62032. // extrusion geometry
  62033. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  62034. var tangents = path3D.getTangents();
  62035. var normals = path3D.getNormals();
  62036. var binormals = path3D.getBinormals();
  62037. var distances = path3D.getDistances();
  62038. var angle = 0;
  62039. var returnScale = function () { return scale !== null ? scale : 1; };
  62040. var returnRotation = function () { return rotation !== null ? rotation : 0; };
  62041. var rotate = custom && rotateFunction ? rotateFunction : returnRotation;
  62042. var scl = custom && scaleFunction ? scaleFunction : returnScale;
  62043. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  62044. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  62045. for (var i = 0; i < curve.length; i++) {
  62046. var shapePath = new Array();
  62047. var angleStep = rotate(i, distances[i]);
  62048. var scaleRatio = scl(i, distances[i]);
  62049. for (var p = 0; p < shape.length; p++) {
  62050. BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
  62051. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  62052. var rotated = shapePath[p] ? shapePath[p] : BABYLON.Vector3.Zero();
  62053. BABYLON.Vector3.TransformCoordinatesToRef(planed, rotationMatrix, rotated);
  62054. rotated.scaleInPlace(scaleRatio).addInPlace(curve[i]);
  62055. shapePath[p] = rotated;
  62056. }
  62057. shapePaths[index] = shapePath;
  62058. angle += angleStep;
  62059. index++;
  62060. }
  62061. // cap
  62062. var capPath = function (shapePath) {
  62063. var pointCap = Array();
  62064. var barycenter = BABYLON.Vector3.Zero();
  62065. var i;
  62066. for (i = 0; i < shapePath.length; i++) {
  62067. barycenter.addInPlace(shapePath[i]);
  62068. }
  62069. barycenter.scaleInPlace(1.0 / shapePath.length);
  62070. for (i = 0; i < shapePath.length; i++) {
  62071. pointCap.push(barycenter);
  62072. }
  62073. return pointCap;
  62074. };
  62075. switch (cap) {
  62076. case BABYLON.Mesh.NO_CAP:
  62077. break;
  62078. case BABYLON.Mesh.CAP_START:
  62079. shapePaths[0] = capPath(shapePaths[2]);
  62080. shapePaths[1] = shapePaths[2];
  62081. break;
  62082. case BABYLON.Mesh.CAP_END:
  62083. shapePaths[index] = shapePaths[index - 1];
  62084. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  62085. break;
  62086. case BABYLON.Mesh.CAP_ALL:
  62087. shapePaths[0] = capPath(shapePaths[2]);
  62088. shapePaths[1] = shapePaths[2];
  62089. shapePaths[index] = shapePaths[index - 1];
  62090. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  62091. break;
  62092. default:
  62093. break;
  62094. }
  62095. return shapePaths;
  62096. };
  62097. var path3D;
  62098. var pathArray;
  62099. if (instance) { // instance update
  62100. path3D = (instance.path3D).update(curve);
  62101. pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  62102. instance = BABYLON.Mesh.CreateRibbon("", pathArray, false, false, 0, scene || undefined, false, 0, instance);
  62103. return instance;
  62104. }
  62105. // extruded shape creation
  62106. path3D = new BABYLON.Path3D(curve);
  62107. var newShapePaths = new Array();
  62108. cap = (cap < 0 || cap > 3) ? 0 : cap;
  62109. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  62110. var extrudedGeneric = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closeArray: rbCA, closePath: rbCP, updatable: updtbl, sideOrientation: side, invertUV: invertUV, frontUVs: frontUVs || undefined, backUVs: backUVs || undefined }, scene);
  62111. extrudedGeneric.pathArray = pathArray;
  62112. extrudedGeneric.path3D = path3D;
  62113. extrudedGeneric.cap = cap;
  62114. return extrudedGeneric;
  62115. };
  62116. return MeshBuilder;
  62117. }());
  62118. BABYLON.MeshBuilder = MeshBuilder;
  62119. })(BABYLON || (BABYLON = {}));
  62120. //# sourceMappingURL=babylon.meshBuilder.js.map
  62121. var BABYLON;
  62122. (function (BABYLON) {
  62123. /**
  62124. * Draco compression (https://google.github.io/draco/)
  62125. *
  62126. * This class wraps the Draco module.
  62127. *
  62128. * **Encoder**
  62129. *
  62130. * The encoder is not currently implemented.
  62131. *
  62132. * **Decoder**
  62133. *
  62134. * By default, the configuration points to a copy of the Draco decoder files for glTF from https://preview.babylonjs.com.
  62135. *
  62136. * To update the configuration, use the following code:
  62137. * ```javascript
  62138. * BABYLON.DracoCompression.Configuration = {
  62139. * decoder: {
  62140. * wasmUrl: "<url to the WebAssembly library>",
  62141. * wasmBinaryUrl: "<url to the WebAssembly binary>",
  62142. * fallbackUrl: "<url to the fallback JavaScript library>",
  62143. * }
  62144. * };
  62145. * ```
  62146. *
  62147. * 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.
  62148. * Decoding will automatically fallback to the JavaScript version if WebAssembly version is not configured or if WebAssembly is not supported by the browser.
  62149. * Use `BABYLON.DracoCompression.DecoderAvailable` to determine if the decoder is available for the current session.
  62150. *
  62151. * To decode Draco compressed data, create a DracoCompression object and call decodeMeshAsync:
  62152. * ```javascript
  62153. * var dracoCompression = new BABYLON.DracoCompression();
  62154. * var vertexData = await dracoCompression.decodeMeshAsync(data, {
  62155. * [BABYLON.VertexBuffer.PositionKind]: 0
  62156. * });
  62157. * ```
  62158. *
  62159. * @see https://www.babylonjs-playground.com/#N3EK4B#0
  62160. */
  62161. var DracoCompression = /** @class */ (function () {
  62162. /**
  62163. * Constructor
  62164. */
  62165. function DracoCompression() {
  62166. }
  62167. Object.defineProperty(DracoCompression, "DecoderAvailable", {
  62168. /**
  62169. * Returns true if the decoder is available.
  62170. */
  62171. get: function () {
  62172. if (typeof DracoDecoderModule !== "undefined") {
  62173. return true;
  62174. }
  62175. var decoder = DracoCompression.Configuration.decoder;
  62176. if (decoder) {
  62177. if (decoder.wasmUrl && decoder.wasmBinaryUrl && typeof WebAssembly === "object") {
  62178. return true;
  62179. }
  62180. if (decoder.fallbackUrl) {
  62181. return true;
  62182. }
  62183. }
  62184. return false;
  62185. },
  62186. enumerable: true,
  62187. configurable: true
  62188. });
  62189. /**
  62190. * Stop all async operations and release resources.
  62191. */
  62192. DracoCompression.prototype.dispose = function () {
  62193. };
  62194. /**
  62195. * Decode Draco compressed mesh data to vertex data.
  62196. * @param data The ArrayBuffer or ArrayBufferView for the Draco compression data
  62197. * @param attributes A map of attributes from vertex buffer kinds to Draco unique ids
  62198. * @returns A promise that resolves with the decoded vertex data
  62199. */
  62200. DracoCompression.prototype.decodeMeshAsync = function (data, attributes) {
  62201. var dataView = data instanceof ArrayBuffer ? new Uint8Array(data) : data;
  62202. return DracoCompression._GetDecoderModule().then(function (wrappedModule) {
  62203. var module = wrappedModule.module;
  62204. var vertexData = new BABYLON.VertexData();
  62205. var buffer = new module.DecoderBuffer();
  62206. buffer.Init(dataView, dataView.byteLength);
  62207. var decoder = new module.Decoder();
  62208. var geometry;
  62209. var status;
  62210. try {
  62211. var type = decoder.GetEncodedGeometryType(buffer);
  62212. switch (type) {
  62213. case module.TRIANGULAR_MESH:
  62214. geometry = new module.Mesh();
  62215. status = decoder.DecodeBufferToMesh(buffer, geometry);
  62216. break;
  62217. case module.POINT_CLOUD:
  62218. geometry = new module.PointCloud();
  62219. status = decoder.DecodeBufferToPointCloud(buffer, geometry);
  62220. break;
  62221. default:
  62222. throw new Error("Invalid geometry type " + type);
  62223. }
  62224. if (!status.ok() || !geometry.ptr) {
  62225. throw new Error(status.error_msg());
  62226. }
  62227. var numPoints = geometry.num_points();
  62228. if (type === module.TRIANGULAR_MESH) {
  62229. var numFaces = geometry.num_faces();
  62230. var faceIndices = new module.DracoInt32Array();
  62231. try {
  62232. var indices = new Uint32Array(numFaces * 3);
  62233. for (var i = 0; i < numFaces; i++) {
  62234. decoder.GetFaceFromMesh(geometry, i, faceIndices);
  62235. var offset = i * 3;
  62236. indices[offset + 0] = faceIndices.GetValue(0);
  62237. indices[offset + 1] = faceIndices.GetValue(1);
  62238. indices[offset + 2] = faceIndices.GetValue(2);
  62239. }
  62240. vertexData.indices = indices;
  62241. }
  62242. finally {
  62243. module.destroy(faceIndices);
  62244. }
  62245. }
  62246. for (var kind in attributes) {
  62247. var uniqueId = attributes[kind];
  62248. var attribute = decoder.GetAttributeByUniqueId(geometry, uniqueId);
  62249. var dracoData = new module.DracoFloat32Array();
  62250. try {
  62251. decoder.GetAttributeFloatForAllPoints(geometry, attribute, dracoData);
  62252. var babylonData = new Float32Array(numPoints * attribute.num_components());
  62253. for (var i = 0; i < babylonData.length; i++) {
  62254. babylonData[i] = dracoData.GetValue(i);
  62255. }
  62256. vertexData.set(babylonData, kind);
  62257. }
  62258. finally {
  62259. module.destroy(dracoData);
  62260. }
  62261. }
  62262. }
  62263. finally {
  62264. if (geometry) {
  62265. module.destroy(geometry);
  62266. }
  62267. module.destroy(decoder);
  62268. module.destroy(buffer);
  62269. }
  62270. return vertexData;
  62271. });
  62272. };
  62273. DracoCompression._GetDecoderModule = function () {
  62274. if (!DracoCompression._DecoderModulePromise) {
  62275. var promise = null;
  62276. var config_1 = {};
  62277. if (typeof DracoDecoderModule !== "undefined") {
  62278. promise = Promise.resolve();
  62279. }
  62280. else {
  62281. var decoder = DracoCompression.Configuration.decoder;
  62282. if (decoder) {
  62283. if (decoder.wasmUrl && decoder.wasmBinaryUrl && typeof WebAssembly === "object") {
  62284. promise = Promise.all([
  62285. DracoCompression._LoadScriptAsync(decoder.wasmUrl),
  62286. DracoCompression._LoadFileAsync(decoder.wasmBinaryUrl).then(function (data) {
  62287. config_1.wasmBinary = data;
  62288. })
  62289. ]);
  62290. }
  62291. else if (decoder.fallbackUrl) {
  62292. promise = DracoCompression._LoadScriptAsync(decoder.fallbackUrl);
  62293. }
  62294. }
  62295. }
  62296. if (!promise) {
  62297. throw new Error("Draco decoder module is not available");
  62298. }
  62299. DracoCompression._DecoderModulePromise = promise.then(function () {
  62300. return new Promise(function (resolve) {
  62301. config_1.onModuleLoaded = function (decoderModule) {
  62302. // decoderModule is Promise-like. Wrap before resolving to avoid loop.
  62303. resolve({ module: decoderModule });
  62304. };
  62305. DracoDecoderModule(config_1);
  62306. });
  62307. });
  62308. }
  62309. return DracoCompression._DecoderModulePromise;
  62310. };
  62311. DracoCompression._LoadScriptAsync = function (url) {
  62312. return new Promise(function (resolve, reject) {
  62313. BABYLON.Tools.LoadScript(url, function () {
  62314. resolve();
  62315. }, function (message) {
  62316. reject(new Error(message));
  62317. });
  62318. });
  62319. };
  62320. DracoCompression._LoadFileAsync = function (url) {
  62321. return new Promise(function (resolve, reject) {
  62322. BABYLON.Tools.LoadFile(url, function (data) {
  62323. resolve(data);
  62324. }, undefined, undefined, true, function (request, exception) {
  62325. reject(exception);
  62326. });
  62327. });
  62328. };
  62329. /**
  62330. * The configuration. Defaults to the following urls:
  62331. * - wasmUrl: "https://preview.babylonjs.com/draco_wasm_wrapper_gltf.js"
  62332. * - wasmBinaryUrl: "https://preview.babylonjs.com/draco_decoder_gltf.wasm"
  62333. * - fallbackUrl: "https://preview.babylonjs.com/draco_decoder_gltf.js"
  62334. */
  62335. DracoCompression.Configuration = {
  62336. decoder: {
  62337. wasmUrl: "https://preview.babylonjs.com/draco_wasm_wrapper_gltf.js",
  62338. wasmBinaryUrl: "https://preview.babylonjs.com/draco_decoder_gltf.wasm",
  62339. fallbackUrl: "https://preview.babylonjs.com/draco_decoder_gltf.js"
  62340. }
  62341. };
  62342. return DracoCompression;
  62343. }());
  62344. BABYLON.DracoCompression = DracoCompression;
  62345. })(BABYLON || (BABYLON = {}));
  62346. //# sourceMappingURL=babylon.dracoCompression.js.map
  62347. var BABYLON;
  62348. (function (BABYLON) {
  62349. var AudioEngine = /** @class */ (function () {
  62350. function AudioEngine() {
  62351. this._audioContext = null;
  62352. this._audioContextInitialized = false;
  62353. this.canUseWebAudio = false;
  62354. this.WarnedWebAudioUnsupported = false;
  62355. this.unlocked = false;
  62356. this.isMP3supported = false;
  62357. this.isOGGsupported = false;
  62358. if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
  62359. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  62360. this.canUseWebAudio = true;
  62361. }
  62362. var audioElem = document.createElement('audio');
  62363. try {
  62364. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/mpeg; codecs="mp3"').replace(/^no$/, '')) {
  62365. this.isMP3supported = true;
  62366. }
  62367. }
  62368. catch (e) {
  62369. // protect error during capability check.
  62370. }
  62371. try {
  62372. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/, '')) {
  62373. this.isOGGsupported = true;
  62374. }
  62375. }
  62376. catch (e) {
  62377. // protect error during capability check.
  62378. }
  62379. if (/iPad|iPhone|iPod/.test(navigator.platform)) {
  62380. this._unlockiOSaudio();
  62381. }
  62382. else {
  62383. this.unlocked = true;
  62384. }
  62385. }
  62386. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  62387. get: function () {
  62388. if (!this._audioContextInitialized) {
  62389. this._initializeAudioContext();
  62390. }
  62391. return this._audioContext;
  62392. },
  62393. enumerable: true,
  62394. configurable: true
  62395. });
  62396. AudioEngine.prototype._unlockiOSaudio = function () {
  62397. var _this = this;
  62398. var unlockaudio = function () {
  62399. if (!_this.audioContext) {
  62400. return;
  62401. }
  62402. var buffer = _this.audioContext.createBuffer(1, 1, 22050);
  62403. var source = _this.audioContext.createBufferSource();
  62404. source.buffer = buffer;
  62405. source.connect(_this.audioContext.destination);
  62406. source.start(0);
  62407. setTimeout(function () {
  62408. if ((source.playbackState === source.PLAYING_STATE || source.playbackState === source.FINISHED_STATE)) {
  62409. _this.unlocked = true;
  62410. window.removeEventListener('touchend', unlockaudio, false);
  62411. if (_this.onAudioUnlocked) {
  62412. _this.onAudioUnlocked();
  62413. }
  62414. }
  62415. }, 0);
  62416. };
  62417. window.addEventListener('touchend', unlockaudio, false);
  62418. };
  62419. AudioEngine.prototype._initializeAudioContext = function () {
  62420. try {
  62421. if (this.canUseWebAudio) {
  62422. this._audioContext = new AudioContext();
  62423. // create a global volume gain node
  62424. this.masterGain = this._audioContext.createGain();
  62425. this.masterGain.gain.value = 1;
  62426. this.masterGain.connect(this._audioContext.destination);
  62427. this._audioContextInitialized = true;
  62428. }
  62429. }
  62430. catch (e) {
  62431. this.canUseWebAudio = false;
  62432. BABYLON.Tools.Error("Web Audio: " + e.message);
  62433. }
  62434. };
  62435. AudioEngine.prototype.dispose = function () {
  62436. if (this.canUseWebAudio && this._audioContextInitialized) {
  62437. if (this._connectedAnalyser && this._audioContext) {
  62438. this._connectedAnalyser.stopDebugCanvas();
  62439. this._connectedAnalyser.dispose();
  62440. this.masterGain.disconnect();
  62441. this.masterGain.connect(this._audioContext.destination);
  62442. this._connectedAnalyser = null;
  62443. }
  62444. this.masterGain.gain.value = 1;
  62445. }
  62446. this.WarnedWebAudioUnsupported = false;
  62447. };
  62448. AudioEngine.prototype.getGlobalVolume = function () {
  62449. if (this.canUseWebAudio && this._audioContextInitialized) {
  62450. return this.masterGain.gain.value;
  62451. }
  62452. else {
  62453. return -1;
  62454. }
  62455. };
  62456. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  62457. if (this.canUseWebAudio && this._audioContextInitialized) {
  62458. this.masterGain.gain.value = newVolume;
  62459. }
  62460. };
  62461. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  62462. if (this._connectedAnalyser) {
  62463. this._connectedAnalyser.stopDebugCanvas();
  62464. }
  62465. if (this.canUseWebAudio && this._audioContextInitialized && this._audioContext) {
  62466. this._connectedAnalyser = analyser;
  62467. this.masterGain.disconnect();
  62468. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  62469. }
  62470. };
  62471. return AudioEngine;
  62472. }());
  62473. BABYLON.AudioEngine = AudioEngine;
  62474. })(BABYLON || (BABYLON = {}));
  62475. //# sourceMappingURL=babylon.audioEngine.js.map
  62476. var BABYLON;
  62477. (function (BABYLON) {
  62478. var Sound = /** @class */ (function () {
  62479. /**
  62480. * Create a sound and attach it to a scene
  62481. * @param name Name of your sound
  62482. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer
  62483. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  62484. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel, streaming
  62485. */
  62486. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  62487. if (readyToPlayCallback === void 0) { readyToPlayCallback = null; }
  62488. var _this = this;
  62489. this.autoplay = false;
  62490. this.loop = false;
  62491. this.useCustomAttenuation = false;
  62492. this.spatialSound = false;
  62493. this.refDistance = 1;
  62494. this.rolloffFactor = 1;
  62495. this.maxDistance = 100;
  62496. this.distanceModel = "linear";
  62497. this._panningModel = "equalpower";
  62498. this._playbackRate = 1;
  62499. this._streaming = false;
  62500. this._startTime = 0;
  62501. this._startOffset = 0;
  62502. this._position = BABYLON.Vector3.Zero();
  62503. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  62504. this._volume = 1;
  62505. this._isReadyToPlay = false;
  62506. this.isPlaying = false;
  62507. this.isPaused = false;
  62508. this._isDirectional = false;
  62509. // Used if you'd like to create a directional sound.
  62510. // If not set, the sound will be omnidirectional
  62511. this._coneInnerAngle = 360;
  62512. this._coneOuterAngle = 360;
  62513. this._coneOuterGain = 0;
  62514. this._isOutputConnected = false;
  62515. this._urlType = "Unknown";
  62516. this.name = name;
  62517. this._scene = scene;
  62518. this._readyToPlayCallback = readyToPlayCallback;
  62519. // Default custom attenuation function is a linear attenuation
  62520. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  62521. if (currentDistance < maxDistance) {
  62522. return currentVolume * (1 - currentDistance / maxDistance);
  62523. }
  62524. else {
  62525. return 0;
  62526. }
  62527. };
  62528. if (options) {
  62529. this.autoplay = options.autoplay || false;
  62530. this.loop = options.loop || false;
  62531. // if volume === 0, we need another way to check this option
  62532. if (options.volume !== undefined) {
  62533. this._volume = options.volume;
  62534. }
  62535. this.spatialSound = options.spatialSound || false;
  62536. this.maxDistance = options.maxDistance || 100;
  62537. this.useCustomAttenuation = options.useCustomAttenuation || false;
  62538. this.rolloffFactor = options.rolloffFactor || 1;
  62539. this.refDistance = options.refDistance || 1;
  62540. this.distanceModel = options.distanceModel || "linear";
  62541. this._playbackRate = options.playbackRate || 1;
  62542. this._streaming = options.streaming || false;
  62543. }
  62544. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  62545. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  62546. this._soundGain.gain.value = this._volume;
  62547. this._inputAudioNode = this._soundGain;
  62548. this._ouputAudioNode = this._soundGain;
  62549. if (this.spatialSound) {
  62550. this._createSpatialParameters();
  62551. }
  62552. this._scene.mainSoundTrack.AddSound(this);
  62553. var validParameter = true;
  62554. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  62555. if (urlOrArrayBuffer) {
  62556. try {
  62557. if (typeof (urlOrArrayBuffer) === "string")
  62558. this._urlType = "String";
  62559. if (Array.isArray(urlOrArrayBuffer))
  62560. this._urlType = "Array";
  62561. if (urlOrArrayBuffer instanceof ArrayBuffer)
  62562. this._urlType = "ArrayBuffer";
  62563. var urls = [];
  62564. var codecSupportedFound = false;
  62565. switch (this._urlType) {
  62566. case "ArrayBuffer":
  62567. if (urlOrArrayBuffer.byteLength > 0) {
  62568. codecSupportedFound = true;
  62569. this._soundLoaded(urlOrArrayBuffer);
  62570. }
  62571. break;
  62572. case "String":
  62573. urls.push(urlOrArrayBuffer);
  62574. case "Array":
  62575. if (urls.length === 0)
  62576. urls = urlOrArrayBuffer;
  62577. // If we found a supported format, we load it immediately and stop the loop
  62578. for (var i = 0; i < urls.length; i++) {
  62579. var url = urls[i];
  62580. if (url.indexOf(".mp3", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isMP3supported) {
  62581. codecSupportedFound = true;
  62582. }
  62583. if (url.indexOf(".ogg", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isOGGsupported) {
  62584. codecSupportedFound = true;
  62585. }
  62586. if (url.indexOf(".wav", url.length - 4) !== -1) {
  62587. codecSupportedFound = true;
  62588. }
  62589. if (url.indexOf("blob:") !== -1) {
  62590. codecSupportedFound = true;
  62591. }
  62592. if (codecSupportedFound) {
  62593. // Loading sound using XHR2
  62594. if (!this._streaming) {
  62595. this._scene._loadFile(url, function (data) {
  62596. _this._soundLoaded(data);
  62597. }, undefined, true, true, function (exception) {
  62598. if (exception) {
  62599. BABYLON.Tools.Error("XHR " + exception.status + " error on: " + url + ".");
  62600. }
  62601. BABYLON.Tools.Error("Sound creation aborted.");
  62602. _this._scene.mainSoundTrack.RemoveSound(_this);
  62603. });
  62604. }
  62605. // Streaming sound using HTML5 Audio tag
  62606. else {
  62607. this._htmlAudioElement = new Audio(url);
  62608. this._htmlAudioElement.controls = false;
  62609. this._htmlAudioElement.loop = this.loop;
  62610. BABYLON.Tools.SetCorsBehavior(url, this._htmlAudioElement);
  62611. this._htmlAudioElement.preload = "auto";
  62612. this._htmlAudioElement.addEventListener("canplaythrough", function () {
  62613. _this._isReadyToPlay = true;
  62614. if (_this.autoplay) {
  62615. _this.play();
  62616. }
  62617. if (_this._readyToPlayCallback) {
  62618. _this._readyToPlayCallback();
  62619. }
  62620. });
  62621. document.body.appendChild(this._htmlAudioElement);
  62622. }
  62623. break;
  62624. }
  62625. }
  62626. break;
  62627. default:
  62628. validParameter = false;
  62629. break;
  62630. }
  62631. if (!validParameter) {
  62632. BABYLON.Tools.Error("Parameter must be a URL to the sound, an Array of URLs (.mp3 & .ogg) or an ArrayBuffer of the sound.");
  62633. }
  62634. else {
  62635. if (!codecSupportedFound) {
  62636. this._isReadyToPlay = true;
  62637. // Simulating a ready to play event to avoid breaking code path
  62638. if (this._readyToPlayCallback) {
  62639. window.setTimeout(function () {
  62640. if (_this._readyToPlayCallback) {
  62641. _this._readyToPlayCallback();
  62642. }
  62643. }, 1000);
  62644. }
  62645. }
  62646. }
  62647. }
  62648. catch (ex) {
  62649. BABYLON.Tools.Error("Unexpected error. Sound creation aborted.");
  62650. this._scene.mainSoundTrack.RemoveSound(this);
  62651. }
  62652. }
  62653. }
  62654. else {
  62655. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  62656. this._scene.mainSoundTrack.AddSound(this);
  62657. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  62658. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  62659. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  62660. }
  62661. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  62662. if (this._readyToPlayCallback) {
  62663. window.setTimeout(function () {
  62664. if (_this._readyToPlayCallback) {
  62665. _this._readyToPlayCallback();
  62666. }
  62667. }, 1000);
  62668. }
  62669. }
  62670. }
  62671. Sound.prototype.dispose = function () {
  62672. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  62673. if (this.isPlaying) {
  62674. this.stop();
  62675. }
  62676. this._isReadyToPlay = false;
  62677. if (this.soundTrackId === -1) {
  62678. this._scene.mainSoundTrack.RemoveSound(this);
  62679. }
  62680. else {
  62681. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  62682. }
  62683. if (this._soundGain) {
  62684. this._soundGain.disconnect();
  62685. this._soundGain = null;
  62686. }
  62687. if (this._soundPanner) {
  62688. this._soundPanner.disconnect();
  62689. this._soundPanner = null;
  62690. }
  62691. if (this._soundSource) {
  62692. this._soundSource.disconnect();
  62693. this._soundSource = null;
  62694. }
  62695. this._audioBuffer = null;
  62696. if (this._htmlAudioElement) {
  62697. this._htmlAudioElement.pause();
  62698. this._htmlAudioElement.src = "";
  62699. document.body.removeChild(this._htmlAudioElement);
  62700. }
  62701. if (this._connectedMesh && this._registerFunc) {
  62702. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  62703. this._connectedMesh = null;
  62704. }
  62705. }
  62706. };
  62707. Sound.prototype.isReady = function () {
  62708. return this._isReadyToPlay;
  62709. };
  62710. Sound.prototype._soundLoaded = function (audioData) {
  62711. var _this = this;
  62712. if (!BABYLON.Engine.audioEngine.audioContext) {
  62713. return;
  62714. }
  62715. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  62716. _this._audioBuffer = buffer;
  62717. _this._isReadyToPlay = true;
  62718. if (_this.autoplay) {
  62719. _this.play();
  62720. }
  62721. if (_this._readyToPlayCallback) {
  62722. _this._readyToPlayCallback();
  62723. }
  62724. }, function (err) { BABYLON.Tools.Error("Error while decoding audio data for: " + _this.name + " / Error: " + err); });
  62725. };
  62726. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  62727. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  62728. this._audioBuffer = audioBuffer;
  62729. this._isReadyToPlay = true;
  62730. }
  62731. };
  62732. Sound.prototype.updateOptions = function (options) {
  62733. if (options) {
  62734. this.loop = options.loop || this.loop;
  62735. this.maxDistance = options.maxDistance || this.maxDistance;
  62736. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  62737. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  62738. this.refDistance = options.refDistance || this.refDistance;
  62739. this.distanceModel = options.distanceModel || this.distanceModel;
  62740. this._playbackRate = options.playbackRate || this._playbackRate;
  62741. this._updateSpatialParameters();
  62742. if (this.isPlaying) {
  62743. if (this._streaming) {
  62744. this._htmlAudioElement.playbackRate = this._playbackRate;
  62745. }
  62746. else {
  62747. if (this._soundSource) {
  62748. this._soundSource.playbackRate.value = this._playbackRate;
  62749. }
  62750. }
  62751. }
  62752. }
  62753. };
  62754. Sound.prototype._createSpatialParameters = function () {
  62755. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  62756. if (this._scene.headphone) {
  62757. this._panningModel = "HRTF";
  62758. }
  62759. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  62760. this._updateSpatialParameters();
  62761. this._soundPanner.connect(this._ouputAudioNode);
  62762. this._inputAudioNode = this._soundPanner;
  62763. }
  62764. };
  62765. Sound.prototype._updateSpatialParameters = function () {
  62766. if (this.spatialSound && this._soundPanner) {
  62767. if (this.useCustomAttenuation) {
  62768. // Tricks to disable in a way embedded Web Audio attenuation
  62769. this._soundPanner.distanceModel = "linear";
  62770. this._soundPanner.maxDistance = Number.MAX_VALUE;
  62771. this._soundPanner.refDistance = 1;
  62772. this._soundPanner.rolloffFactor = 1;
  62773. this._soundPanner.panningModel = this._panningModel;
  62774. }
  62775. else {
  62776. this._soundPanner.distanceModel = this.distanceModel;
  62777. this._soundPanner.maxDistance = this.maxDistance;
  62778. this._soundPanner.refDistance = this.refDistance;
  62779. this._soundPanner.rolloffFactor = this.rolloffFactor;
  62780. this._soundPanner.panningModel = this._panningModel;
  62781. }
  62782. }
  62783. };
  62784. Sound.prototype.switchPanningModelToHRTF = function () {
  62785. this._panningModel = "HRTF";
  62786. this._switchPanningModel();
  62787. };
  62788. Sound.prototype.switchPanningModelToEqualPower = function () {
  62789. this._panningModel = "equalpower";
  62790. this._switchPanningModel();
  62791. };
  62792. Sound.prototype._switchPanningModel = function () {
  62793. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  62794. this._soundPanner.panningModel = this._panningModel;
  62795. }
  62796. };
  62797. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  62798. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  62799. if (this._isOutputConnected) {
  62800. this._ouputAudioNode.disconnect();
  62801. }
  62802. this._ouputAudioNode.connect(soundTrackAudioNode);
  62803. this._isOutputConnected = true;
  62804. }
  62805. };
  62806. /**
  62807. * Transform this sound into a directional source
  62808. * @param coneInnerAngle Size of the inner cone in degree
  62809. * @param coneOuterAngle Size of the outer cone in degree
  62810. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  62811. */
  62812. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  62813. if (coneOuterAngle < coneInnerAngle) {
  62814. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  62815. return;
  62816. }
  62817. this._coneInnerAngle = coneInnerAngle;
  62818. this._coneOuterAngle = coneOuterAngle;
  62819. this._coneOuterGain = coneOuterGain;
  62820. this._isDirectional = true;
  62821. if (this.isPlaying && this.loop) {
  62822. this.stop();
  62823. this.play();
  62824. }
  62825. };
  62826. Sound.prototype.setPosition = function (newPosition) {
  62827. this._position = newPosition;
  62828. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  62829. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  62830. }
  62831. };
  62832. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  62833. this._localDirection = newLocalDirection;
  62834. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  62835. this._updateDirection();
  62836. }
  62837. };
  62838. Sound.prototype._updateDirection = function () {
  62839. if (!this._connectedMesh || !this._soundPanner) {
  62840. return;
  62841. }
  62842. var mat = this._connectedMesh.getWorldMatrix();
  62843. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  62844. direction.normalize();
  62845. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  62846. };
  62847. Sound.prototype.updateDistanceFromListener = function () {
  62848. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation && this._soundGain && this._scene.activeCamera) {
  62849. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  62850. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  62851. }
  62852. };
  62853. Sound.prototype.setAttenuationFunction = function (callback) {
  62854. this._customAttenuationFunction = callback;
  62855. };
  62856. /**
  62857. * Play the sound
  62858. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  62859. * @param offset (optional) Start the sound setting it at a specific time
  62860. */
  62861. Sound.prototype.play = function (time, offset) {
  62862. var _this = this;
  62863. if (this._isReadyToPlay && this._scene.audioEnabled && BABYLON.Engine.audioEngine.audioContext) {
  62864. try {
  62865. if (this._startOffset < 0) {
  62866. time = -this._startOffset;
  62867. this._startOffset = 0;
  62868. }
  62869. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  62870. if (!this._soundSource || !this._streamingSource) {
  62871. if (this.spatialSound && this._soundPanner) {
  62872. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  62873. if (this._isDirectional) {
  62874. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  62875. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  62876. this._soundPanner.coneOuterGain = this._coneOuterGain;
  62877. if (this._connectedMesh) {
  62878. this._updateDirection();
  62879. }
  62880. else {
  62881. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  62882. }
  62883. }
  62884. }
  62885. }
  62886. if (this._streaming) {
  62887. if (!this._streamingSource) {
  62888. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement);
  62889. this._htmlAudioElement.onended = function () { _this._onended(); };
  62890. this._htmlAudioElement.playbackRate = this._playbackRate;
  62891. }
  62892. this._streamingSource.disconnect();
  62893. this._streamingSource.connect(this._inputAudioNode);
  62894. this._htmlAudioElement.play();
  62895. }
  62896. else {
  62897. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  62898. this._soundSource.buffer = this._audioBuffer;
  62899. this._soundSource.connect(this._inputAudioNode);
  62900. this._soundSource.loop = this.loop;
  62901. this._soundSource.playbackRate.value = this._playbackRate;
  62902. this._soundSource.onended = function () { _this._onended(); };
  62903. if (this._soundSource.buffer) {
  62904. this._soundSource.start(startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : offset ? offset : 0);
  62905. }
  62906. }
  62907. this._startTime = startTime;
  62908. this.isPlaying = true;
  62909. this.isPaused = false;
  62910. }
  62911. catch (ex) {
  62912. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  62913. }
  62914. }
  62915. };
  62916. Sound.prototype._onended = function () {
  62917. this.isPlaying = false;
  62918. if (this.onended) {
  62919. this.onended();
  62920. }
  62921. };
  62922. /**
  62923. * Stop the sound
  62924. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  62925. */
  62926. Sound.prototype.stop = function (time) {
  62927. if (this.isPlaying) {
  62928. if (this._streaming) {
  62929. this._htmlAudioElement.pause();
  62930. // Test needed for Firefox or it will generate an Invalid State Error
  62931. if (this._htmlAudioElement.currentTime > 0) {
  62932. this._htmlAudioElement.currentTime = 0;
  62933. }
  62934. }
  62935. else if (BABYLON.Engine.audioEngine.audioContext && this._soundSource) {
  62936. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  62937. this._soundSource.stop(stopTime);
  62938. this._soundSource.onended = function () { };
  62939. if (!this.isPaused) {
  62940. this._startOffset = 0;
  62941. }
  62942. }
  62943. this.isPlaying = false;
  62944. }
  62945. };
  62946. Sound.prototype.pause = function () {
  62947. if (this.isPlaying) {
  62948. this.isPaused = true;
  62949. if (this._streaming) {
  62950. this._htmlAudioElement.pause();
  62951. }
  62952. else if (BABYLON.Engine.audioEngine.audioContext) {
  62953. this.stop(0);
  62954. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  62955. }
  62956. }
  62957. };
  62958. Sound.prototype.setVolume = function (newVolume, time) {
  62959. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._soundGain) {
  62960. if (time && BABYLON.Engine.audioEngine.audioContext) {
  62961. this._soundGain.gain.cancelScheduledValues(BABYLON.Engine.audioEngine.audioContext.currentTime);
  62962. this._soundGain.gain.setValueAtTime(this._soundGain.gain.value, BABYLON.Engine.audioEngine.audioContext.currentTime);
  62963. this._soundGain.gain.linearRampToValueAtTime(newVolume, BABYLON.Engine.audioEngine.audioContext.currentTime + time);
  62964. }
  62965. else {
  62966. this._soundGain.gain.value = newVolume;
  62967. }
  62968. }
  62969. this._volume = newVolume;
  62970. };
  62971. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  62972. this._playbackRate = newPlaybackRate;
  62973. if (this.isPlaying) {
  62974. if (this._streaming) {
  62975. this._htmlAudioElement.playbackRate = this._playbackRate;
  62976. }
  62977. else if (this._soundSource) {
  62978. this._soundSource.playbackRate.value = this._playbackRate;
  62979. }
  62980. }
  62981. };
  62982. Sound.prototype.getVolume = function () {
  62983. return this._volume;
  62984. };
  62985. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  62986. var _this = this;
  62987. if (this._connectedMesh && this._registerFunc) {
  62988. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  62989. this._registerFunc = null;
  62990. }
  62991. this._connectedMesh = meshToConnectTo;
  62992. if (!this.spatialSound) {
  62993. this.spatialSound = true;
  62994. this._createSpatialParameters();
  62995. if (this.isPlaying && this.loop) {
  62996. this.stop();
  62997. this.play();
  62998. }
  62999. }
  63000. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  63001. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  63002. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  63003. };
  63004. Sound.prototype.detachFromMesh = function () {
  63005. if (this._connectedMesh && this._registerFunc) {
  63006. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  63007. this._registerFunc = null;
  63008. this._connectedMesh = null;
  63009. }
  63010. };
  63011. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (node) {
  63012. if (!node.getBoundingInfo) {
  63013. return;
  63014. }
  63015. var mesh = node;
  63016. var boundingInfo = mesh.getBoundingInfo();
  63017. this.setPosition(boundingInfo.boundingSphere.centerWorld);
  63018. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  63019. this._updateDirection();
  63020. }
  63021. };
  63022. Sound.prototype.clone = function () {
  63023. var _this = this;
  63024. if (!this._streaming) {
  63025. var setBufferAndRun = function () {
  63026. if (_this._isReadyToPlay) {
  63027. clonedSound._audioBuffer = _this.getAudioBuffer();
  63028. clonedSound._isReadyToPlay = true;
  63029. if (clonedSound.autoplay) {
  63030. clonedSound.play();
  63031. }
  63032. }
  63033. else {
  63034. window.setTimeout(setBufferAndRun, 300);
  63035. }
  63036. };
  63037. var currentOptions = {
  63038. autoplay: this.autoplay, loop: this.loop,
  63039. volume: this._volume, spatialSound: this.spatialSound, maxDistance: this.maxDistance,
  63040. useCustomAttenuation: this.useCustomAttenuation, rolloffFactor: this.rolloffFactor,
  63041. refDistance: this.refDistance, distanceModel: this.distanceModel
  63042. };
  63043. var clonedSound = new Sound(this.name + "_cloned", new ArrayBuffer(0), this._scene, null, currentOptions);
  63044. if (this.useCustomAttenuation) {
  63045. clonedSound.setAttenuationFunction(this._customAttenuationFunction);
  63046. }
  63047. clonedSound.setPosition(this._position);
  63048. clonedSound.setPlaybackRate(this._playbackRate);
  63049. setBufferAndRun();
  63050. return clonedSound;
  63051. }
  63052. // Can't clone a streaming sound
  63053. else {
  63054. return null;
  63055. }
  63056. };
  63057. Sound.prototype.getAudioBuffer = function () {
  63058. return this._audioBuffer;
  63059. };
  63060. Sound.prototype.serialize = function () {
  63061. var serializationObject = {
  63062. name: this.name,
  63063. url: this.name,
  63064. autoplay: this.autoplay,
  63065. loop: this.loop,
  63066. volume: this._volume,
  63067. spatialSound: this.spatialSound,
  63068. maxDistance: this.maxDistance,
  63069. rolloffFactor: this.rolloffFactor,
  63070. refDistance: this.refDistance,
  63071. distanceModel: this.distanceModel,
  63072. playbackRate: this._playbackRate,
  63073. panningModel: this._panningModel,
  63074. soundTrackId: this.soundTrackId
  63075. };
  63076. if (this.spatialSound) {
  63077. if (this._connectedMesh)
  63078. serializationObject.connectedMeshId = this._connectedMesh.id;
  63079. serializationObject.position = this._position.asArray();
  63080. serializationObject.refDistance = this.refDistance;
  63081. serializationObject.distanceModel = this.distanceModel;
  63082. serializationObject.isDirectional = this._isDirectional;
  63083. serializationObject.localDirectionToMesh = this._localDirection.asArray();
  63084. serializationObject.coneInnerAngle = this._coneInnerAngle;
  63085. serializationObject.coneOuterAngle = this._coneOuterAngle;
  63086. serializationObject.coneOuterGain = this._coneOuterGain;
  63087. }
  63088. return serializationObject;
  63089. };
  63090. Sound.Parse = function (parsedSound, scene, rootUrl, sourceSound) {
  63091. var soundName = parsedSound.name;
  63092. var soundUrl;
  63093. if (parsedSound.url) {
  63094. soundUrl = rootUrl + parsedSound.url;
  63095. }
  63096. else {
  63097. soundUrl = rootUrl + soundName;
  63098. }
  63099. var options = {
  63100. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  63101. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  63102. rolloffFactor: parsedSound.rolloffFactor,
  63103. refDistance: parsedSound.refDistance,
  63104. distanceModel: parsedSound.distanceModel,
  63105. playbackRate: parsedSound.playbackRate
  63106. };
  63107. var newSound;
  63108. if (!sourceSound) {
  63109. newSound = new Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
  63110. scene._addPendingData(newSound);
  63111. }
  63112. else {
  63113. var setBufferAndRun = function () {
  63114. if (sourceSound._isReadyToPlay) {
  63115. newSound._audioBuffer = sourceSound.getAudioBuffer();
  63116. newSound._isReadyToPlay = true;
  63117. if (newSound.autoplay) {
  63118. newSound.play();
  63119. }
  63120. }
  63121. else {
  63122. window.setTimeout(setBufferAndRun, 300);
  63123. }
  63124. };
  63125. newSound = new Sound(soundName, new ArrayBuffer(0), scene, null, options);
  63126. setBufferAndRun();
  63127. }
  63128. if (parsedSound.position) {
  63129. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  63130. newSound.setPosition(soundPosition);
  63131. }
  63132. if (parsedSound.isDirectional) {
  63133. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  63134. if (parsedSound.localDirectionToMesh) {
  63135. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  63136. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  63137. }
  63138. }
  63139. if (parsedSound.connectedMeshId) {
  63140. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  63141. if (connectedMesh) {
  63142. newSound.attachToMesh(connectedMesh);
  63143. }
  63144. }
  63145. return newSound;
  63146. };
  63147. return Sound;
  63148. }());
  63149. BABYLON.Sound = Sound;
  63150. })(BABYLON || (BABYLON = {}));
  63151. //# sourceMappingURL=babylon.sound.js.map
  63152. var BABYLON;
  63153. (function (BABYLON) {
  63154. var SoundTrack = /** @class */ (function () {
  63155. function SoundTrack(scene, options) {
  63156. this.id = -1;
  63157. this._isMainTrack = false;
  63158. this._isInitialized = false;
  63159. this._scene = scene;
  63160. this.soundCollection = new Array();
  63161. this._options = options;
  63162. if (!this._isMainTrack) {
  63163. this._scene.soundTracks.push(this);
  63164. this.id = this._scene.soundTracks.length - 1;
  63165. }
  63166. }
  63167. SoundTrack.prototype._initializeSoundTrackAudioGraph = function () {
  63168. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  63169. this._outputAudioNode = BABYLON.Engine.audioEngine.audioContext.createGain();
  63170. this._outputAudioNode.connect(BABYLON.Engine.audioEngine.masterGain);
  63171. if (this._options) {
  63172. if (this._options.volume) {
  63173. this._outputAudioNode.gain.value = this._options.volume;
  63174. }
  63175. if (this._options.mainTrack) {
  63176. this._isMainTrack = this._options.mainTrack;
  63177. }
  63178. }
  63179. this._isInitialized = true;
  63180. }
  63181. };
  63182. SoundTrack.prototype.dispose = function () {
  63183. if (BABYLON.Engine.audioEngine && BABYLON.Engine.audioEngine.canUseWebAudio) {
  63184. if (this._connectedAnalyser) {
  63185. this._connectedAnalyser.stopDebugCanvas();
  63186. }
  63187. while (this.soundCollection.length) {
  63188. this.soundCollection[0].dispose();
  63189. }
  63190. if (this._outputAudioNode) {
  63191. this._outputAudioNode.disconnect();
  63192. }
  63193. this._outputAudioNode = null;
  63194. }
  63195. };
  63196. SoundTrack.prototype.AddSound = function (sound) {
  63197. if (!this._isInitialized) {
  63198. this._initializeSoundTrackAudioGraph();
  63199. }
  63200. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  63201. sound.connectToSoundTrackAudioNode(this._outputAudioNode);
  63202. }
  63203. if (sound.soundTrackId) {
  63204. if (sound.soundTrackId === -1) {
  63205. this._scene.mainSoundTrack.RemoveSound(sound);
  63206. }
  63207. else {
  63208. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  63209. }
  63210. }
  63211. this.soundCollection.push(sound);
  63212. sound.soundTrackId = this.id;
  63213. };
  63214. SoundTrack.prototype.RemoveSound = function (sound) {
  63215. var index = this.soundCollection.indexOf(sound);
  63216. if (index !== -1) {
  63217. this.soundCollection.splice(index, 1);
  63218. }
  63219. };
  63220. SoundTrack.prototype.setVolume = function (newVolume) {
  63221. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  63222. this._outputAudioNode.gain.value = newVolume;
  63223. }
  63224. };
  63225. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  63226. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  63227. for (var i = 0; i < this.soundCollection.length; i++) {
  63228. this.soundCollection[i].switchPanningModelToHRTF();
  63229. }
  63230. }
  63231. };
  63232. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  63233. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  63234. for (var i = 0; i < this.soundCollection.length; i++) {
  63235. this.soundCollection[i].switchPanningModelToEqualPower();
  63236. }
  63237. }
  63238. };
  63239. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  63240. if (this._connectedAnalyser) {
  63241. this._connectedAnalyser.stopDebugCanvas();
  63242. }
  63243. this._connectedAnalyser = analyser;
  63244. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  63245. this._outputAudioNode.disconnect();
  63246. this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, BABYLON.Engine.audioEngine.masterGain);
  63247. }
  63248. };
  63249. return SoundTrack;
  63250. }());
  63251. BABYLON.SoundTrack = SoundTrack;
  63252. })(BABYLON || (BABYLON = {}));
  63253. //# sourceMappingURL=babylon.soundtrack.js.map
  63254. var BABYLON;
  63255. (function (BABYLON) {
  63256. /**
  63257. * Class used to work with sound analyzer using fast fourier transform (FFT)
  63258. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  63259. */
  63260. var Analyser = /** @class */ (function () {
  63261. /**
  63262. * Creates a new analyser
  63263. * @param scene defines hosting scene
  63264. */
  63265. function Analyser(scene) {
  63266. /**
  63267. * Gets or sets the smoothing
  63268. * @ignorenaming
  63269. */
  63270. this.SMOOTHING = 0.75;
  63271. /**
  63272. * Gets or sets the FFT table size
  63273. * @ignorenaming
  63274. */
  63275. this.FFT_SIZE = 512;
  63276. /**
  63277. * Gets or sets the bar graph amplitude
  63278. * @ignorenaming
  63279. */
  63280. this.BARGRAPHAMPLITUDE = 256;
  63281. /**
  63282. * Gets or sets the position of the debug canvas
  63283. * @ignorenaming
  63284. */
  63285. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  63286. /**
  63287. * Gets or sets the debug canvas size
  63288. * @ignorenaming
  63289. */
  63290. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  63291. this._scene = scene;
  63292. this._audioEngine = BABYLON.Engine.audioEngine;
  63293. if (this._audioEngine.canUseWebAudio && this._audioEngine.audioContext) {
  63294. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  63295. this._webAudioAnalyser.minDecibels = -140;
  63296. this._webAudioAnalyser.maxDecibels = 0;
  63297. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  63298. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  63299. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  63300. }
  63301. }
  63302. /**
  63303. * Get the number of data values you will have to play with for the visualization
  63304. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/frequencyBinCount
  63305. * @returns a number
  63306. */
  63307. Analyser.prototype.getFrequencyBinCount = function () {
  63308. if (this._audioEngine.canUseWebAudio) {
  63309. return this._webAudioAnalyser.frequencyBinCount;
  63310. }
  63311. else {
  63312. return 0;
  63313. }
  63314. };
  63315. /**
  63316. * Gets the current frequency data as a byte array
  63317. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/getByteFrequencyData
  63318. * @returns a Uint8Array
  63319. */
  63320. Analyser.prototype.getByteFrequencyData = function () {
  63321. if (this._audioEngine.canUseWebAudio) {
  63322. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  63323. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  63324. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  63325. }
  63326. return this._byteFreqs;
  63327. };
  63328. /**
  63329. * Gets the current waveform as a byte array
  63330. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/getByteTimeDomainData
  63331. * @returns a Uint8Array
  63332. */
  63333. Analyser.prototype.getByteTimeDomainData = function () {
  63334. if (this._audioEngine.canUseWebAudio) {
  63335. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  63336. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  63337. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  63338. }
  63339. return this._byteTime;
  63340. };
  63341. /**
  63342. * Gets the current frequency data as a float array
  63343. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/getByteFrequencyData
  63344. * @returns a Float32Array
  63345. */
  63346. Analyser.prototype.getFloatFrequencyData = function () {
  63347. if (this._audioEngine.canUseWebAudio) {
  63348. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  63349. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  63350. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  63351. }
  63352. return this._floatFreqs;
  63353. };
  63354. /**
  63355. * Renders the debug canvas
  63356. */
  63357. Analyser.prototype.drawDebugCanvas = function () {
  63358. var _this = this;
  63359. if (this._audioEngine.canUseWebAudio) {
  63360. if (!this._debugCanvas) {
  63361. this._debugCanvas = document.createElement("canvas");
  63362. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  63363. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  63364. this._debugCanvas.style.position = "absolute";
  63365. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  63366. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  63367. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  63368. document.body.appendChild(this._debugCanvas);
  63369. this._registerFunc = function () {
  63370. _this.drawDebugCanvas();
  63371. };
  63372. this._scene.registerBeforeRender(this._registerFunc);
  63373. }
  63374. if (this._registerFunc && this._debugCanvasContext) {
  63375. var workingArray = this.getByteFrequencyData();
  63376. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  63377. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  63378. // Draw the frequency domain chart.
  63379. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  63380. var value = workingArray[i];
  63381. var percent = value / this.BARGRAPHAMPLITUDE;
  63382. var height = this.DEBUGCANVASSIZE.height * percent;
  63383. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  63384. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  63385. var hue = i / this.getFrequencyBinCount() * 360;
  63386. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  63387. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  63388. }
  63389. }
  63390. }
  63391. };
  63392. /**
  63393. * Stops rendering the debug canvas and removes it
  63394. */
  63395. Analyser.prototype.stopDebugCanvas = function () {
  63396. if (this._debugCanvas) {
  63397. if (this._registerFunc) {
  63398. this._scene.unregisterBeforeRender(this._registerFunc);
  63399. this._registerFunc = null;
  63400. }
  63401. document.body.removeChild(this._debugCanvas);
  63402. this._debugCanvas = null;
  63403. this._debugCanvasContext = null;
  63404. }
  63405. };
  63406. /**
  63407. * Connects two audio nodes
  63408. * @param inputAudioNode defines first node to connect
  63409. * @param outputAudioNode defines second node to connect
  63410. */
  63411. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  63412. if (this._audioEngine.canUseWebAudio) {
  63413. inputAudioNode.connect(this._webAudioAnalyser);
  63414. this._webAudioAnalyser.connect(outputAudioNode);
  63415. }
  63416. };
  63417. /**
  63418. * Releases all associated resources
  63419. */
  63420. Analyser.prototype.dispose = function () {
  63421. if (this._audioEngine.canUseWebAudio) {
  63422. this._webAudioAnalyser.disconnect();
  63423. }
  63424. };
  63425. return Analyser;
  63426. }());
  63427. BABYLON.Analyser = Analyser;
  63428. })(BABYLON || (BABYLON = {}));
  63429. //# sourceMappingURL=babylon.analyser.js.map
  63430. var BABYLON;
  63431. (function (BABYLON) {
  63432. var CubeTexture = /** @class */ (function (_super) {
  63433. __extends(CubeTexture, _super);
  63434. /**
  63435. * Creates a cube texture to use with reflection for instance. It can be based upon dds or six images as well
  63436. * as prefiltered data.
  63437. * @param rootUrl defines the url of the texture or the root name of the six images
  63438. * @param scene defines the scene the texture is attached to
  63439. * @param extensions defines the suffixes add to the picture name in case six images are in use like _px.jpg...
  63440. * @param noMipmap defines if mipmaps should be created or not
  63441. * @param files defines the six files to load for the different faces
  63442. * @param onLoad defines a callback triggered at the end of the file load if no errors occured
  63443. * @param onError defines a callback triggered in case of error during load
  63444. * @param format defines the internal format to use for the texture once loaded
  63445. * @param prefiltered defines whether or not the texture is created from prefiltered data
  63446. * @param forcedExtension defines the extensions to use (force a special type of file to load) in case it is different from the file name
  63447. * @param createPolynomials defines whether or not to create polynomial harmonics from the texture data if necessary
  63448. * @return the cube texture
  63449. */
  63450. function CubeTexture(rootUrl, scene, extensions, noMipmap, files, onLoad, onError, format, prefiltered, forcedExtension, createPolynomials) {
  63451. if (extensions === void 0) { extensions = null; }
  63452. if (noMipmap === void 0) { noMipmap = false; }
  63453. if (files === void 0) { files = null; }
  63454. if (onLoad === void 0) { onLoad = null; }
  63455. if (onError === void 0) { onError = null; }
  63456. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  63457. if (prefiltered === void 0) { prefiltered = false; }
  63458. if (forcedExtension === void 0) { forcedExtension = null; }
  63459. if (createPolynomials === void 0) { createPolynomials = false; }
  63460. var _this = _super.call(this, scene) || this;
  63461. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  63462. /**
  63463. * Gets or sets the center of the bounding box associated with the cube texture
  63464. * It must define where the camera used to render the texture was set
  63465. */
  63466. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  63467. _this._rotationY = 0;
  63468. _this.name = rootUrl;
  63469. _this.url = rootUrl;
  63470. _this._noMipmap = noMipmap;
  63471. _this.hasAlpha = false;
  63472. _this._format = format;
  63473. _this._prefiltered = prefiltered;
  63474. _this.isCube = true;
  63475. _this._textureMatrix = BABYLON.Matrix.Identity();
  63476. _this._createPolynomials = createPolynomials;
  63477. if (prefiltered) {
  63478. _this.gammaSpace = false;
  63479. }
  63480. if (!rootUrl && !files) {
  63481. return _this;
  63482. }
  63483. _this._texture = _this._getFromCache(rootUrl, noMipmap);
  63484. var lastDot = rootUrl.lastIndexOf(".");
  63485. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  63486. var isDDS = (extension === ".dds");
  63487. if (!files) {
  63488. if (!isDDS && !extensions) {
  63489. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  63490. }
  63491. files = [];
  63492. if (extensions) {
  63493. for (var index = 0; index < extensions.length; index++) {
  63494. files.push(rootUrl + extensions[index]);
  63495. }
  63496. }
  63497. }
  63498. _this._files = files;
  63499. if (!_this._texture) {
  63500. if (!scene.useDelayedTextureLoading) {
  63501. if (prefiltered) {
  63502. _this._texture = scene.getEngine().createPrefilteredCubeTexture(rootUrl, scene, _this.lodGenerationScale, _this.lodGenerationOffset, onLoad, onError, format, forcedExtension, _this._createPolynomials);
  63503. }
  63504. else {
  63505. _this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, files, noMipmap, onLoad, onError, _this._format, forcedExtension);
  63506. }
  63507. }
  63508. else {
  63509. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  63510. }
  63511. }
  63512. else if (onLoad) {
  63513. if (_this._texture.isReady) {
  63514. BABYLON.Tools.SetImmediate(function () { return onLoad(); });
  63515. }
  63516. else {
  63517. _this._texture.onLoadedObservable.add(onLoad);
  63518. }
  63519. }
  63520. return _this;
  63521. }
  63522. Object.defineProperty(CubeTexture.prototype, "boundingBoxSize", {
  63523. get: function () {
  63524. return this._boundingBoxSize;
  63525. },
  63526. /**
  63527. * Gets or sets the size of the bounding box associated with the cube texture
  63528. * When defined, the cubemap will switch to local mode
  63529. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  63530. * @example https://www.babylonjs-playground.com/#RNASML
  63531. */
  63532. set: function (value) {
  63533. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  63534. return;
  63535. }
  63536. this._boundingBoxSize = value;
  63537. var scene = this.getScene();
  63538. if (scene) {
  63539. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  63540. }
  63541. },
  63542. enumerable: true,
  63543. configurable: true
  63544. });
  63545. Object.defineProperty(CubeTexture.prototype, "rotationY", {
  63546. /**
  63547. * Gets texture matrix rotation angle around Y axis radians.
  63548. */
  63549. get: function () {
  63550. return this._rotationY;
  63551. },
  63552. /**
  63553. * Sets texture matrix rotation angle around Y axis in radians.
  63554. */
  63555. set: function (value) {
  63556. this._rotationY = value;
  63557. this.setReflectionTextureMatrix(BABYLON.Matrix.RotationY(this._rotationY));
  63558. },
  63559. enumerable: true,
  63560. configurable: true
  63561. });
  63562. CubeTexture.CreateFromImages = function (files, scene, noMipmap) {
  63563. var rootUrlKey = "";
  63564. files.forEach(function (url) { return rootUrlKey += url; });
  63565. return new CubeTexture(rootUrlKey, scene, null, noMipmap, files);
  63566. };
  63567. /**
  63568. * Creates and return a texture created from prefilterd data by tools like IBL Baker or Lys.
  63569. * @param url defines the url of the prefiltered texture
  63570. * @param scene defines the scene the texture is attached to
  63571. * @param forcedExtension defines the extension of the file if different from the url
  63572. * @param createPolynomials defines whether or not to create polynomial harmonics from the texture data if necessary
  63573. * @return the prefiltered texture
  63574. */
  63575. CubeTexture.CreateFromPrefilteredData = function (url, scene, forcedExtension, createPolynomials) {
  63576. if (forcedExtension === void 0) { forcedExtension = null; }
  63577. if (createPolynomials === void 0) { createPolynomials = true; }
  63578. return new CubeTexture(url, scene, null, false, null, null, null, undefined, true, forcedExtension, createPolynomials);
  63579. };
  63580. // Methods
  63581. CubeTexture.prototype.delayLoad = function () {
  63582. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  63583. return;
  63584. }
  63585. var scene = this.getScene();
  63586. if (!scene) {
  63587. return;
  63588. }
  63589. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  63590. this._texture = this._getFromCache(this.url, this._noMipmap);
  63591. if (!this._texture) {
  63592. if (this._prefiltered) {
  63593. this._texture = scene.getEngine().createPrefilteredCubeTexture(this.url, scene, this.lodGenerationScale, this.lodGenerationOffset, undefined, undefined, this._format, undefined, this._createPolynomials);
  63594. }
  63595. else {
  63596. this._texture = scene.getEngine().createCubeTexture(this.url, scene, this._files, this._noMipmap, undefined, undefined, this._format);
  63597. }
  63598. }
  63599. };
  63600. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  63601. return this._textureMatrix;
  63602. };
  63603. CubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  63604. this._textureMatrix = value;
  63605. };
  63606. CubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  63607. var texture = BABYLON.SerializationHelper.Parse(function () {
  63608. var prefiltered = false;
  63609. if (parsedTexture.prefiltered) {
  63610. prefiltered = parsedTexture.prefiltered;
  63611. }
  63612. return new CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions, false, null, null, null, undefined, prefiltered);
  63613. }, parsedTexture, scene);
  63614. // Local Cubemaps
  63615. if (parsedTexture.boundingBoxPosition) {
  63616. texture.boundingBoxPosition = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxPosition);
  63617. }
  63618. if (parsedTexture.boundingBoxSize) {
  63619. texture.boundingBoxSize = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxSize);
  63620. }
  63621. // Animations
  63622. if (parsedTexture.animations) {
  63623. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  63624. var parsedAnimation = parsedTexture.animations[animationIndex];
  63625. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  63626. }
  63627. }
  63628. return texture;
  63629. };
  63630. CubeTexture.prototype.clone = function () {
  63631. var _this = this;
  63632. return BABYLON.SerializationHelper.Clone(function () {
  63633. var scene = _this.getScene();
  63634. if (!scene) {
  63635. return _this;
  63636. }
  63637. return new CubeTexture(_this.url, scene, _this._extensions, _this._noMipmap, _this._files);
  63638. }, this);
  63639. };
  63640. __decorate([
  63641. BABYLON.serialize("rotationY")
  63642. ], CubeTexture.prototype, "_rotationY", void 0);
  63643. return CubeTexture;
  63644. }(BABYLON.BaseTexture));
  63645. BABYLON.CubeTexture = CubeTexture;
  63646. })(BABYLON || (BABYLON = {}));
  63647. //# sourceMappingURL=babylon.cubeTexture.js.map
  63648. var BABYLON;
  63649. (function (BABYLON) {
  63650. var RenderTargetTexture = /** @class */ (function (_super) {
  63651. __extends(RenderTargetTexture, _super);
  63652. /**
  63653. * Instantiate a render target texture. This is mainly to render of screen the scene to for instance apply post processse
  63654. * or used a shadow, depth texture...
  63655. * @param name The friendly name of the texture
  63656. * @param size The size of the RTT (number if square, or {with: number, height:number} or {ratio:} to define a ratio from the main scene)
  63657. * @param scene The scene the RTT belongs to. The latest created scene will be used if not precised.
  63658. * @param generateMipMaps True if mip maps need to be generated after render.
  63659. * @param doNotChangeAspectRatio True to not change the aspect ratio of the scene in the RTT
  63660. * @param type The type of the buffer in the RTT (int, half float, float...)
  63661. * @param isCube True if a cube texture needs to be created
  63662. * @param samplingMode The sampling mode to be usedwith the render target (Linear, Nearest...)
  63663. * @param generateDepthBuffer True to generate a depth buffer
  63664. * @param generateStencilBuffer True to generate a stencil buffer
  63665. * @param isMulti True if multiple textures need to be created (Draw Buffers)
  63666. */
  63667. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube, samplingMode, generateDepthBuffer, generateStencilBuffer, isMulti) {
  63668. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  63669. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  63670. if (isCube === void 0) { isCube = false; }
  63671. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  63672. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  63673. if (generateStencilBuffer === void 0) { generateStencilBuffer = false; }
  63674. if (isMulti === void 0) { isMulti = false; }
  63675. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  63676. _this.isCube = isCube;
  63677. /**
  63678. * Use this list to define the list of mesh you want to render.
  63679. */
  63680. _this.renderList = new Array();
  63681. _this.renderParticles = true;
  63682. _this.renderSprites = false;
  63683. _this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  63684. _this.ignoreCameraViewport = false;
  63685. // Events
  63686. /**
  63687. * An event triggered when the texture is unbind.
  63688. */
  63689. _this.onBeforeBindObservable = new BABYLON.Observable();
  63690. /**
  63691. * An event triggered when the texture is unbind.
  63692. */
  63693. _this.onAfterUnbindObservable = new BABYLON.Observable();
  63694. /**
  63695. * An event triggered before rendering the texture
  63696. */
  63697. _this.onBeforeRenderObservable = new BABYLON.Observable();
  63698. /**
  63699. * An event triggered after rendering the texture
  63700. */
  63701. _this.onAfterRenderObservable = new BABYLON.Observable();
  63702. /**
  63703. * An event triggered after the texture clear
  63704. */
  63705. _this.onClearObservable = new BABYLON.Observable();
  63706. _this._currentRefreshId = -1;
  63707. _this._refreshRate = 1;
  63708. _this._samples = 1;
  63709. /**
  63710. * Gets or sets the center of the bounding box associated with the texture (when in cube mode)
  63711. * It must define where the camera used to render the texture is set
  63712. */
  63713. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  63714. scene = _this.getScene();
  63715. if (!scene) {
  63716. return _this;
  63717. }
  63718. _this._engine = scene.getEngine();
  63719. _this.name = name;
  63720. _this.isRenderTarget = true;
  63721. _this._initialSizeParameter = size;
  63722. _this._processSizeParameter(size);
  63723. _this._resizeObserver = _this.getScene().getEngine().onResizeObservable.add(function () {
  63724. });
  63725. _this._generateMipMaps = generateMipMaps ? true : false;
  63726. _this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  63727. // Rendering groups
  63728. _this._renderingManager = new BABYLON.RenderingManager(scene);
  63729. if (isMulti) {
  63730. return _this;
  63731. }
  63732. _this._renderTargetOptions = {
  63733. generateMipMaps: generateMipMaps,
  63734. type: type,
  63735. samplingMode: samplingMode,
  63736. generateDepthBuffer: generateDepthBuffer,
  63737. generateStencilBuffer: generateStencilBuffer
  63738. };
  63739. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  63740. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  63741. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  63742. }
  63743. if (isCube) {
  63744. _this._texture = scene.getEngine().createRenderTargetCubeTexture(_this.getRenderSize(), _this._renderTargetOptions);
  63745. _this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
  63746. _this._textureMatrix = BABYLON.Matrix.Identity();
  63747. }
  63748. else {
  63749. _this._texture = scene.getEngine().createRenderTargetTexture(_this._size, _this._renderTargetOptions);
  63750. }
  63751. return _this;
  63752. }
  63753. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONCE", {
  63754. get: function () {
  63755. return RenderTargetTexture._REFRESHRATE_RENDER_ONCE;
  63756. },
  63757. enumerable: true,
  63758. configurable: true
  63759. });
  63760. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYFRAME", {
  63761. get: function () {
  63762. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME;
  63763. },
  63764. enumerable: true,
  63765. configurable: true
  63766. });
  63767. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYTWOFRAMES", {
  63768. get: function () {
  63769. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES;
  63770. },
  63771. enumerable: true,
  63772. configurable: true
  63773. });
  63774. Object.defineProperty(RenderTargetTexture.prototype, "onAfterUnbind", {
  63775. set: function (callback) {
  63776. if (this._onAfterUnbindObserver) {
  63777. this.onAfterUnbindObservable.remove(this._onAfterUnbindObserver);
  63778. }
  63779. this._onAfterUnbindObserver = this.onAfterUnbindObservable.add(callback);
  63780. },
  63781. enumerable: true,
  63782. configurable: true
  63783. });
  63784. Object.defineProperty(RenderTargetTexture.prototype, "onBeforeRender", {
  63785. set: function (callback) {
  63786. if (this._onBeforeRenderObserver) {
  63787. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  63788. }
  63789. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  63790. },
  63791. enumerable: true,
  63792. configurable: true
  63793. });
  63794. Object.defineProperty(RenderTargetTexture.prototype, "onAfterRender", {
  63795. set: function (callback) {
  63796. if (this._onAfterRenderObserver) {
  63797. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  63798. }
  63799. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  63800. },
  63801. enumerable: true,
  63802. configurable: true
  63803. });
  63804. Object.defineProperty(RenderTargetTexture.prototype, "onClear", {
  63805. set: function (callback) {
  63806. if (this._onClearObserver) {
  63807. this.onClearObservable.remove(this._onClearObserver);
  63808. }
  63809. this._onClearObserver = this.onClearObservable.add(callback);
  63810. },
  63811. enumerable: true,
  63812. configurable: true
  63813. });
  63814. Object.defineProperty(RenderTargetTexture.prototype, "renderTargetOptions", {
  63815. get: function () {
  63816. return this._renderTargetOptions;
  63817. },
  63818. enumerable: true,
  63819. configurable: true
  63820. });
  63821. RenderTargetTexture.prototype._onRatioRescale = function () {
  63822. if (this._sizeRatio) {
  63823. this.resize(this._initialSizeParameter);
  63824. }
  63825. };
  63826. Object.defineProperty(RenderTargetTexture.prototype, "boundingBoxSize", {
  63827. get: function () {
  63828. return this._boundingBoxSize;
  63829. },
  63830. /**
  63831. * Gets or sets the size of the bounding box associated with the texture (when in cube mode)
  63832. * When defined, the cubemap will switch to local mode
  63833. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  63834. * @example https://www.babylonjs-playground.com/#RNASML
  63835. */
  63836. set: function (value) {
  63837. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  63838. return;
  63839. }
  63840. this._boundingBoxSize = value;
  63841. var scene = this.getScene();
  63842. if (scene) {
  63843. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  63844. }
  63845. },
  63846. enumerable: true,
  63847. configurable: true
  63848. });
  63849. /**
  63850. * Creates a depth stencil texture.
  63851. * This is only available in WebGL 2 or with the depth texture extension available.
  63852. * @param comparisonFunction Specifies the comparison function to set on the texture. If 0 or undefined, the texture is not in comparison mode
  63853. * @param bilinearFiltering Specifies whether or not bilinear filtering is enable on the texture
  63854. * @param generateStencil Specifies whether or not a stencil should be allocated in the texture
  63855. */
  63856. RenderTargetTexture.prototype.createDepthStencilTexture = function (comparisonFunction, bilinearFiltering, generateStencil) {
  63857. if (comparisonFunction === void 0) { comparisonFunction = 0; }
  63858. if (bilinearFiltering === void 0) { bilinearFiltering = true; }
  63859. if (generateStencil === void 0) { generateStencil = false; }
  63860. if (!this.getScene()) {
  63861. return;
  63862. }
  63863. var engine = this.getScene().getEngine();
  63864. this.depthStencilTexture = engine.createDepthStencilTexture(this._size, {
  63865. bilinearFiltering: bilinearFiltering,
  63866. comparisonFunction: comparisonFunction,
  63867. generateStencil: generateStencil,
  63868. isCube: this.isCube
  63869. });
  63870. engine.setFrameBufferDepthStencilTexture(this);
  63871. };
  63872. RenderTargetTexture.prototype._processSizeParameter = function (size) {
  63873. if (size.ratio) {
  63874. this._sizeRatio = size.ratio;
  63875. this._size = {
  63876. width: this._bestReflectionRenderTargetDimension(this._engine.getRenderWidth(), this._sizeRatio),
  63877. height: this._bestReflectionRenderTargetDimension(this._engine.getRenderHeight(), this._sizeRatio)
  63878. };
  63879. }
  63880. else {
  63881. this._size = size;
  63882. }
  63883. };
  63884. Object.defineProperty(RenderTargetTexture.prototype, "samples", {
  63885. get: function () {
  63886. return this._samples;
  63887. },
  63888. set: function (value) {
  63889. if (this._samples === value) {
  63890. return;
  63891. }
  63892. var scene = this.getScene();
  63893. if (!scene) {
  63894. return;
  63895. }
  63896. this._samples = scene.getEngine().updateRenderTargetTextureSampleCount(this._texture, value);
  63897. },
  63898. enumerable: true,
  63899. configurable: true
  63900. });
  63901. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  63902. this._currentRefreshId = -1;
  63903. };
  63904. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  63905. get: function () {
  63906. return this._refreshRate;
  63907. },
  63908. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  63909. set: function (value) {
  63910. this._refreshRate = value;
  63911. this.resetRefreshCounter();
  63912. },
  63913. enumerable: true,
  63914. configurable: true
  63915. });
  63916. RenderTargetTexture.prototype.addPostProcess = function (postProcess) {
  63917. if (!this._postProcessManager) {
  63918. var scene = this.getScene();
  63919. if (!scene) {
  63920. return;
  63921. }
  63922. this._postProcessManager = new BABYLON.PostProcessManager(scene);
  63923. this._postProcesses = new Array();
  63924. }
  63925. this._postProcesses.push(postProcess);
  63926. this._postProcesses[0].autoClear = false;
  63927. };
  63928. RenderTargetTexture.prototype.clearPostProcesses = function (dispose) {
  63929. if (!this._postProcesses) {
  63930. return;
  63931. }
  63932. if (dispose) {
  63933. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  63934. var postProcess = _a[_i];
  63935. postProcess.dispose();
  63936. }
  63937. }
  63938. this._postProcesses = [];
  63939. };
  63940. RenderTargetTexture.prototype.removePostProcess = function (postProcess) {
  63941. if (!this._postProcesses) {
  63942. return;
  63943. }
  63944. var index = this._postProcesses.indexOf(postProcess);
  63945. if (index === -1) {
  63946. return;
  63947. }
  63948. this._postProcesses.splice(index, 1);
  63949. if (this._postProcesses.length > 0) {
  63950. this._postProcesses[0].autoClear = false;
  63951. }
  63952. };
  63953. RenderTargetTexture.prototype._shouldRender = function () {
  63954. if (this._currentRefreshId === -1) { // At least render once
  63955. this._currentRefreshId = 1;
  63956. return true;
  63957. }
  63958. if (this.refreshRate === this._currentRefreshId) {
  63959. this._currentRefreshId = 1;
  63960. return true;
  63961. }
  63962. this._currentRefreshId++;
  63963. return false;
  63964. };
  63965. RenderTargetTexture.prototype.getRenderSize = function () {
  63966. if (this._size.width) {
  63967. return this._size.width;
  63968. }
  63969. return this._size;
  63970. };
  63971. RenderTargetTexture.prototype.getRenderWidth = function () {
  63972. if (this._size.width) {
  63973. return this._size.width;
  63974. }
  63975. return this._size;
  63976. };
  63977. RenderTargetTexture.prototype.getRenderHeight = function () {
  63978. if (this._size.width) {
  63979. return this._size.height;
  63980. }
  63981. return this._size;
  63982. };
  63983. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  63984. get: function () {
  63985. return true;
  63986. },
  63987. enumerable: true,
  63988. configurable: true
  63989. });
  63990. RenderTargetTexture.prototype.scale = function (ratio) {
  63991. var newSize = this.getRenderSize() * ratio;
  63992. this.resize(newSize);
  63993. };
  63994. RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
  63995. if (this.isCube) {
  63996. return this._textureMatrix;
  63997. }
  63998. return _super.prototype.getReflectionTextureMatrix.call(this);
  63999. };
  64000. RenderTargetTexture.prototype.resize = function (size) {
  64001. this.releaseInternalTexture();
  64002. var scene = this.getScene();
  64003. if (!scene) {
  64004. return;
  64005. }
  64006. this._processSizeParameter(size);
  64007. if (this.isCube) {
  64008. this._texture = scene.getEngine().createRenderTargetCubeTexture(this.getRenderSize(), this._renderTargetOptions);
  64009. }
  64010. else {
  64011. this._texture = scene.getEngine().createRenderTargetTexture(this._size, this._renderTargetOptions);
  64012. }
  64013. };
  64014. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  64015. if (useCameraPostProcess === void 0) { useCameraPostProcess = false; }
  64016. if (dumpForDebug === void 0) { dumpForDebug = false; }
  64017. var scene = this.getScene();
  64018. if (!scene) {
  64019. return;
  64020. }
  64021. var engine = scene.getEngine();
  64022. if (this.useCameraPostProcesses !== undefined) {
  64023. useCameraPostProcess = this.useCameraPostProcesses;
  64024. }
  64025. if (this._waitingRenderList) {
  64026. this.renderList = [];
  64027. for (var index = 0; index < this._waitingRenderList.length; index++) {
  64028. var id = this._waitingRenderList[index];
  64029. var mesh_1 = scene.getMeshByID(id);
  64030. if (mesh_1) {
  64031. this.renderList.push(mesh_1);
  64032. }
  64033. }
  64034. delete this._waitingRenderList;
  64035. }
  64036. // Is predicate defined?
  64037. if (this.renderListPredicate) {
  64038. if (this.renderList) {
  64039. this.renderList.splice(0); // Clear previous renderList
  64040. }
  64041. else {
  64042. this.renderList = [];
  64043. }
  64044. var scene = this.getScene();
  64045. if (!scene) {
  64046. return;
  64047. }
  64048. var sceneMeshes = scene.meshes;
  64049. for (var index = 0; index < sceneMeshes.length; index++) {
  64050. var mesh = sceneMeshes[index];
  64051. if (this.renderListPredicate(mesh)) {
  64052. this.renderList.push(mesh);
  64053. }
  64054. }
  64055. }
  64056. this.onBeforeBindObservable.notifyObservers(this);
  64057. // Set custom projection.
  64058. // Needs to be before binding to prevent changing the aspect ratio.
  64059. var camera;
  64060. if (this.activeCamera) {
  64061. camera = this.activeCamera;
  64062. engine.setViewport(this.activeCamera.viewport, this.getRenderWidth(), this.getRenderHeight());
  64063. if (this.activeCamera !== scene.activeCamera) {
  64064. scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));
  64065. }
  64066. }
  64067. else {
  64068. camera = scene.activeCamera;
  64069. if (camera) {
  64070. engine.setViewport(camera.viewport, this.getRenderWidth(), this.getRenderHeight());
  64071. }
  64072. }
  64073. // Prepare renderingManager
  64074. this._renderingManager.reset();
  64075. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  64076. var currentRenderListLength = this.renderList ? this.renderList.length : scene.getActiveMeshes().length;
  64077. var sceneRenderId = scene.getRenderId();
  64078. for (var meshIndex = 0; meshIndex < currentRenderListLength; meshIndex++) {
  64079. var mesh = currentRenderList[meshIndex];
  64080. if (mesh) {
  64081. if (!mesh.isReady(this.refreshRate === 0)) {
  64082. this.resetRefreshCounter();
  64083. continue;
  64084. }
  64085. mesh._preActivateForIntermediateRendering(sceneRenderId);
  64086. var isMasked = void 0;
  64087. if (!this.renderList && camera) {
  64088. isMasked = ((mesh.layerMask & camera.layerMask) === 0);
  64089. }
  64090. else {
  64091. isMasked = false;
  64092. }
  64093. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && !isMasked) {
  64094. mesh._activate(sceneRenderId);
  64095. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  64096. var subMesh = mesh.subMeshes[subIndex];
  64097. scene._activeIndices.addCount(subMesh.indexCount, false);
  64098. this._renderingManager.dispatch(subMesh, mesh);
  64099. }
  64100. }
  64101. }
  64102. }
  64103. for (var particleIndex = 0; particleIndex < scene.particleSystems.length; particleIndex++) {
  64104. var particleSystem = scene.particleSystems[particleIndex];
  64105. var emitter = particleSystem.emitter;
  64106. if (!particleSystem.isStarted() || !emitter || !emitter.position || !emitter.isEnabled()) {
  64107. continue;
  64108. }
  64109. if (currentRenderList.indexOf(emitter) >= 0) {
  64110. this._renderingManager.dispatchParticles(particleSystem);
  64111. }
  64112. }
  64113. if (this.isCube) {
  64114. for (var face = 0; face < 6; face++) {
  64115. this.renderToTarget(face, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  64116. scene.incrementRenderId();
  64117. scene.resetCachedMaterial();
  64118. }
  64119. }
  64120. else {
  64121. this.renderToTarget(0, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  64122. }
  64123. this.onAfterUnbindObservable.notifyObservers(this);
  64124. if (scene.activeCamera) {
  64125. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  64126. scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));
  64127. }
  64128. engine.setViewport(scene.activeCamera.viewport);
  64129. }
  64130. scene.resetCachedMaterial();
  64131. };
  64132. RenderTargetTexture.prototype._bestReflectionRenderTargetDimension = function (renderDimension, scale) {
  64133. var minimum = 128;
  64134. var x = renderDimension * scale;
  64135. var curved = BABYLON.Tools.NearestPOT(x + (minimum * minimum / (minimum + x)));
  64136. // Ensure we don't exceed the render dimension (while staying POT)
  64137. return Math.min(BABYLON.Tools.FloorPOT(renderDimension), curved);
  64138. };
  64139. RenderTargetTexture.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  64140. var _this = this;
  64141. if (!this._texture) {
  64142. return;
  64143. }
  64144. engine.unBindFramebuffer(this._texture, this.isCube, function () {
  64145. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  64146. });
  64147. };
  64148. RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug) {
  64149. var scene = this.getScene();
  64150. if (!scene) {
  64151. return;
  64152. }
  64153. var engine = scene.getEngine();
  64154. if (!this._texture) {
  64155. return;
  64156. }
  64157. // Bind
  64158. if (this._postProcessManager) {
  64159. this._postProcessManager._prepareFrame(this._texture, this._postProcesses);
  64160. }
  64161. else if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  64162. if (this._texture) {
  64163. engine.bindFramebuffer(this._texture, this.isCube ? faceIndex : undefined, undefined, undefined, this.ignoreCameraViewport, this.depthStencilTexture ? this.depthStencilTexture : undefined);
  64164. }
  64165. }
  64166. this.onBeforeRenderObservable.notifyObservers(faceIndex);
  64167. // Clear
  64168. if (this.onClearObservable.hasObservers()) {
  64169. this.onClearObservable.notifyObservers(engine);
  64170. }
  64171. else {
  64172. engine.clear(this.clearColor || scene.clearColor, true, true, true);
  64173. }
  64174. if (!this._doNotChangeAspectRatio) {
  64175. scene.updateTransformMatrix(true);
  64176. }
  64177. // Render
  64178. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  64179. if (this._postProcessManager) {
  64180. this._postProcessManager._finalizeFrame(false, this._texture, faceIndex, this._postProcesses, this.ignoreCameraViewport);
  64181. }
  64182. else if (useCameraPostProcess) {
  64183. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  64184. }
  64185. if (!this._doNotChangeAspectRatio) {
  64186. scene.updateTransformMatrix(true);
  64187. }
  64188. // Dump ?
  64189. if (dumpForDebug) {
  64190. BABYLON.Tools.DumpFramebuffer(this.getRenderWidth(), this.getRenderHeight(), engine);
  64191. }
  64192. // Unbind
  64193. if (!this.isCube || faceIndex === 5) {
  64194. if (this.isCube) {
  64195. if (faceIndex === 5) {
  64196. engine.generateMipMapsForCubemap(this._texture);
  64197. }
  64198. }
  64199. this.unbindFrameBuffer(engine, faceIndex);
  64200. }
  64201. else {
  64202. this.onAfterRenderObservable.notifyObservers(faceIndex);
  64203. }
  64204. };
  64205. /**
  64206. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  64207. * This allowed control for front to back rendering or reversly depending of the special needs.
  64208. *
  64209. * @param renderingGroupId The rendering group id corresponding to its index
  64210. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  64211. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  64212. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  64213. */
  64214. RenderTargetTexture.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  64215. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  64216. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  64217. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  64218. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  64219. };
  64220. /**
  64221. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  64222. *
  64223. * @param renderingGroupId The rendering group id corresponding to its index
  64224. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  64225. */
  64226. RenderTargetTexture.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  64227. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  64228. };
  64229. RenderTargetTexture.prototype.clone = function () {
  64230. var textureSize = this.getSize();
  64231. 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);
  64232. // Base texture
  64233. newTexture.hasAlpha = this.hasAlpha;
  64234. newTexture.level = this.level;
  64235. // RenderTarget Texture
  64236. newTexture.coordinatesMode = this.coordinatesMode;
  64237. if (this.renderList) {
  64238. newTexture.renderList = this.renderList.slice(0);
  64239. }
  64240. return newTexture;
  64241. };
  64242. RenderTargetTexture.prototype.serialize = function () {
  64243. if (!this.name) {
  64244. return null;
  64245. }
  64246. var serializationObject = _super.prototype.serialize.call(this);
  64247. serializationObject.renderTargetSize = this.getRenderSize();
  64248. serializationObject.renderList = [];
  64249. if (this.renderList) {
  64250. for (var index = 0; index < this.renderList.length; index++) {
  64251. serializationObject.renderList.push(this.renderList[index].id);
  64252. }
  64253. }
  64254. return serializationObject;
  64255. };
  64256. // This will remove the attached framebuffer objects. The texture will not be able to be used as render target anymore
  64257. RenderTargetTexture.prototype.disposeFramebufferObjects = function () {
  64258. var objBuffer = this.getInternalTexture();
  64259. var scene = this.getScene();
  64260. if (objBuffer && scene) {
  64261. scene.getEngine()._releaseFramebufferObjects(objBuffer);
  64262. }
  64263. };
  64264. RenderTargetTexture.prototype.dispose = function () {
  64265. if (this._postProcessManager) {
  64266. this._postProcessManager.dispose();
  64267. this._postProcessManager = null;
  64268. }
  64269. this.clearPostProcesses(true);
  64270. if (this._resizeObserver) {
  64271. this.getScene().getEngine().onResizeObservable.remove(this._resizeObserver);
  64272. this._resizeObserver = null;
  64273. }
  64274. this.renderList = null;
  64275. // Remove from custom render targets
  64276. var scene = this.getScene();
  64277. if (!scene) {
  64278. return;
  64279. }
  64280. var index = scene.customRenderTargets.indexOf(this);
  64281. if (index >= 0) {
  64282. scene.customRenderTargets.splice(index, 1);
  64283. }
  64284. for (var _i = 0, _a = scene.cameras; _i < _a.length; _i++) {
  64285. var camera = _a[_i];
  64286. index = camera.customRenderTargets.indexOf(this);
  64287. if (index >= 0) {
  64288. camera.customRenderTargets.splice(index, 1);
  64289. }
  64290. }
  64291. _super.prototype.dispose.call(this);
  64292. };
  64293. RenderTargetTexture.prototype._rebuild = function () {
  64294. if (this.refreshRate === RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  64295. this.refreshRate = RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  64296. }
  64297. if (this._postProcessManager) {
  64298. this._postProcessManager._rebuild();
  64299. }
  64300. };
  64301. /**
  64302. * Clear the info related to rendering groups preventing retention point in material dispose.
  64303. */
  64304. RenderTargetTexture.prototype.freeRenderingGroups = function () {
  64305. if (this._renderingManager) {
  64306. this._renderingManager.freeRenderingGroups();
  64307. }
  64308. };
  64309. RenderTargetTexture._REFRESHRATE_RENDER_ONCE = 0;
  64310. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME = 1;
  64311. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
  64312. return RenderTargetTexture;
  64313. }(BABYLON.Texture));
  64314. BABYLON.RenderTargetTexture = RenderTargetTexture;
  64315. })(BABYLON || (BABYLON = {}));
  64316. //# sourceMappingURL=babylon.renderTargetTexture.js.map
  64317. var BABYLON;
  64318. (function (BABYLON) {
  64319. ;
  64320. var MultiRenderTarget = /** @class */ (function (_super) {
  64321. __extends(MultiRenderTarget, _super);
  64322. function MultiRenderTarget(name, size, count, scene, options) {
  64323. var _this = this;
  64324. var generateMipMaps = options && options.generateMipMaps ? options.generateMipMaps : false;
  64325. var generateDepthTexture = options && options.generateDepthTexture ? options.generateDepthTexture : false;
  64326. var doNotChangeAspectRatio = !options || options.doNotChangeAspectRatio === undefined ? true : options.doNotChangeAspectRatio;
  64327. _this = _super.call(this, name, size, scene, generateMipMaps, doNotChangeAspectRatio) || this;
  64328. _this._engine = scene.getEngine();
  64329. if (!_this.isSupported) {
  64330. _this.dispose();
  64331. return;
  64332. }
  64333. var types = [];
  64334. var samplingModes = [];
  64335. for (var i = 0; i < count; i++) {
  64336. if (options && options.types && options.types[i] !== undefined) {
  64337. types.push(options.types[i]);
  64338. }
  64339. else {
  64340. types.push(options && options.defaultType ? options.defaultType : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  64341. }
  64342. if (options && options.samplingModes && options.samplingModes[i] !== undefined) {
  64343. samplingModes.push(options.samplingModes[i]);
  64344. }
  64345. else {
  64346. samplingModes.push(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  64347. }
  64348. }
  64349. var generateDepthBuffer = !options || options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  64350. var generateStencilBuffer = !options || options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  64351. _this._size = size;
  64352. _this._multiRenderTargetOptions = {
  64353. samplingModes: samplingModes,
  64354. generateMipMaps: generateMipMaps,
  64355. generateDepthBuffer: generateDepthBuffer,
  64356. generateStencilBuffer: generateStencilBuffer,
  64357. generateDepthTexture: generateDepthTexture,
  64358. types: types,
  64359. textureCount: count
  64360. };
  64361. _this._createInternalTextures();
  64362. _this._createTextures();
  64363. return _this;
  64364. }
  64365. Object.defineProperty(MultiRenderTarget.prototype, "isSupported", {
  64366. get: function () {
  64367. return this._engine.webGLVersion > 1 || this._engine.getCaps().drawBuffersExtension;
  64368. },
  64369. enumerable: true,
  64370. configurable: true
  64371. });
  64372. Object.defineProperty(MultiRenderTarget.prototype, "textures", {
  64373. get: function () {
  64374. return this._textures;
  64375. },
  64376. enumerable: true,
  64377. configurable: true
  64378. });
  64379. Object.defineProperty(MultiRenderTarget.prototype, "depthTexture", {
  64380. get: function () {
  64381. return this._textures[this._textures.length - 1];
  64382. },
  64383. enumerable: true,
  64384. configurable: true
  64385. });
  64386. Object.defineProperty(MultiRenderTarget.prototype, "wrapU", {
  64387. set: function (wrap) {
  64388. if (this._textures) {
  64389. for (var i = 0; i < this._textures.length; i++) {
  64390. this._textures[i].wrapU = wrap;
  64391. }
  64392. }
  64393. },
  64394. enumerable: true,
  64395. configurable: true
  64396. });
  64397. Object.defineProperty(MultiRenderTarget.prototype, "wrapV", {
  64398. set: function (wrap) {
  64399. if (this._textures) {
  64400. for (var i = 0; i < this._textures.length; i++) {
  64401. this._textures[i].wrapV = wrap;
  64402. }
  64403. }
  64404. },
  64405. enumerable: true,
  64406. configurable: true
  64407. });
  64408. MultiRenderTarget.prototype._rebuild = function () {
  64409. this.releaseInternalTextures();
  64410. this._createInternalTextures();
  64411. for (var i = 0; i < this._internalTextures.length; i++) {
  64412. var texture = this._textures[i];
  64413. texture._texture = this._internalTextures[i];
  64414. }
  64415. // Keeps references to frame buffer and stencil/depth buffer
  64416. this._texture = this._internalTextures[0];
  64417. };
  64418. MultiRenderTarget.prototype._createInternalTextures = function () {
  64419. this._internalTextures = this._engine.createMultipleRenderTarget(this._size, this._multiRenderTargetOptions);
  64420. };
  64421. MultiRenderTarget.prototype._createTextures = function () {
  64422. this._textures = [];
  64423. for (var i = 0; i < this._internalTextures.length; i++) {
  64424. var texture = new BABYLON.Texture(null, this.getScene());
  64425. texture._texture = this._internalTextures[i];
  64426. this._textures.push(texture);
  64427. }
  64428. // Keeps references to frame buffer and stencil/depth buffer
  64429. this._texture = this._internalTextures[0];
  64430. };
  64431. Object.defineProperty(MultiRenderTarget.prototype, "samples", {
  64432. get: function () {
  64433. return this._samples;
  64434. },
  64435. set: function (value) {
  64436. if (this._samples === value) {
  64437. return;
  64438. }
  64439. this._samples = this._engine.updateMultipleRenderTargetTextureSampleCount(this._internalTextures, value);
  64440. },
  64441. enumerable: true,
  64442. configurable: true
  64443. });
  64444. MultiRenderTarget.prototype.resize = function (size) {
  64445. this.releaseInternalTextures();
  64446. this._internalTextures = this._engine.createMultipleRenderTarget(size, this._multiRenderTargetOptions);
  64447. this._createInternalTextures();
  64448. };
  64449. MultiRenderTarget.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  64450. var _this = this;
  64451. engine.unBindMultiColorAttachmentFramebuffer(this._internalTextures, this.isCube, function () {
  64452. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  64453. });
  64454. };
  64455. MultiRenderTarget.prototype.dispose = function () {
  64456. this.releaseInternalTextures();
  64457. _super.prototype.dispose.call(this);
  64458. };
  64459. MultiRenderTarget.prototype.releaseInternalTextures = function () {
  64460. if (!this._internalTextures) {
  64461. return;
  64462. }
  64463. for (var i = this._internalTextures.length - 1; i >= 0; i--) {
  64464. if (this._internalTextures[i] !== undefined) {
  64465. this._internalTextures[i].dispose();
  64466. this._internalTextures.splice(i, 1);
  64467. }
  64468. }
  64469. };
  64470. return MultiRenderTarget;
  64471. }(BABYLON.RenderTargetTexture));
  64472. BABYLON.MultiRenderTarget = MultiRenderTarget;
  64473. })(BABYLON || (BABYLON = {}));
  64474. //# sourceMappingURL=babylon.multiRenderTarget.js.map
  64475. var BABYLON;
  64476. (function (BABYLON) {
  64477. var MirrorTexture = /** @class */ (function (_super) {
  64478. __extends(MirrorTexture, _super);
  64479. function MirrorTexture(name, size, scene, generateMipMaps, type, samplingMode, generateDepthBuffer) {
  64480. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  64481. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  64482. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  64483. var _this = _super.call(this, name, size, scene, generateMipMaps, true, type, false, samplingMode, generateDepthBuffer) || this;
  64484. _this.scene = scene;
  64485. _this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  64486. _this._transformMatrix = BABYLON.Matrix.Zero();
  64487. _this._mirrorMatrix = BABYLON.Matrix.Zero();
  64488. _this._adaptiveBlurKernel = 0;
  64489. _this._blurKernelX = 0;
  64490. _this._blurKernelY = 0;
  64491. _this._blurRatio = 1.0;
  64492. _this.ignoreCameraViewport = true;
  64493. _this._updateGammaSpace();
  64494. _this._imageProcessingConfigChangeObserver = scene.imageProcessingConfiguration.onUpdateParameters.add(function () {
  64495. _this._updateGammaSpace;
  64496. });
  64497. _this.onBeforeRenderObservable.add(function () {
  64498. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  64499. _this._savedViewMatrix = scene.getViewMatrix();
  64500. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  64501. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  64502. scene.clipPlane = _this.mirrorPlane;
  64503. scene.getEngine().cullBackFaces = false;
  64504. scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.globalPosition, _this._mirrorMatrix);
  64505. });
  64506. _this.onAfterRenderObservable.add(function () {
  64507. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  64508. scene.getEngine().cullBackFaces = true;
  64509. scene._mirroredCameraPosition = null;
  64510. delete scene.clipPlane;
  64511. });
  64512. return _this;
  64513. }
  64514. Object.defineProperty(MirrorTexture.prototype, "blurRatio", {
  64515. get: function () {
  64516. return this._blurRatio;
  64517. },
  64518. set: function (value) {
  64519. if (this._blurRatio === value) {
  64520. return;
  64521. }
  64522. this._blurRatio = value;
  64523. this._preparePostProcesses();
  64524. },
  64525. enumerable: true,
  64526. configurable: true
  64527. });
  64528. Object.defineProperty(MirrorTexture.prototype, "adaptiveBlurKernel", {
  64529. set: function (value) {
  64530. this._adaptiveBlurKernel = value;
  64531. this._autoComputeBlurKernel();
  64532. },
  64533. enumerable: true,
  64534. configurable: true
  64535. });
  64536. Object.defineProperty(MirrorTexture.prototype, "blurKernel", {
  64537. set: function (value) {
  64538. this.blurKernelX = value;
  64539. this.blurKernelY = value;
  64540. },
  64541. enumerable: true,
  64542. configurable: true
  64543. });
  64544. Object.defineProperty(MirrorTexture.prototype, "blurKernelX", {
  64545. get: function () {
  64546. return this._blurKernelX;
  64547. },
  64548. set: function (value) {
  64549. if (this._blurKernelX === value) {
  64550. return;
  64551. }
  64552. this._blurKernelX = value;
  64553. this._preparePostProcesses();
  64554. },
  64555. enumerable: true,
  64556. configurable: true
  64557. });
  64558. Object.defineProperty(MirrorTexture.prototype, "blurKernelY", {
  64559. get: function () {
  64560. return this._blurKernelY;
  64561. },
  64562. set: function (value) {
  64563. if (this._blurKernelY === value) {
  64564. return;
  64565. }
  64566. this._blurKernelY = value;
  64567. this._preparePostProcesses();
  64568. },
  64569. enumerable: true,
  64570. configurable: true
  64571. });
  64572. MirrorTexture.prototype._autoComputeBlurKernel = function () {
  64573. var engine = this.getScene().getEngine();
  64574. var dw = this.getRenderWidth() / engine.getRenderWidth();
  64575. var dh = this.getRenderHeight() / engine.getRenderHeight();
  64576. this.blurKernelX = this._adaptiveBlurKernel * dw;
  64577. this.blurKernelY = this._adaptiveBlurKernel * dh;
  64578. };
  64579. MirrorTexture.prototype._onRatioRescale = function () {
  64580. if (this._sizeRatio) {
  64581. this.resize(this._initialSizeParameter);
  64582. if (!this._adaptiveBlurKernel) {
  64583. this._preparePostProcesses();
  64584. }
  64585. }
  64586. if (this._adaptiveBlurKernel) {
  64587. this._autoComputeBlurKernel();
  64588. }
  64589. };
  64590. MirrorTexture.prototype._updateGammaSpace = function () {
  64591. this.gammaSpace = !this.scene.imageProcessingConfiguration.isEnabled || !this.scene.imageProcessingConfiguration.applyByPostProcess;
  64592. };
  64593. MirrorTexture.prototype._preparePostProcesses = function () {
  64594. this.clearPostProcesses(true);
  64595. if (this._blurKernelX && this._blurKernelY) {
  64596. var engine = this.getScene().getEngine();
  64597. var textureType = engine.getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  64598. 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);
  64599. this._blurX.autoClear = false;
  64600. if (this._blurRatio === 1 && this.samples < 2 && this._texture) {
  64601. this._blurX.inputTexture = this._texture;
  64602. }
  64603. else {
  64604. this._blurX.alwaysForcePOT = true;
  64605. }
  64606. 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);
  64607. this._blurY.autoClear = false;
  64608. this._blurY.alwaysForcePOT = this._blurRatio !== 1;
  64609. this.addPostProcess(this._blurX);
  64610. this.addPostProcess(this._blurY);
  64611. }
  64612. else {
  64613. if (this._blurY) {
  64614. this.removePostProcess(this._blurY);
  64615. this._blurY.dispose();
  64616. this._blurY = null;
  64617. }
  64618. if (this._blurX) {
  64619. this.removePostProcess(this._blurX);
  64620. this._blurX.dispose();
  64621. this._blurX = null;
  64622. }
  64623. }
  64624. };
  64625. MirrorTexture.prototype.clone = function () {
  64626. var scene = this.getScene();
  64627. if (!scene) {
  64628. return this;
  64629. }
  64630. var textureSize = this.getSize();
  64631. var newTexture = new MirrorTexture(this.name, textureSize.width, scene, this._renderTargetOptions.generateMipMaps, this._renderTargetOptions.type, this._renderTargetOptions.samplingMode, this._renderTargetOptions.generateDepthBuffer);
  64632. // Base texture
  64633. newTexture.hasAlpha = this.hasAlpha;
  64634. newTexture.level = this.level;
  64635. // Mirror Texture
  64636. newTexture.mirrorPlane = this.mirrorPlane.clone();
  64637. if (this.renderList) {
  64638. newTexture.renderList = this.renderList.slice(0);
  64639. }
  64640. return newTexture;
  64641. };
  64642. MirrorTexture.prototype.serialize = function () {
  64643. if (!this.name) {
  64644. return null;
  64645. }
  64646. var serializationObject = _super.prototype.serialize.call(this);
  64647. serializationObject.mirrorPlane = this.mirrorPlane.asArray();
  64648. return serializationObject;
  64649. };
  64650. MirrorTexture.prototype.dispose = function () {
  64651. _super.prototype.dispose.call(this);
  64652. this.scene.imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingConfigChangeObserver);
  64653. };
  64654. return MirrorTexture;
  64655. }(BABYLON.RenderTargetTexture));
  64656. BABYLON.MirrorTexture = MirrorTexture;
  64657. })(BABYLON || (BABYLON = {}));
  64658. //# sourceMappingURL=babylon.mirrorTexture.js.map
  64659. var BABYLON;
  64660. (function (BABYLON) {
  64661. /**
  64662. * Creates a refraction texture used by refraction channel of the standard material.
  64663. * @param name the texture name
  64664. * @param size size of the underlying texture
  64665. * @param scene root scene
  64666. */
  64667. var RefractionTexture = /** @class */ (function (_super) {
  64668. __extends(RefractionTexture, _super);
  64669. function RefractionTexture(name, size, scene, generateMipMaps) {
  64670. var _this = _super.call(this, name, size, scene, generateMipMaps, true) || this;
  64671. _this.refractionPlane = new BABYLON.Plane(0, 1, 0, 1);
  64672. _this.depth = 2.0;
  64673. _this.onBeforeRenderObservable.add(function () {
  64674. scene.clipPlane = _this.refractionPlane;
  64675. });
  64676. _this.onAfterRenderObservable.add(function () {
  64677. delete scene.clipPlane;
  64678. });
  64679. return _this;
  64680. }
  64681. RefractionTexture.prototype.clone = function () {
  64682. var scene = this.getScene();
  64683. if (!scene) {
  64684. return this;
  64685. }
  64686. var textureSize = this.getSize();
  64687. var newTexture = new RefractionTexture(this.name, textureSize.width, scene, this._generateMipMaps);
  64688. // Base texture
  64689. newTexture.hasAlpha = this.hasAlpha;
  64690. newTexture.level = this.level;
  64691. // Refraction Texture
  64692. newTexture.refractionPlane = this.refractionPlane.clone();
  64693. if (this.renderList) {
  64694. newTexture.renderList = this.renderList.slice(0);
  64695. }
  64696. newTexture.depth = this.depth;
  64697. return newTexture;
  64698. };
  64699. RefractionTexture.prototype.serialize = function () {
  64700. if (!this.name) {
  64701. return null;
  64702. }
  64703. var serializationObject = _super.prototype.serialize.call(this);
  64704. serializationObject.mirrorPlane = this.refractionPlane.asArray();
  64705. serializationObject.depth = this.depth;
  64706. return serializationObject;
  64707. };
  64708. return RefractionTexture;
  64709. }(BABYLON.RenderTargetTexture));
  64710. BABYLON.RefractionTexture = RefractionTexture;
  64711. })(BABYLON || (BABYLON = {}));
  64712. //# sourceMappingURL=babylon.refractionTexture.js.map
  64713. var BABYLON;
  64714. (function (BABYLON) {
  64715. /**
  64716. * A class extending {BABYLON.Texture} allowing drawing on a texture
  64717. * @see http://doc.babylonjs.com/how_to/dynamictexture
  64718. */
  64719. var DynamicTexture = /** @class */ (function (_super) {
  64720. __extends(DynamicTexture, _super);
  64721. /**
  64722. * Creates a {BABYLON.DynamicTexture}
  64723. * @param name defines the name of the texture
  64724. * @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
  64725. * @param scene defines the scene where you want the texture
  64726. * @param generateMipMaps defines the use of MinMaps or not (default is false)
  64727. * @param samplingMode defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  64728. * @param format defines the texture format to use (default is BABYLON.Engine.TEXTUREFORMAT_RGBA)
  64729. */
  64730. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode, format) {
  64731. if (scene === void 0) { scene = null; }
  64732. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  64733. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  64734. var _this = _super.call(this, null, scene, !generateMipMaps, undefined, samplingMode, undefined, undefined, undefined, undefined, format) || this;
  64735. _this.name = name;
  64736. _this._engine = _this.getScene().getEngine();
  64737. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  64738. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  64739. _this._generateMipMaps = generateMipMaps;
  64740. if (options.getContext) {
  64741. _this._canvas = options;
  64742. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  64743. }
  64744. else {
  64745. _this._canvas = document.createElement("canvas");
  64746. if (options.width || options.width === 0) {
  64747. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  64748. }
  64749. else {
  64750. _this._texture = _this._engine.createDynamicTexture(options, options, generateMipMaps, samplingMode);
  64751. }
  64752. }
  64753. var textureSize = _this.getSize();
  64754. _this._canvas.width = textureSize.width;
  64755. _this._canvas.height = textureSize.height;
  64756. _this._context = _this._canvas.getContext("2d");
  64757. return _this;
  64758. }
  64759. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  64760. /**
  64761. * Gets the current state of canRescale
  64762. */
  64763. get: function () {
  64764. return true;
  64765. },
  64766. enumerable: true,
  64767. configurable: true
  64768. });
  64769. DynamicTexture.prototype._recreate = function (textureSize) {
  64770. this._canvas.width = textureSize.width;
  64771. this._canvas.height = textureSize.height;
  64772. this.releaseInternalTexture();
  64773. this._texture = this._engine.createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  64774. };
  64775. /**
  64776. * Scales the texture
  64777. * @param ratio the scale factor to apply to both width and height
  64778. */
  64779. DynamicTexture.prototype.scale = function (ratio) {
  64780. var textureSize = this.getSize();
  64781. textureSize.width *= ratio;
  64782. textureSize.height *= ratio;
  64783. this._recreate(textureSize);
  64784. };
  64785. /**
  64786. * Resizes the texture
  64787. * @param width the new width
  64788. * @param height the new height
  64789. */
  64790. DynamicTexture.prototype.scaleTo = function (width, height) {
  64791. var textureSize = this.getSize();
  64792. textureSize.width = width;
  64793. textureSize.height = height;
  64794. this._recreate(textureSize);
  64795. };
  64796. /**
  64797. * Gets the context of the canvas used by the texture
  64798. * @returns the canvas context of the dynamic texture
  64799. */
  64800. DynamicTexture.prototype.getContext = function () {
  64801. return this._context;
  64802. };
  64803. /**
  64804. * Clears the texture
  64805. */
  64806. DynamicTexture.prototype.clear = function () {
  64807. var size = this.getSize();
  64808. this._context.fillRect(0, 0, size.width, size.height);
  64809. };
  64810. /**
  64811. * Updates the texture
  64812. * @param invertY defines the direction for the Y axis (default is true - y increases downwards)
  64813. * @param premulAlpha defines if alpha is stored as premultiplied (default is false)
  64814. */
  64815. DynamicTexture.prototype.update = function (invertY, premulAlpha) {
  64816. if (premulAlpha === void 0) { premulAlpha = false; }
  64817. this._engine.updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY, premulAlpha, this._format || undefined);
  64818. };
  64819. /**
  64820. * Draws text onto the texture
  64821. * @param text defines the text to be drawn
  64822. * @param x defines the placement of the text from the left
  64823. * @param y defines the placement of the text from the top when invertY is true and from the bottom when false
  64824. * @param font defines the font to be used with font-style, font-size, font-name
  64825. * @param color defines the color used for the text
  64826. * @param clearColor defines the color for the canvas, use null to not overwrite canvas
  64827. * @param invertY defines the direction for the Y axis (default is true - y increases downwards)
  64828. * @param update defines whether texture is immediately update (default is true)
  64829. */
  64830. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  64831. if (update === void 0) { update = true; }
  64832. var size = this.getSize();
  64833. if (clearColor) {
  64834. this._context.fillStyle = clearColor;
  64835. this._context.fillRect(0, 0, size.width, size.height);
  64836. }
  64837. this._context.font = font;
  64838. if (x === null || x === undefined) {
  64839. var textSize = this._context.measureText(text);
  64840. x = (size.width - textSize.width) / 2;
  64841. }
  64842. if (y === null || y === undefined) {
  64843. var fontSize = parseInt((font.replace(/\D/g, '')));
  64844. y = (size.height / 2) + (fontSize / 3.65);
  64845. }
  64846. this._context.fillStyle = color;
  64847. this._context.fillText(text, x, y);
  64848. if (update) {
  64849. this.update(invertY);
  64850. }
  64851. };
  64852. /**
  64853. * Clones the texture
  64854. * @returns the clone of the texture.
  64855. */
  64856. DynamicTexture.prototype.clone = function () {
  64857. var scene = this.getScene();
  64858. if (!scene) {
  64859. return this;
  64860. }
  64861. var textureSize = this.getSize();
  64862. var newTexture = new DynamicTexture(this.name, textureSize, scene, this._generateMipMaps);
  64863. // Base texture
  64864. newTexture.hasAlpha = this.hasAlpha;
  64865. newTexture.level = this.level;
  64866. // Dynamic Texture
  64867. newTexture.wrapU = this.wrapU;
  64868. newTexture.wrapV = this.wrapV;
  64869. return newTexture;
  64870. };
  64871. /** @hidden */
  64872. DynamicTexture.prototype._rebuild = function () {
  64873. this.update();
  64874. };
  64875. return DynamicTexture;
  64876. }(BABYLON.Texture));
  64877. BABYLON.DynamicTexture = DynamicTexture;
  64878. })(BABYLON || (BABYLON = {}));
  64879. //# sourceMappingURL=babylon.dynamicTexture.js.map
  64880. var BABYLON;
  64881. (function (BABYLON) {
  64882. var VideoTexture = /** @class */ (function (_super) {
  64883. __extends(VideoTexture, _super);
  64884. /**
  64885. * Creates a video texture.
  64886. * Sample : https://doc.babylonjs.com/how_to/video_texture
  64887. * @param {string | null} name optional name, will detect from video source, if not defined
  64888. * @param {(string | string[] | HTMLVideoElement)} src can be used to provide an url, array of urls or an already setup HTML video element.
  64889. * @param {BABYLON.Scene} scene is obviously the current scene.
  64890. * @param {boolean} generateMipMaps can be used to turn on mipmaps (Can be expensive for videoTextures because they are often updated).
  64891. * @param {boolean} invertY is false by default but can be used to invert video on Y axis
  64892. * @param {number} samplingMode controls the sampling method and is set to TRILINEAR_SAMPLINGMODE by default
  64893. * @param {VideoTextureSettings} [settings] allows finer control over video usage
  64894. */
  64895. function VideoTexture(name, src, scene, generateMipMaps, invertY, samplingMode, settings) {
  64896. if (generateMipMaps === void 0) { generateMipMaps = false; }
  64897. if (invertY === void 0) { invertY = false; }
  64898. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  64899. if (settings === void 0) { settings = {
  64900. autoPlay: true,
  64901. loop: true,
  64902. autoUpdateTexture: true,
  64903. }; }
  64904. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  64905. _this._stillImageCaptured = false;
  64906. _this._createInternalTexture = function () {
  64907. if (_this._texture != null) {
  64908. return;
  64909. }
  64910. if (!_this._engine.needPOTTextures ||
  64911. (BABYLON.Tools.IsExponentOfTwo(_this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(_this.video.videoHeight))) {
  64912. _this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  64913. _this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  64914. }
  64915. else {
  64916. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  64917. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  64918. _this._generateMipMaps = false;
  64919. }
  64920. _this._texture = _this._engine.createDynamicTexture(_this.video.videoWidth, _this.video.videoHeight, _this._generateMipMaps, _this._samplingMode);
  64921. if (!_this.video.autoplay) {
  64922. var oldHandler_1 = _this.video.onplaying;
  64923. _this.video.onplaying = function () {
  64924. _this.video.onplaying = oldHandler_1;
  64925. _this._texture.isReady = true;
  64926. _this._updateInternalTexture();
  64927. _this.video.pause();
  64928. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  64929. _this.onLoadObservable.notifyObservers(_this);
  64930. }
  64931. };
  64932. _this.video.play();
  64933. }
  64934. else {
  64935. _this._texture.isReady = true;
  64936. _this._updateInternalTexture();
  64937. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  64938. _this.onLoadObservable.notifyObservers(_this);
  64939. }
  64940. }
  64941. };
  64942. _this.reset = function () {
  64943. if (_this._texture == null) {
  64944. return;
  64945. }
  64946. _this._texture.dispose();
  64947. _this._texture = null;
  64948. };
  64949. _this._updateInternalTexture = function (e) {
  64950. if (_this._texture == null || !_this._texture.isReady) {
  64951. return;
  64952. }
  64953. if (_this.video.readyState < _this.video.HAVE_CURRENT_DATA) {
  64954. return;
  64955. }
  64956. _this._engine.updateVideoTexture(_this._texture, _this.video, _this._invertY);
  64957. };
  64958. _this._engine = _this.getScene().getEngine();
  64959. _this._generateMipMaps = generateMipMaps;
  64960. _this._samplingMode = samplingMode;
  64961. _this.autoUpdateTexture = settings.autoUpdateTexture;
  64962. _this.name = name || _this._getName(src);
  64963. _this.video = _this._getVideo(src);
  64964. if (settings.autoPlay !== undefined) {
  64965. _this.video.autoplay = settings.autoPlay;
  64966. }
  64967. if (settings.loop !== undefined) {
  64968. _this.video.loop = settings.loop;
  64969. }
  64970. _this.video.addEventListener("canplay", _this._createInternalTexture);
  64971. _this.video.addEventListener("paused", _this._updateInternalTexture);
  64972. _this.video.addEventListener("seeked", _this._updateInternalTexture);
  64973. _this.video.addEventListener("emptied", _this.reset);
  64974. if (_this.video.readyState >= _this.video.HAVE_CURRENT_DATA) {
  64975. _this._createInternalTexture();
  64976. }
  64977. return _this;
  64978. }
  64979. VideoTexture.prototype._getName = function (src) {
  64980. if (src instanceof HTMLVideoElement) {
  64981. return src.currentSrc;
  64982. }
  64983. if (typeof src === "object") {
  64984. return src.toString();
  64985. }
  64986. return src;
  64987. };
  64988. ;
  64989. VideoTexture.prototype._getVideo = function (src) {
  64990. if (src instanceof HTMLVideoElement) {
  64991. BABYLON.Tools.SetCorsBehavior(src.currentSrc, src);
  64992. return src;
  64993. }
  64994. var video = document.createElement("video");
  64995. if (typeof src === "string") {
  64996. BABYLON.Tools.SetCorsBehavior(src, video);
  64997. video.src = src;
  64998. }
  64999. else {
  65000. BABYLON.Tools.SetCorsBehavior(src[0], video);
  65001. src.forEach(function (url) {
  65002. var source = document.createElement("source");
  65003. source.src = url;
  65004. video.appendChild(source);
  65005. });
  65006. }
  65007. return video;
  65008. };
  65009. ;
  65010. /**
  65011. * Internal method to initiate `update`.
  65012. */
  65013. VideoTexture.prototype._rebuild = function () {
  65014. this.update();
  65015. };
  65016. /**
  65017. * Update Texture in the `auto` mode. Does not do anything if `settings.autoUpdateTexture` is false.
  65018. */
  65019. VideoTexture.prototype.update = function () {
  65020. if (!this.autoUpdateTexture) {
  65021. // Expecting user to call `updateTexture` manually
  65022. return;
  65023. }
  65024. this.updateTexture(true);
  65025. };
  65026. /**
  65027. * Update Texture in `manual` mode. Does not do anything if not visible or paused.
  65028. * @param isVisible Visibility state, detected by user using `scene.getActiveMeshes()` or othervise.
  65029. */
  65030. VideoTexture.prototype.updateTexture = function (isVisible) {
  65031. if (!isVisible) {
  65032. return;
  65033. }
  65034. if (this.video.paused && this._stillImageCaptured) {
  65035. return;
  65036. }
  65037. this._stillImageCaptured = true;
  65038. this._updateInternalTexture();
  65039. };
  65040. /**
  65041. * Change video content. Changing video instance or setting multiple urls (as in constructor) is not supported.
  65042. * @param url New url.
  65043. */
  65044. VideoTexture.prototype.updateURL = function (url) {
  65045. this.video.src = url;
  65046. };
  65047. VideoTexture.prototype.dispose = function () {
  65048. _super.prototype.dispose.call(this);
  65049. this.video.removeEventListener("canplay", this._createInternalTexture);
  65050. this.video.removeEventListener("paused", this._updateInternalTexture);
  65051. this.video.removeEventListener("seeked", this._updateInternalTexture);
  65052. this.video.removeEventListener("emptied", this.reset);
  65053. this.video.pause();
  65054. };
  65055. VideoTexture.CreateFromWebCam = function (scene, onReady, constraints) {
  65056. var video = document.createElement("video");
  65057. var constraintsDeviceId;
  65058. if (constraints && constraints.deviceId) {
  65059. constraintsDeviceId = {
  65060. exact: constraints.deviceId,
  65061. };
  65062. }
  65063. window.URL = window.URL || window.webkitURL || window.mozURL || window.msURL;
  65064. if (navigator.mediaDevices) {
  65065. navigator.mediaDevices.getUserMedia({ video: constraints })
  65066. .then(function (stream) {
  65067. if (video.mozSrcObject !== undefined) {
  65068. // hack for Firefox < 19
  65069. video.mozSrcObject = stream;
  65070. }
  65071. else {
  65072. video.srcObject = stream;
  65073. }
  65074. var onPlaying = function () {
  65075. if (onReady) {
  65076. onReady(new VideoTexture("video", video, scene, true, true));
  65077. }
  65078. video.removeEventListener("playing", onPlaying);
  65079. };
  65080. video.addEventListener("playing", onPlaying);
  65081. video.play();
  65082. })
  65083. .catch(function (err) {
  65084. BABYLON.Tools.Error(err.name);
  65085. });
  65086. }
  65087. else {
  65088. navigator.getUserMedia =
  65089. navigator.getUserMedia ||
  65090. navigator.webkitGetUserMedia ||
  65091. navigator.mozGetUserMedia ||
  65092. navigator.msGetUserMedia;
  65093. if (navigator.getUserMedia) {
  65094. navigator.getUserMedia({
  65095. video: {
  65096. deviceId: constraintsDeviceId,
  65097. width: {
  65098. min: (constraints && constraints.minWidth) || 256,
  65099. max: (constraints && constraints.maxWidth) || 640,
  65100. },
  65101. height: {
  65102. min: (constraints && constraints.minHeight) || 256,
  65103. max: (constraints && constraints.maxHeight) || 480,
  65104. },
  65105. },
  65106. }, function (stream) {
  65107. if (video.mozSrcObject !== undefined) {
  65108. // hack for Firefox < 19
  65109. video.mozSrcObject = stream;
  65110. }
  65111. else {
  65112. video.src = (window.URL && window.URL.createObjectURL(stream)) || stream;
  65113. }
  65114. video.play();
  65115. if (onReady) {
  65116. onReady(new VideoTexture("video", video, scene, true, true));
  65117. }
  65118. }, function (e) {
  65119. BABYLON.Tools.Error(e.name);
  65120. });
  65121. }
  65122. }
  65123. };
  65124. return VideoTexture;
  65125. }(BABYLON.Texture));
  65126. BABYLON.VideoTexture = VideoTexture;
  65127. })(BABYLON || (BABYLON = {}));
  65128. //# sourceMappingURL=babylon.videoTexture.js.map
  65129. var BABYLON;
  65130. (function (BABYLON) {
  65131. var RawTexture = /** @class */ (function (_super) {
  65132. __extends(RawTexture, _super);
  65133. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode, type) {
  65134. if (generateMipMaps === void 0) { generateMipMaps = true; }
  65135. if (invertY === void 0) { invertY = false; }
  65136. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  65137. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  65138. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  65139. _this.format = format;
  65140. _this._engine = scene.getEngine();
  65141. _this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode, null, type);
  65142. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  65143. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  65144. return _this;
  65145. }
  65146. RawTexture.prototype.update = function (data) {
  65147. this._engine.updateRawTexture(this._texture, data, this._texture.format, this._texture.invertY, undefined, this._texture.type);
  65148. };
  65149. // Statics
  65150. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  65151. if (generateMipMaps === void 0) { generateMipMaps = true; }
  65152. if (invertY === void 0) { invertY = false; }
  65153. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  65154. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  65155. };
  65156. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  65157. if (generateMipMaps === void 0) { generateMipMaps = true; }
  65158. if (invertY === void 0) { invertY = false; }
  65159. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  65160. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  65161. };
  65162. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  65163. if (generateMipMaps === void 0) { generateMipMaps = true; }
  65164. if (invertY === void 0) { invertY = false; }
  65165. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  65166. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  65167. };
  65168. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  65169. if (generateMipMaps === void 0) { generateMipMaps = true; }
  65170. if (invertY === void 0) { invertY = false; }
  65171. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  65172. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  65173. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode, type);
  65174. };
  65175. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  65176. if (generateMipMaps === void 0) { generateMipMaps = true; }
  65177. if (invertY === void 0) { invertY = false; }
  65178. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  65179. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  65180. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode, type);
  65181. };
  65182. return RawTexture;
  65183. }(BABYLON.Texture));
  65184. BABYLON.RawTexture = RawTexture;
  65185. })(BABYLON || (BABYLON = {}));
  65186. //# sourceMappingURL=babylon.rawTexture.js.map
  65187. var BABYLON;
  65188. (function (BABYLON) {
  65189. /**
  65190. * Class used to store 3D textures containing user data
  65191. */
  65192. var RawTexture3D = /** @class */ (function (_super) {
  65193. __extends(RawTexture3D, _super);
  65194. /**
  65195. * Create a new RawTexture3D
  65196. * @param data defines the data of the texture
  65197. * @param width defines the width of the texture
  65198. * @param height defines the height of the texture
  65199. * @param depth defines the depth of the texture
  65200. * @param format defines the texture format to use
  65201. * @param scene defines the hosting scene
  65202. * @param generateMipMaps defines a boolean indicating if mip levels should be generated (true by default)
  65203. * @param invertY defines if texture must be stored with Y axis inverted
  65204. * @param samplingMode defines the sampling mode to use (BABYLON.Texture.TRILINEAR_SAMPLINGMODE by default)
  65205. * @param textureType defines the texture Type (Engine.TEXTURETYPE_UNSIGNED_INT, Engine.TEXTURETYPE_FLOAT...)
  65206. */
  65207. function RawTexture3D(data, width, height, depth,
  65208. /** Gets or sets the texture format to use */
  65209. format, scene, generateMipMaps, invertY, samplingMode, textureType) {
  65210. if (generateMipMaps === void 0) { generateMipMaps = true; }
  65211. if (invertY === void 0) { invertY = false; }
  65212. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  65213. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  65214. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  65215. _this.format = format;
  65216. _this._engine = scene.getEngine();
  65217. _this._texture = scene.getEngine().createRawTexture3D(data, width, height, depth, format, generateMipMaps, invertY, samplingMode, undefined, textureType);
  65218. _this.is3D = true;
  65219. return _this;
  65220. }
  65221. /**
  65222. * Update the texture with new data
  65223. * @param data defines the data to store in the texture
  65224. */
  65225. RawTexture3D.prototype.update = function (data) {
  65226. if (!this._texture) {
  65227. return;
  65228. }
  65229. this._engine.updateRawTexture3D(this._texture, data, this._texture.format, this._texture.invertY, undefined, this._texture.type);
  65230. };
  65231. return RawTexture3D;
  65232. }(BABYLON.Texture));
  65233. BABYLON.RawTexture3D = RawTexture3D;
  65234. })(BABYLON || (BABYLON = {}));
  65235. //# sourceMappingURL=babylon.rawTexture3D.js.map
  65236. var BABYLON;
  65237. (function (BABYLON) {
  65238. /**
  65239. * PostProcess can be used to apply a shader to a texture after it has been rendered
  65240. * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  65241. */
  65242. var PostProcess = /** @class */ (function () {
  65243. /**
  65244. * Creates a new instance PostProcess
  65245. * @param name The name of the PostProcess.
  65246. * @param fragmentUrl The url of the fragment shader to be used.
  65247. * @param parameters Array of the names of uniform non-sampler2D variables that will be passed to the shader.
  65248. * @param samplers Array of the names of uniform sampler2D variables that will be passed to the shader.
  65249. * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
  65250. * @param camera The camera to apply the render pass to.
  65251. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  65252. * @param engine The engine which the post process will be applied. (default: current engine)
  65253. * @param reusable If the post process can be reused on the same frame. (default: false)
  65254. * @param defines String of defines that will be set when running the fragment shader. (default: null)
  65255. * @param textureType Type of textures used when performing the post process. (default: 0)
  65256. * @param vertexUrl The url of the vertex shader to be used. (default: "postprocess")
  65257. * @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
  65258. * @param blockCompilation If the shader should not be compiled imediatly. (default: false)
  65259. */
  65260. function PostProcess(/** Name of the PostProcess. */ name, fragmentUrl, parameters, samplers, options, camera, samplingMode, engine, reusable, defines, textureType, vertexUrl, indexParameters, blockCompilation) {
  65261. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  65262. if (defines === void 0) { defines = null; }
  65263. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  65264. if (vertexUrl === void 0) { vertexUrl = "postprocess"; }
  65265. if (blockCompilation === void 0) { blockCompilation = false; }
  65266. this.name = name;
  65267. /**
  65268. * Width of the texture to apply the post process on
  65269. */
  65270. this.width = -1;
  65271. /**
  65272. * Height of the texture to apply the post process on
  65273. */
  65274. this.height = -1;
  65275. /**
  65276. * Internal, reference to the location where this postprocess was output to. (Typically the texture on the next postprocess in the chain)
  65277. */
  65278. this._outputTexture = null;
  65279. /**
  65280. * If the buffer needs to be cleared before applying the post process. (default: true)
  65281. * Should be set to false if shader will overwrite all previous pixels.
  65282. */
  65283. this.autoClear = true;
  65284. /**
  65285. * Type of alpha mode to use when performing the post process (default: Engine.ALPHA_DISABLE)
  65286. */
  65287. this.alphaMode = BABYLON.Engine.ALPHA_DISABLE;
  65288. /**
  65289. * Animations to be used for the post processing
  65290. */
  65291. this.animations = new Array();
  65292. /**
  65293. * Enable Pixel Perfect mode where texture is not scaled to be power of 2.
  65294. * Can only be used on a single postprocess or on the last one of a chain. (default: false)
  65295. */
  65296. this.enablePixelPerfectMode = false;
  65297. /**
  65298. * Force the postprocess to be applied without taking in account viewport
  65299. */
  65300. this.forceFullscreenViewport = true;
  65301. /**
  65302. * Scale mode for the post process (default: Engine.SCALEMODE_FLOOR)
  65303. */
  65304. this.scaleMode = BABYLON.Engine.SCALEMODE_FLOOR;
  65305. /**
  65306. * Force textures to be a power of two (default: false)
  65307. */
  65308. this.alwaysForcePOT = false;
  65309. /**
  65310. * Number of sample textures (default: 1)
  65311. */
  65312. this.samples = 1;
  65313. /**
  65314. * Modify the scale of the post process to be the same as the viewport (default: false)
  65315. */
  65316. this.adaptScaleToCurrentViewport = false;
  65317. this._reusable = false;
  65318. /**
  65319. * Smart array of input and output textures for the post process.
  65320. */
  65321. this._textures = new BABYLON.SmartArray(2);
  65322. /**
  65323. * The index in _textures that corresponds to the output texture.
  65324. */
  65325. this._currentRenderTextureInd = 0;
  65326. this._scaleRatio = new BABYLON.Vector2(1, 1);
  65327. this._texelSize = BABYLON.Vector2.Zero();
  65328. // Events
  65329. /**
  65330. * An event triggered when the postprocess is activated.
  65331. */
  65332. this.onActivateObservable = new BABYLON.Observable();
  65333. /**
  65334. * An event triggered when the postprocess changes its size.
  65335. */
  65336. this.onSizeChangedObservable = new BABYLON.Observable();
  65337. /**
  65338. * An event triggered when the postprocess applies its effect.
  65339. */
  65340. this.onApplyObservable = new BABYLON.Observable();
  65341. /**
  65342. * An event triggered before rendering the postprocess
  65343. */
  65344. this.onBeforeRenderObservable = new BABYLON.Observable();
  65345. /**
  65346. * An event triggered after rendering the postprocess
  65347. */
  65348. this.onAfterRenderObservable = new BABYLON.Observable();
  65349. if (camera != null) {
  65350. this._camera = camera;
  65351. this._scene = camera.getScene();
  65352. camera.attachPostProcess(this);
  65353. this._engine = this._scene.getEngine();
  65354. this._scene.postProcesses.push(this);
  65355. }
  65356. else if (engine) {
  65357. this._engine = engine;
  65358. this._engine.postProcesses.push(this);
  65359. }
  65360. this._options = options;
  65361. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  65362. this._reusable = reusable || false;
  65363. this._textureType = textureType;
  65364. this._samplers = samplers || [];
  65365. this._samplers.push("textureSampler");
  65366. this._fragmentUrl = fragmentUrl;
  65367. this._vertexUrl = vertexUrl;
  65368. this._parameters = parameters || [];
  65369. this._parameters.push("scale");
  65370. this._indexParameters = indexParameters;
  65371. if (!blockCompilation) {
  65372. this.updateEffect(defines);
  65373. }
  65374. }
  65375. Object.defineProperty(PostProcess.prototype, "onActivate", {
  65376. /**
  65377. * A function that is added to the onActivateObservable
  65378. */
  65379. set: function (callback) {
  65380. if (this._onActivateObserver) {
  65381. this.onActivateObservable.remove(this._onActivateObserver);
  65382. }
  65383. if (callback) {
  65384. this._onActivateObserver = this.onActivateObservable.add(callback);
  65385. }
  65386. },
  65387. enumerable: true,
  65388. configurable: true
  65389. });
  65390. Object.defineProperty(PostProcess.prototype, "onSizeChanged", {
  65391. /**
  65392. * A function that is added to the onSizeChangedObservable
  65393. */
  65394. set: function (callback) {
  65395. if (this._onSizeChangedObserver) {
  65396. this.onSizeChangedObservable.remove(this._onSizeChangedObserver);
  65397. }
  65398. this._onSizeChangedObserver = this.onSizeChangedObservable.add(callback);
  65399. },
  65400. enumerable: true,
  65401. configurable: true
  65402. });
  65403. Object.defineProperty(PostProcess.prototype, "onApply", {
  65404. /**
  65405. * A function that is added to the onApplyObservable
  65406. */
  65407. set: function (callback) {
  65408. if (this._onApplyObserver) {
  65409. this.onApplyObservable.remove(this._onApplyObserver);
  65410. }
  65411. this._onApplyObserver = this.onApplyObservable.add(callback);
  65412. },
  65413. enumerable: true,
  65414. configurable: true
  65415. });
  65416. Object.defineProperty(PostProcess.prototype, "onBeforeRender", {
  65417. /**
  65418. * A function that is added to the onBeforeRenderObservable
  65419. */
  65420. set: function (callback) {
  65421. if (this._onBeforeRenderObserver) {
  65422. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  65423. }
  65424. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  65425. },
  65426. enumerable: true,
  65427. configurable: true
  65428. });
  65429. Object.defineProperty(PostProcess.prototype, "onAfterRender", {
  65430. /**
  65431. * A function that is added to the onAfterRenderObservable
  65432. */
  65433. set: function (callback) {
  65434. if (this._onAfterRenderObserver) {
  65435. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  65436. }
  65437. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  65438. },
  65439. enumerable: true,
  65440. configurable: true
  65441. });
  65442. Object.defineProperty(PostProcess.prototype, "inputTexture", {
  65443. /**
  65444. * 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
  65445. * render it's output into this texture and this texture will be used as textureSampler in the fragment shader of this post process.
  65446. */
  65447. get: function () {
  65448. return this._textures.data[this._currentRenderTextureInd];
  65449. },
  65450. set: function (value) {
  65451. this._forcedOutputTexture = value;
  65452. },
  65453. enumerable: true,
  65454. configurable: true
  65455. });
  65456. /**
  65457. * Gets the camera which post process is applied to.
  65458. * @returns The camera the post process is applied to.
  65459. */
  65460. PostProcess.prototype.getCamera = function () {
  65461. return this._camera;
  65462. };
  65463. Object.defineProperty(PostProcess.prototype, "texelSize", {
  65464. /**
  65465. * Gets the texel size of the postprocess.
  65466. * See https://en.wikipedia.org/wiki/Texel_(graphics)
  65467. */
  65468. get: function () {
  65469. if (this._shareOutputWithPostProcess) {
  65470. return this._shareOutputWithPostProcess.texelSize;
  65471. }
  65472. if (this._forcedOutputTexture) {
  65473. this._texelSize.copyFromFloats(1.0 / this._forcedOutputTexture.width, 1.0 / this._forcedOutputTexture.height);
  65474. }
  65475. return this._texelSize;
  65476. },
  65477. enumerable: true,
  65478. configurable: true
  65479. });
  65480. /**
  65481. * Gets the engine which this post process belongs to.
  65482. * @returns The engine the post process was enabled with.
  65483. */
  65484. PostProcess.prototype.getEngine = function () {
  65485. return this._engine;
  65486. };
  65487. /**
  65488. * The effect that is created when initializing the post process.
  65489. * @returns The created effect corrisponding the the postprocess.
  65490. */
  65491. PostProcess.prototype.getEffect = function () {
  65492. return this._effect;
  65493. };
  65494. /**
  65495. * To avoid multiple redundant textures for multiple post process, the output the output texture for this post process can be shared with another.
  65496. * @param postProcess The post process to share the output with.
  65497. * @returns This post process.
  65498. */
  65499. PostProcess.prototype.shareOutputWith = function (postProcess) {
  65500. this._disposeTextures();
  65501. this._shareOutputWithPostProcess = postProcess;
  65502. return this;
  65503. };
  65504. /**
  65505. * Reverses the effect of calling shareOutputWith and returns the post process back to its original state.
  65506. * This should be called if the post process that shares output with this post process is disabled/disposed.
  65507. */
  65508. PostProcess.prototype.useOwnOutput = function () {
  65509. if (this._textures.length == 0) {
  65510. this._textures = new BABYLON.SmartArray(2);
  65511. }
  65512. this._shareOutputWithPostProcess = null;
  65513. };
  65514. /**
  65515. * Updates the effect with the current post process compile time values and recompiles the shader.
  65516. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  65517. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  65518. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  65519. * @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
  65520. * @param onCompiled Called when the shader has been compiled.
  65521. * @param onError Called if there is an error when compiling a shader.
  65522. */
  65523. PostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  65524. if (defines === void 0) { defines = null; }
  65525. if (uniforms === void 0) { uniforms = null; }
  65526. if (samplers === void 0) { samplers = null; }
  65527. 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);
  65528. };
  65529. /**
  65530. * The post process is reusable if it can be used multiple times within one frame.
  65531. * @returns If the post process is reusable
  65532. */
  65533. PostProcess.prototype.isReusable = function () {
  65534. return this._reusable;
  65535. };
  65536. /** invalidate frameBuffer to hint the postprocess to create a depth buffer */
  65537. PostProcess.prototype.markTextureDirty = function () {
  65538. this.width = -1;
  65539. };
  65540. /**
  65541. * Activates the post process by intializing the textures to be used when executed. Notifies onActivateObservable.
  65542. * 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.
  65543. * @param camera The camera that will be used in the post process. This camera will be used when calling onActivateObservable.
  65544. * @param sourceTexture The source texture to be inspected to get the width and height if not specified in the post process constructor. (default: null)
  65545. * @param forceDepthStencil If true, a depth and stencil buffer will be generated. (default: false)
  65546. * @returns The target texture that was bound to be written to.
  65547. */
  65548. PostProcess.prototype.activate = function (camera, sourceTexture, forceDepthStencil) {
  65549. var _this = this;
  65550. if (sourceTexture === void 0) { sourceTexture = null; }
  65551. camera = camera || this._camera;
  65552. var scene = camera.getScene();
  65553. var engine = scene.getEngine();
  65554. var maxSize = engine.getCaps().maxTextureSize;
  65555. var requiredWidth = ((sourceTexture ? sourceTexture.width : this._engine.getRenderWidth(true)) * this._options) | 0;
  65556. var requiredHeight = ((sourceTexture ? sourceTexture.height : this._engine.getRenderHeight(true)) * this._options) | 0;
  65557. // 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
  65558. var webVRCamera = camera.parent;
  65559. if (webVRCamera && (webVRCamera.leftCamera == camera || webVRCamera.rightCamera == camera)) {
  65560. requiredWidth /= 2;
  65561. }
  65562. var desiredWidth = (this._options.width || requiredWidth);
  65563. var desiredHeight = this._options.height || requiredHeight;
  65564. if (!this._shareOutputWithPostProcess && !this._forcedOutputTexture) {
  65565. if (this.adaptScaleToCurrentViewport) {
  65566. var currentViewport = engine.currentViewport;
  65567. if (currentViewport) {
  65568. desiredWidth *= currentViewport.width;
  65569. desiredHeight *= currentViewport.height;
  65570. }
  65571. }
  65572. if (this.renderTargetSamplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE || this.alwaysForcePOT) {
  65573. if (!this._options.width) {
  65574. desiredWidth = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize, this.scaleMode) : desiredWidth;
  65575. }
  65576. if (!this._options.height) {
  65577. desiredHeight = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize, this.scaleMode) : desiredHeight;
  65578. }
  65579. }
  65580. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  65581. if (this._textures.length > 0) {
  65582. for (var i = 0; i < this._textures.length; i++) {
  65583. this._engine._releaseTexture(this._textures.data[i]);
  65584. }
  65585. this._textures.reset();
  65586. }
  65587. this.width = desiredWidth;
  65588. this.height = desiredHeight;
  65589. var textureSize = { width: this.width, height: this.height };
  65590. var textureOptions = {
  65591. generateMipMaps: false,
  65592. generateDepthBuffer: forceDepthStencil || camera._postProcesses.indexOf(this) === 0,
  65593. generateStencilBuffer: (forceDepthStencil || camera._postProcesses.indexOf(this) === 0) && this._engine.isStencilEnable,
  65594. samplingMode: this.renderTargetSamplingMode,
  65595. type: this._textureType
  65596. };
  65597. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  65598. if (this._reusable) {
  65599. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  65600. }
  65601. this._texelSize.copyFromFloats(1.0 / this.width, 1.0 / this.height);
  65602. this.onSizeChangedObservable.notifyObservers(this);
  65603. }
  65604. this._textures.forEach(function (texture) {
  65605. if (texture.samples !== _this.samples) {
  65606. _this._engine.updateRenderTargetTextureSampleCount(texture, _this.samples);
  65607. }
  65608. });
  65609. }
  65610. var target;
  65611. if (this._shareOutputWithPostProcess) {
  65612. target = this._shareOutputWithPostProcess.inputTexture;
  65613. }
  65614. else if (this._forcedOutputTexture) {
  65615. target = this._forcedOutputTexture;
  65616. this.width = this._forcedOutputTexture.width;
  65617. this.height = this._forcedOutputTexture.height;
  65618. }
  65619. else {
  65620. target = this.inputTexture;
  65621. }
  65622. // Bind the input of this post process to be used as the output of the previous post process.
  65623. if (this.enablePixelPerfectMode) {
  65624. this._scaleRatio.copyFromFloats(requiredWidth / desiredWidth, requiredHeight / desiredHeight);
  65625. this._engine.bindFramebuffer(target, 0, requiredWidth, requiredHeight, this.forceFullscreenViewport);
  65626. }
  65627. else {
  65628. this._scaleRatio.copyFromFloats(1, 1);
  65629. this._engine.bindFramebuffer(target, 0, undefined, undefined, this.forceFullscreenViewport);
  65630. }
  65631. this.onActivateObservable.notifyObservers(camera);
  65632. // Clear
  65633. if (this.autoClear && this.alphaMode === BABYLON.Engine.ALPHA_DISABLE) {
  65634. this._engine.clear(this.clearColor ? this.clearColor : scene.clearColor, true, true, true);
  65635. }
  65636. if (this._reusable) {
  65637. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  65638. }
  65639. return target;
  65640. };
  65641. Object.defineProperty(PostProcess.prototype, "isSupported", {
  65642. /**
  65643. * If the post process is supported.
  65644. */
  65645. get: function () {
  65646. return this._effect.isSupported;
  65647. },
  65648. enumerable: true,
  65649. configurable: true
  65650. });
  65651. Object.defineProperty(PostProcess.prototype, "aspectRatio", {
  65652. /**
  65653. * The aspect ratio of the output texture.
  65654. */
  65655. get: function () {
  65656. if (this._shareOutputWithPostProcess) {
  65657. return this._shareOutputWithPostProcess.aspectRatio;
  65658. }
  65659. if (this._forcedOutputTexture) {
  65660. return this._forcedOutputTexture.width / this._forcedOutputTexture.height;
  65661. }
  65662. return this.width / this.height;
  65663. },
  65664. enumerable: true,
  65665. configurable: true
  65666. });
  65667. /**
  65668. * Get a value indicating if the post-process is ready to be used
  65669. * @returns true if the post-process is ready (shader is compiled)
  65670. */
  65671. PostProcess.prototype.isReady = function () {
  65672. return this._effect && this._effect.isReady();
  65673. };
  65674. /**
  65675. * Binds all textures and uniforms to the shader, this will be run on every pass.
  65676. * @returns the effect corrisponding to this post process. Null if not compiled or not ready.
  65677. */
  65678. PostProcess.prototype.apply = function () {
  65679. // Check
  65680. if (!this._effect || !this._effect.isReady())
  65681. return null;
  65682. // States
  65683. this._engine.enableEffect(this._effect);
  65684. this._engine.setState(false);
  65685. this._engine.setDepthBuffer(false);
  65686. this._engine.setDepthWrite(false);
  65687. // Alpha
  65688. this._engine.setAlphaMode(this.alphaMode);
  65689. if (this.alphaConstants) {
  65690. this.getEngine().setAlphaConstants(this.alphaConstants.r, this.alphaConstants.g, this.alphaConstants.b, this.alphaConstants.a);
  65691. }
  65692. // Bind the output texture of the preivous post process as the input to this post process.
  65693. var source;
  65694. if (this._shareOutputWithPostProcess) {
  65695. source = this._shareOutputWithPostProcess.inputTexture;
  65696. }
  65697. else if (this._forcedOutputTexture) {
  65698. source = this._forcedOutputTexture;
  65699. }
  65700. else {
  65701. source = this.inputTexture;
  65702. }
  65703. this._effect._bindTexture("textureSampler", source);
  65704. // Parameters
  65705. this._effect.setVector2("scale", this._scaleRatio);
  65706. this.onApplyObservable.notifyObservers(this._effect);
  65707. return this._effect;
  65708. };
  65709. PostProcess.prototype._disposeTextures = function () {
  65710. if (this._shareOutputWithPostProcess || this._forcedOutputTexture) {
  65711. return;
  65712. }
  65713. if (this._textures.length > 0) {
  65714. for (var i = 0; i < this._textures.length; i++) {
  65715. this._engine._releaseTexture(this._textures.data[i]);
  65716. }
  65717. }
  65718. this._textures.dispose();
  65719. };
  65720. /**
  65721. * Disposes the post process.
  65722. * @param camera The camera to dispose the post process on.
  65723. */
  65724. PostProcess.prototype.dispose = function (camera) {
  65725. camera = camera || this._camera;
  65726. this._disposeTextures();
  65727. if (this._scene) {
  65728. var index_1 = this._scene.postProcesses.indexOf(this);
  65729. if (index_1 !== -1) {
  65730. this._scene.postProcesses.splice(index_1, 1);
  65731. }
  65732. }
  65733. else {
  65734. var index_2 = this._engine.postProcesses.indexOf(this);
  65735. if (index_2 !== -1) {
  65736. this._engine.postProcesses.splice(index_2, 1);
  65737. }
  65738. }
  65739. if (!camera) {
  65740. return;
  65741. }
  65742. camera.detachPostProcess(this);
  65743. var index = camera._postProcesses.indexOf(this);
  65744. if (index === 0 && camera._postProcesses.length > 0) {
  65745. var firstPostProcess = this._camera._getFirstPostProcess();
  65746. if (firstPostProcess) {
  65747. firstPostProcess.markTextureDirty();
  65748. }
  65749. }
  65750. this.onActivateObservable.clear();
  65751. this.onAfterRenderObservable.clear();
  65752. this.onApplyObservable.clear();
  65753. this.onBeforeRenderObservable.clear();
  65754. this.onSizeChangedObservable.clear();
  65755. };
  65756. return PostProcess;
  65757. }());
  65758. BABYLON.PostProcess = PostProcess;
  65759. })(BABYLON || (BABYLON = {}));
  65760. //# sourceMappingURL=babylon.postProcess.js.map
  65761. var BABYLON;
  65762. (function (BABYLON) {
  65763. var PassPostProcess = /** @class */ (function (_super) {
  65764. __extends(PassPostProcess, _super);
  65765. function PassPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  65766. if (camera === void 0) { camera = null; }
  65767. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  65768. if (blockCompilation === void 0) { blockCompilation = false; }
  65769. return _super.call(this, name, "pass", null, null, options, camera, samplingMode, engine, reusable, undefined, textureType, undefined, null, blockCompilation) || this;
  65770. }
  65771. return PassPostProcess;
  65772. }(BABYLON.PostProcess));
  65773. BABYLON.PassPostProcess = PassPostProcess;
  65774. })(BABYLON || (BABYLON = {}));
  65775. //# sourceMappingURL=babylon.passPostProcess.js.map
  65776. var __assign = (this && this.__assign) || Object.assign || function(t) {
  65777. for (var s, i = 1, n = arguments.length; i < n; i++) {
  65778. s = arguments[i];
  65779. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  65780. t[p] = s[p];
  65781. }
  65782. return t;
  65783. };
  65784. var BABYLON;
  65785. (function (BABYLON) {
  65786. /**
  65787. * Default implementation IShadowGenerator.
  65788. * This is the main object responsible of generating shadows in the framework.
  65789. * Documentation: https://doc.babylonjs.com/babylon101/shadows
  65790. */
  65791. var ShadowGenerator = /** @class */ (function () {
  65792. /**
  65793. * Creates a ShadowGenerator object.
  65794. * A ShadowGenerator is the required tool to use the shadows.
  65795. * Each light casting shadows needs to use its own ShadowGenerator.
  65796. * Documentation : http://doc.babylonjs.com/tutorials/shadows
  65797. * @param mapSize The size of the texture what stores the shadows. Example : 1024.
  65798. * @param light The light object generating the shadows.
  65799. * @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.
  65800. */
  65801. function ShadowGenerator(mapSize, light, useFullFloatFirst) {
  65802. this._bias = 0.00005;
  65803. this._normalBias = 0;
  65804. this._blurBoxOffset = 1;
  65805. this._blurScale = 2;
  65806. this._blurKernel = 1;
  65807. this._useKernelBlur = false;
  65808. this._filter = ShadowGenerator.FILTER_NONE;
  65809. this._filteringQuality = ShadowGenerator.QUALITY_HIGH;
  65810. this._contactHardeningLightSizeUVRatio = 0.1;
  65811. this._darkness = 0;
  65812. this._transparencyShadow = false;
  65813. /**
  65814. * Controls the extent to which the shadows fade out at the edge of the frustum
  65815. * Used only by directionals and spots
  65816. */
  65817. this.frustumEdgeFalloff = 0;
  65818. /**
  65819. * If true the shadow map is generated by rendering the back face of the mesh instead of the front face.
  65820. * This can help with self-shadowing as the geometry making up the back of objects is slightly offset.
  65821. * It might on the other hand introduce peter panning.
  65822. */
  65823. this.forceBackFacesOnly = false;
  65824. this._lightDirection = BABYLON.Vector3.Zero();
  65825. this._viewMatrix = BABYLON.Matrix.Zero();
  65826. this._projectionMatrix = BABYLON.Matrix.Zero();
  65827. this._transformMatrix = BABYLON.Matrix.Zero();
  65828. this._cachedPosition = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  65829. this._cachedDirection = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  65830. this._currentFaceIndex = 0;
  65831. this._currentFaceIndexCache = 0;
  65832. this._defaultTextureMatrix = BABYLON.Matrix.Identity();
  65833. this._mapSize = mapSize;
  65834. this._light = light;
  65835. this._scene = light.getScene();
  65836. light._shadowGenerator = this;
  65837. // Texture type fallback from float to int if not supported.
  65838. var caps = this._scene.getEngine().getCaps();
  65839. if (!useFullFloatFirst) {
  65840. if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  65841. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  65842. }
  65843. else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  65844. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  65845. }
  65846. else {
  65847. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  65848. }
  65849. }
  65850. else {
  65851. if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  65852. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  65853. }
  65854. else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  65855. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  65856. }
  65857. else {
  65858. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  65859. }
  65860. }
  65861. this._initializeGenerator();
  65862. this._applyFilterValues();
  65863. }
  65864. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  65865. /**
  65866. * Gets the bias: offset applied on the depth preventing acnea (in light direction).
  65867. */
  65868. get: function () {
  65869. return this._bias;
  65870. },
  65871. /**
  65872. * Sets the bias: offset applied on the depth preventing acnea (in light direction).
  65873. */
  65874. set: function (bias) {
  65875. this._bias = bias;
  65876. },
  65877. enumerable: true,
  65878. configurable: true
  65879. });
  65880. Object.defineProperty(ShadowGenerator.prototype, "normalBias", {
  65881. /**
  65882. * Gets the normalBias: offset applied on the depth preventing acnea (along side the normal direction and proportinal to the light/normal angle).
  65883. */
  65884. get: function () {
  65885. return this._normalBias;
  65886. },
  65887. /**
  65888. * Sets the normalBias: offset applied on the depth preventing acnea (along side the normal direction and proportinal to the light/normal angle).
  65889. */
  65890. set: function (normalBias) {
  65891. this._normalBias = normalBias;
  65892. },
  65893. enumerable: true,
  65894. configurable: true
  65895. });
  65896. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  65897. /**
  65898. * Gets the blur box offset: offset applied during the blur pass.
  65899. * Only usefull if useKernelBlur = false
  65900. */
  65901. get: function () {
  65902. return this._blurBoxOffset;
  65903. },
  65904. /**
  65905. * Sets the blur box offset: offset applied during the blur pass.
  65906. * Only usefull if useKernelBlur = false
  65907. */
  65908. set: function (value) {
  65909. if (this._blurBoxOffset === value) {
  65910. return;
  65911. }
  65912. this._blurBoxOffset = value;
  65913. this._disposeBlurPostProcesses();
  65914. },
  65915. enumerable: true,
  65916. configurable: true
  65917. });
  65918. Object.defineProperty(ShadowGenerator.prototype, "blurScale", {
  65919. /**
  65920. * Gets the blur scale: scale of the blurred texture compared to the main shadow map.
  65921. * 2 means half of the size.
  65922. */
  65923. get: function () {
  65924. return this._blurScale;
  65925. },
  65926. /**
  65927. * Sets the blur scale: scale of the blurred texture compared to the main shadow map.
  65928. * 2 means half of the size.
  65929. */
  65930. set: function (value) {
  65931. if (this._blurScale === value) {
  65932. return;
  65933. }
  65934. this._blurScale = value;
  65935. this._disposeBlurPostProcesses();
  65936. },
  65937. enumerable: true,
  65938. configurable: true
  65939. });
  65940. Object.defineProperty(ShadowGenerator.prototype, "blurKernel", {
  65941. /**
  65942. * Gets the blur kernel: kernel size of the blur pass.
  65943. * Only usefull if useKernelBlur = true
  65944. */
  65945. get: function () {
  65946. return this._blurKernel;
  65947. },
  65948. /**
  65949. * Sets the blur kernel: kernel size of the blur pass.
  65950. * Only usefull if useKernelBlur = true
  65951. */
  65952. set: function (value) {
  65953. if (this._blurKernel === value) {
  65954. return;
  65955. }
  65956. this._blurKernel = value;
  65957. this._disposeBlurPostProcesses();
  65958. },
  65959. enumerable: true,
  65960. configurable: true
  65961. });
  65962. Object.defineProperty(ShadowGenerator.prototype, "useKernelBlur", {
  65963. /**
  65964. * Gets whether the blur pass is a kernel blur (if true) or box blur.
  65965. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  65966. */
  65967. get: function () {
  65968. return this._useKernelBlur;
  65969. },
  65970. /**
  65971. * Sets whether the blur pass is a kernel blur (if true) or box blur.
  65972. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  65973. */
  65974. set: function (value) {
  65975. if (this._useKernelBlur === value) {
  65976. return;
  65977. }
  65978. this._useKernelBlur = value;
  65979. this._disposeBlurPostProcesses();
  65980. },
  65981. enumerable: true,
  65982. configurable: true
  65983. });
  65984. Object.defineProperty(ShadowGenerator.prototype, "depthScale", {
  65985. /**
  65986. * Gets the depth scale used in ESM mode.
  65987. */
  65988. get: function () {
  65989. return this._depthScale !== undefined ? this._depthScale : this._light.getDepthScale();
  65990. },
  65991. /**
  65992. * Sets the depth scale used in ESM mode.
  65993. * This can override the scale stored on the light.
  65994. */
  65995. set: function (value) {
  65996. this._depthScale = value;
  65997. },
  65998. enumerable: true,
  65999. configurable: true
  66000. });
  66001. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  66002. /**
  66003. * Gets the current mode of the shadow generator (normal, PCF, ESM...).
  66004. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  66005. */
  66006. get: function () {
  66007. return this._filter;
  66008. },
  66009. /**
  66010. * Sets the current mode of the shadow generator (normal, PCF, ESM...).
  66011. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  66012. */
  66013. set: function (value) {
  66014. // Blurring the cubemap is going to be too expensive. Reverting to unblurred version
  66015. if (this._light.needCube()) {
  66016. if (value === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  66017. this.useExponentialShadowMap = true;
  66018. return;
  66019. }
  66020. else if (value === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  66021. this.useCloseExponentialShadowMap = true;
  66022. return;
  66023. }
  66024. // PCF on cubemap would also be expensive
  66025. else if (value === ShadowGenerator.FILTER_PCF || value === ShadowGenerator.FILTER_PCSS) {
  66026. this.usePoissonSampling = true;
  66027. return;
  66028. }
  66029. }
  66030. // Weblg1 fallback for PCF.
  66031. if (value === ShadowGenerator.FILTER_PCF || value === ShadowGenerator.FILTER_PCSS) {
  66032. if (this._scene.getEngine().webGLVersion === 1) {
  66033. this.usePoissonSampling = true;
  66034. return;
  66035. }
  66036. }
  66037. if (this._filter === value) {
  66038. return;
  66039. }
  66040. this._filter = value;
  66041. this._disposeBlurPostProcesses();
  66042. this._applyFilterValues();
  66043. this._light._markMeshesAsLightDirty();
  66044. },
  66045. enumerable: true,
  66046. configurable: true
  66047. });
  66048. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  66049. /**
  66050. * Gets if the current filter is set to Poisson Sampling.
  66051. */
  66052. get: function () {
  66053. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING;
  66054. },
  66055. /**
  66056. * Sets the current filter to Poisson Sampling.
  66057. */
  66058. set: function (value) {
  66059. if (!value && this.filter !== ShadowGenerator.FILTER_POISSONSAMPLING) {
  66060. return;
  66061. }
  66062. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  66063. },
  66064. enumerable: true,
  66065. configurable: true
  66066. });
  66067. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  66068. /**
  66069. * Gets if the current filter is set to VSM.
  66070. * DEPRECATED. Should use useExponentialShadowMap instead.
  66071. */
  66072. get: function () {
  66073. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  66074. return this.useExponentialShadowMap;
  66075. },
  66076. /**
  66077. * Sets the current filter is to VSM.
  66078. * DEPRECATED. Should use useExponentialShadowMap instead.
  66079. */
  66080. set: function (value) {
  66081. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  66082. this.useExponentialShadowMap = value;
  66083. },
  66084. enumerable: true,
  66085. configurable: true
  66086. });
  66087. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  66088. /**
  66089. * Gets if the current filter is set to blurred VSM.
  66090. * DEPRECATED. Should use useBlurExponentialShadowMap instead.
  66091. */
  66092. get: function () {
  66093. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  66094. return this.useBlurExponentialShadowMap;
  66095. },
  66096. /**
  66097. * Sets the current filter is to blurred VSM.
  66098. * DEPRECATED. Should use useBlurExponentialShadowMap instead.
  66099. */
  66100. set: function (value) {
  66101. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  66102. this.useBlurExponentialShadowMap = value;
  66103. },
  66104. enumerable: true,
  66105. configurable: true
  66106. });
  66107. Object.defineProperty(ShadowGenerator.prototype, "useExponentialShadowMap", {
  66108. /**
  66109. * Gets if the current filter is set to ESM.
  66110. */
  66111. get: function () {
  66112. return this.filter === ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP;
  66113. },
  66114. /**
  66115. * Sets the current filter is to ESM.
  66116. */
  66117. set: function (value) {
  66118. if (!value && this.filter !== ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP) {
  66119. return;
  66120. }
  66121. this.filter = (value ? ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  66122. },
  66123. enumerable: true,
  66124. configurable: true
  66125. });
  66126. Object.defineProperty(ShadowGenerator.prototype, "useBlurExponentialShadowMap", {
  66127. /**
  66128. * Gets if the current filter is set to filtered ESM.
  66129. */
  66130. get: function () {
  66131. return this.filter === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP;
  66132. },
  66133. /**
  66134. * Gets if the current filter is set to filtered ESM.
  66135. */
  66136. set: function (value) {
  66137. if (!value && this.filter !== ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  66138. return;
  66139. }
  66140. this.filter = (value ? ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  66141. },
  66142. enumerable: true,
  66143. configurable: true
  66144. });
  66145. Object.defineProperty(ShadowGenerator.prototype, "useCloseExponentialShadowMap", {
  66146. /**
  66147. * Gets if the current filter is set to "close ESM" (using the inverse of the
  66148. * exponential to prevent steep falloff artifacts).
  66149. */
  66150. get: function () {
  66151. return this.filter === ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP;
  66152. },
  66153. /**
  66154. * Sets the current filter to "close ESM" (using the inverse of the
  66155. * exponential to prevent steep falloff artifacts).
  66156. */
  66157. set: function (value) {
  66158. if (!value && this.filter !== ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP) {
  66159. return;
  66160. }
  66161. this.filter = (value ? ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  66162. },
  66163. enumerable: true,
  66164. configurable: true
  66165. });
  66166. Object.defineProperty(ShadowGenerator.prototype, "useBlurCloseExponentialShadowMap", {
  66167. /**
  66168. * Gets if the current filter is set to filtered "close ESM" (using the inverse of the
  66169. * exponential to prevent steep falloff artifacts).
  66170. */
  66171. get: function () {
  66172. return this.filter === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  66173. },
  66174. /**
  66175. * Sets the current filter to filtered "close ESM" (using the inverse of the
  66176. * exponential to prevent steep falloff artifacts).
  66177. */
  66178. set: function (value) {
  66179. if (!value && this.filter !== ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  66180. return;
  66181. }
  66182. this.filter = (value ? ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  66183. },
  66184. enumerable: true,
  66185. configurable: true
  66186. });
  66187. Object.defineProperty(ShadowGenerator.prototype, "usePercentageCloserFiltering", {
  66188. /**
  66189. * Gets if the current filter is set to "PCF" (percentage closer filtering).
  66190. */
  66191. get: function () {
  66192. return this.filter === ShadowGenerator.FILTER_PCF;
  66193. },
  66194. /**
  66195. * Sets the current filter to "PCF" (percentage closer filtering).
  66196. */
  66197. set: function (value) {
  66198. if (!value && this.filter !== ShadowGenerator.FILTER_PCF) {
  66199. return;
  66200. }
  66201. this.filter = (value ? ShadowGenerator.FILTER_PCF : ShadowGenerator.FILTER_NONE);
  66202. },
  66203. enumerable: true,
  66204. configurable: true
  66205. });
  66206. Object.defineProperty(ShadowGenerator.prototype, "filteringQuality", {
  66207. /**
  66208. * Gets the PCF or PCSS Quality.
  66209. * Only valid if usePercentageCloserFiltering or usePercentageCloserFiltering is true.
  66210. */
  66211. get: function () {
  66212. return this._filteringQuality;
  66213. },
  66214. /**
  66215. * Sets the PCF or PCSS Quality.
  66216. * Only valid if usePercentageCloserFiltering or usePercentageCloserFiltering is true.
  66217. */
  66218. set: function (filteringQuality) {
  66219. this._filteringQuality = filteringQuality;
  66220. },
  66221. enumerable: true,
  66222. configurable: true
  66223. });
  66224. Object.defineProperty(ShadowGenerator.prototype, "useContactHardeningShadow", {
  66225. /**
  66226. * Gets if the current filter is set to "PCSS" (contact hardening).
  66227. */
  66228. get: function () {
  66229. return this.filter === ShadowGenerator.FILTER_PCSS;
  66230. },
  66231. /**
  66232. * Sets the current filter to "PCSS" (contact hardening).
  66233. */
  66234. set: function (value) {
  66235. if (!value && this.filter !== ShadowGenerator.FILTER_PCSS) {
  66236. return;
  66237. }
  66238. this.filter = (value ? ShadowGenerator.FILTER_PCSS : ShadowGenerator.FILTER_NONE);
  66239. },
  66240. enumerable: true,
  66241. configurable: true
  66242. });
  66243. Object.defineProperty(ShadowGenerator.prototype, "contactHardeningLightSizeUVRatio", {
  66244. /**
  66245. * Gets the Light Size (in shadow map uv unit) used in PCSS to determine the blocker search area and the penumbra size.
  66246. * Using a ratio helps keeping shape stability independently of the map size.
  66247. *
  66248. * It does not account for the light projection as it was having too much
  66249. * instability during the light setup or during light position changes.
  66250. *
  66251. * Only valid if useContactHardeningShadow is true.
  66252. */
  66253. get: function () {
  66254. return this._contactHardeningLightSizeUVRatio;
  66255. },
  66256. /**
  66257. * Sets the Light Size (in shadow map uv unit) used in PCSS to determine the blocker search area and the penumbra size.
  66258. * Using a ratio helps keeping shape stability independently of the map size.
  66259. *
  66260. * It does not account for the light projection as it was having too much
  66261. * instability during the light setup or during light position changes.
  66262. *
  66263. * Only valid if useContactHardeningShadow is true.
  66264. */
  66265. set: function (contactHardeningLightSizeUVRatio) {
  66266. this._contactHardeningLightSizeUVRatio = contactHardeningLightSizeUVRatio;
  66267. },
  66268. enumerable: true,
  66269. configurable: true
  66270. });
  66271. /**
  66272. * Returns the darkness value (float). This can only decrease the actual darkness of a shadow.
  66273. * 0 means strongest and 1 would means no shadow.
  66274. * @returns the darkness.
  66275. */
  66276. ShadowGenerator.prototype.getDarkness = function () {
  66277. return this._darkness;
  66278. };
  66279. /**
  66280. * Sets the darkness value (float). This can only decrease the actual darkness of a shadow.
  66281. * @param darkness The darkness value 0 means strongest and 1 would means no shadow.
  66282. * @returns the shadow generator allowing fluent coding.
  66283. */
  66284. ShadowGenerator.prototype.setDarkness = function (darkness) {
  66285. if (darkness >= 1.0)
  66286. this._darkness = 1.0;
  66287. else if (darkness <= 0.0)
  66288. this._darkness = 0.0;
  66289. else
  66290. this._darkness = darkness;
  66291. return this;
  66292. };
  66293. /**
  66294. * Sets the ability to have transparent shadow (boolean).
  66295. * @param transparent True if transparent else False
  66296. * @returns the shadow generator allowing fluent coding
  66297. */
  66298. ShadowGenerator.prototype.setTransparencyShadow = function (transparent) {
  66299. this._transparencyShadow = transparent;
  66300. return this;
  66301. };
  66302. /**
  66303. * Gets the main RTT containing the shadow map (usually storing depth from the light point of view).
  66304. * @returns The render target texture if present otherwise, null
  66305. */
  66306. ShadowGenerator.prototype.getShadowMap = function () {
  66307. return this._shadowMap;
  66308. };
  66309. /**
  66310. * Gets the RTT used during rendering (can be a blurred version of the shadow map or the shadow map itself).
  66311. * @returns The render target texture if the shadow map is present otherwise, null
  66312. */
  66313. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  66314. if (this._shadowMap2) {
  66315. return this._shadowMap2;
  66316. }
  66317. return this._shadowMap;
  66318. };
  66319. /**
  66320. * Helper function to add a mesh and its descendants to the list of shadow casters.
  66321. * @param mesh Mesh to add
  66322. * @param includeDescendants boolean indicating if the descendants should be added. Default to true
  66323. * @returns the Shadow Generator itself
  66324. */
  66325. ShadowGenerator.prototype.addShadowCaster = function (mesh, includeDescendants) {
  66326. if (includeDescendants === void 0) { includeDescendants = true; }
  66327. if (!this._shadowMap) {
  66328. return this;
  66329. }
  66330. if (!this._shadowMap.renderList) {
  66331. this._shadowMap.renderList = [];
  66332. }
  66333. this._shadowMap.renderList.push(mesh);
  66334. if (includeDescendants) {
  66335. (_a = this._shadowMap.renderList).push.apply(_a, mesh.getChildMeshes());
  66336. }
  66337. return this;
  66338. var _a;
  66339. };
  66340. /**
  66341. * Helper function to remove a mesh and its descendants from the list of shadow casters
  66342. * @param mesh Mesh to remove
  66343. * @param includeDescendants boolean indicating if the descendants should be removed. Default to true
  66344. * @returns the Shadow Generator itself
  66345. */
  66346. ShadowGenerator.prototype.removeShadowCaster = function (mesh, includeDescendants) {
  66347. if (includeDescendants === void 0) { includeDescendants = true; }
  66348. if (!this._shadowMap || !this._shadowMap.renderList) {
  66349. return this;
  66350. }
  66351. var index = this._shadowMap.renderList.indexOf(mesh);
  66352. if (index !== -1) {
  66353. this._shadowMap.renderList.splice(index, 1);
  66354. }
  66355. if (includeDescendants) {
  66356. for (var _i = 0, _a = mesh.getChildren(); _i < _a.length; _i++) {
  66357. var child = _a[_i];
  66358. this.removeShadowCaster(child);
  66359. }
  66360. }
  66361. return this;
  66362. };
  66363. /**
  66364. * Returns the associated light object.
  66365. * @returns the light generating the shadow
  66366. */
  66367. ShadowGenerator.prototype.getLight = function () {
  66368. return this._light;
  66369. };
  66370. ShadowGenerator.prototype._initializeGenerator = function () {
  66371. this._light._markMeshesAsLightDirty();
  66372. this._initializeShadowMap();
  66373. };
  66374. ShadowGenerator.prototype._initializeShadowMap = function () {
  66375. var _this = this;
  66376. // Render target
  66377. var engine = this._scene.getEngine();
  66378. if (engine.webGLVersion > 1) {
  66379. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube(), undefined, false, false);
  66380. this._shadowMap.createDepthStencilTexture(BABYLON.Engine.LESS, true);
  66381. }
  66382. else {
  66383. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube());
  66384. }
  66385. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  66386. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  66387. this._shadowMap.anisotropicFilteringLevel = 1;
  66388. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  66389. this._shadowMap.renderParticles = false;
  66390. this._shadowMap.ignoreCameraViewport = true;
  66391. // Record Face Index before render.
  66392. this._shadowMap.onBeforeRenderObservable.add(function (faceIndex) {
  66393. _this._currentFaceIndex = faceIndex;
  66394. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  66395. engine.setColorWrite(false);
  66396. }
  66397. });
  66398. // Custom render function.
  66399. this._shadowMap.customRenderFunction = this._renderForShadowMap.bind(this);
  66400. // Blur if required afer render.
  66401. this._shadowMap.onAfterUnbindObservable.add(function () {
  66402. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  66403. engine.setColorWrite(true);
  66404. }
  66405. if (!_this.useBlurExponentialShadowMap && !_this.useBlurCloseExponentialShadowMap) {
  66406. return;
  66407. }
  66408. var shadowMap = _this.getShadowMapForRendering();
  66409. if (shadowMap) {
  66410. _this._scene.postProcessManager.directRender(_this._blurPostProcesses, shadowMap.getInternalTexture(), true);
  66411. }
  66412. });
  66413. // Clear according to the chosen filter.
  66414. var clearZero = new BABYLON.Color4(0, 0, 0, 0);
  66415. var clearOne = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  66416. this._shadowMap.onClearObservable.add(function (engine) {
  66417. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  66418. engine.clear(clearOne, false, true, false);
  66419. }
  66420. else if (_this.useExponentialShadowMap || _this.useBlurExponentialShadowMap) {
  66421. engine.clear(clearZero, true, true, false);
  66422. }
  66423. else {
  66424. engine.clear(clearOne, true, true, false);
  66425. }
  66426. });
  66427. };
  66428. ShadowGenerator.prototype._initializeBlurRTTAndPostProcesses = function () {
  66429. var _this = this;
  66430. var engine = this._scene.getEngine();
  66431. var targetSize = this._mapSize / this.blurScale;
  66432. if (!this.useKernelBlur || this.blurScale !== 1.0) {
  66433. this._shadowMap2 = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap2", targetSize, this._scene, false, true, this._textureType);
  66434. this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  66435. this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  66436. this._shadowMap2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  66437. }
  66438. if (this.useKernelBlur) {
  66439. 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);
  66440. this._kernelBlurXPostprocess.width = targetSize;
  66441. this._kernelBlurXPostprocess.height = targetSize;
  66442. this._kernelBlurXPostprocess.onApplyObservable.add(function (effect) {
  66443. effect.setTexture("textureSampler", _this._shadowMap);
  66444. });
  66445. 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);
  66446. this._kernelBlurXPostprocess.autoClear = false;
  66447. this._kernelBlurYPostprocess.autoClear = false;
  66448. if (this._textureType === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  66449. this._kernelBlurXPostprocess.packedFloat = true;
  66450. this._kernelBlurYPostprocess.packedFloat = true;
  66451. }
  66452. this._blurPostProcesses = [this._kernelBlurXPostprocess, this._kernelBlurYPostprocess];
  66453. }
  66454. else {
  66455. 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);
  66456. this._boxBlurPostprocess.onApplyObservable.add(function (effect) {
  66457. effect.setFloat2("screenSize", targetSize, targetSize);
  66458. effect.setTexture("textureSampler", _this._shadowMap);
  66459. });
  66460. this._boxBlurPostprocess.autoClear = false;
  66461. this._blurPostProcesses = [this._boxBlurPostprocess];
  66462. }
  66463. };
  66464. ShadowGenerator.prototype._renderForShadowMap = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  66465. var index;
  66466. var engine = this._scene.getEngine();
  66467. if (depthOnlySubMeshes.length) {
  66468. engine.setColorWrite(false);
  66469. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  66470. this._renderSubMeshForShadowMap(depthOnlySubMeshes.data[index]);
  66471. }
  66472. engine.setColorWrite(true);
  66473. }
  66474. for (index = 0; index < opaqueSubMeshes.length; index++) {
  66475. this._renderSubMeshForShadowMap(opaqueSubMeshes.data[index]);
  66476. }
  66477. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  66478. this._renderSubMeshForShadowMap(alphaTestSubMeshes.data[index]);
  66479. }
  66480. if (this._transparencyShadow) {
  66481. for (index = 0; index < transparentSubMeshes.length; index++) {
  66482. this._renderSubMeshForShadowMap(transparentSubMeshes.data[index]);
  66483. }
  66484. }
  66485. };
  66486. ShadowGenerator.prototype._renderSubMeshForShadowMap = function (subMesh) {
  66487. var _this = this;
  66488. var mesh = subMesh.getRenderingMesh();
  66489. var scene = this._scene;
  66490. var engine = scene.getEngine();
  66491. var material = subMesh.getMaterial();
  66492. if (!material) {
  66493. return;
  66494. }
  66495. // Culling
  66496. engine.setState(material.backFaceCulling);
  66497. // Managing instances
  66498. var batch = mesh._getInstancesRenderList(subMesh._id);
  66499. if (batch.mustReturn) {
  66500. return;
  66501. }
  66502. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  66503. if (this.isReady(subMesh, hardwareInstancedRendering)) {
  66504. engine.enableEffect(this._effect);
  66505. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  66506. this._effect.setFloat3("biasAndScale", this.bias, this.normalBias, this.depthScale);
  66507. this._effect.setMatrix("viewProjection", this.getTransformMatrix());
  66508. if (this.getLight().getTypeID() === BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  66509. this._effect.setVector3("lightData", this._cachedDirection);
  66510. }
  66511. else {
  66512. this._effect.setVector3("lightData", this._cachedPosition);
  66513. }
  66514. if (scene.activeCamera) {
  66515. this._effect.setFloat2("depthValues", this.getLight().getDepthMinZ(scene.activeCamera), this.getLight().getDepthMinZ(scene.activeCamera) + this.getLight().getDepthMaxZ(scene.activeCamera));
  66516. }
  66517. // Alpha test
  66518. if (material && material.needAlphaTesting()) {
  66519. var alphaTexture = material.getAlphaTestTexture();
  66520. if (alphaTexture) {
  66521. this._effect.setTexture("diffuseSampler", alphaTexture);
  66522. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix() || this._defaultTextureMatrix);
  66523. }
  66524. }
  66525. // Bones
  66526. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  66527. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices((mesh)));
  66528. }
  66529. // Morph targets
  66530. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._effect);
  66531. if (this.forceBackFacesOnly) {
  66532. engine.setState(true, 0, false, true);
  66533. }
  66534. // Draw
  66535. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  66536. if (this.forceBackFacesOnly) {
  66537. engine.setState(true, 0, false, false);
  66538. }
  66539. }
  66540. else {
  66541. // Need to reset refresh rate of the shadowMap
  66542. if (this._shadowMap) {
  66543. this._shadowMap.resetRefreshCounter();
  66544. }
  66545. }
  66546. };
  66547. ShadowGenerator.prototype._applyFilterValues = function () {
  66548. if (!this._shadowMap) {
  66549. return;
  66550. }
  66551. if (this.filter === ShadowGenerator.FILTER_NONE || this.filter === ShadowGenerator.FILTER_PCSS) {
  66552. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  66553. }
  66554. else {
  66555. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  66556. }
  66557. };
  66558. /**
  66559. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  66560. * @param onCompiled Callback triggered at the and of the effects compilation
  66561. * @param options Sets of optional options forcing the compilation with different modes
  66562. */
  66563. ShadowGenerator.prototype.forceCompilation = function (onCompiled, options) {
  66564. var _this = this;
  66565. var localOptions = __assign({ useInstances: false }, options);
  66566. var shadowMap = this.getShadowMap();
  66567. if (!shadowMap) {
  66568. if (onCompiled) {
  66569. onCompiled(this);
  66570. }
  66571. return;
  66572. }
  66573. var renderList = shadowMap.renderList;
  66574. if (!renderList) {
  66575. if (onCompiled) {
  66576. onCompiled(this);
  66577. }
  66578. return;
  66579. }
  66580. var subMeshes = new Array();
  66581. for (var _i = 0, renderList_1 = renderList; _i < renderList_1.length; _i++) {
  66582. var mesh = renderList_1[_i];
  66583. subMeshes.push.apply(subMeshes, mesh.subMeshes);
  66584. }
  66585. if (subMeshes.length === 0) {
  66586. if (onCompiled) {
  66587. onCompiled(this);
  66588. }
  66589. return;
  66590. }
  66591. var currentIndex = 0;
  66592. var checkReady = function () {
  66593. if (!_this._scene || !_this._scene.getEngine()) {
  66594. return;
  66595. }
  66596. while (_this.isReady(subMeshes[currentIndex], localOptions.useInstances)) {
  66597. currentIndex++;
  66598. if (currentIndex >= subMeshes.length) {
  66599. if (onCompiled) {
  66600. onCompiled(_this);
  66601. }
  66602. return;
  66603. }
  66604. }
  66605. setTimeout(checkReady, 16);
  66606. };
  66607. checkReady();
  66608. };
  66609. /**
  66610. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  66611. * @param options Sets of optional options forcing the compilation with different modes
  66612. * @returns A promise that resolves when the compilation completes
  66613. */
  66614. ShadowGenerator.prototype.forceCompilationAsync = function (options) {
  66615. var _this = this;
  66616. return new Promise(function (resolve) {
  66617. _this.forceCompilation(function () {
  66618. resolve();
  66619. }, options);
  66620. });
  66621. };
  66622. /**
  66623. * Determine wheter the shadow generator is ready or not (mainly all effects and related post processes needs to be ready).
  66624. * @param subMesh The submesh we want to render in the shadow map
  66625. * @param useInstances Defines wether will draw in the map using instances
  66626. * @returns true if ready otherwise, false
  66627. */
  66628. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  66629. var defines = [];
  66630. if (this._textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  66631. defines.push("#define FLOAT");
  66632. }
  66633. if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  66634. defines.push("#define ESM");
  66635. }
  66636. else if (this.usePercentageCloserFiltering || this.useContactHardeningShadow) {
  66637. defines.push("#define DEPTHTEXTURE");
  66638. }
  66639. var attribs = [BABYLON.VertexBuffer.PositionKind];
  66640. var mesh = subMesh.getMesh();
  66641. var material = subMesh.getMaterial();
  66642. // Normal bias.
  66643. if (this.normalBias && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  66644. attribs.push(BABYLON.VertexBuffer.NormalKind);
  66645. defines.push("#define NORMAL");
  66646. if (mesh.nonUniformScaling) {
  66647. defines.push("#define NONUNIFORMSCALING");
  66648. }
  66649. if (this.getLight().getTypeID() === BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  66650. defines.push("#define DIRECTIONINLIGHTDATA");
  66651. }
  66652. }
  66653. // Alpha test
  66654. if (material && material.needAlphaTesting()) {
  66655. var alphaTexture = material.getAlphaTestTexture();
  66656. if (alphaTexture) {
  66657. defines.push("#define ALPHATEST");
  66658. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  66659. attribs.push(BABYLON.VertexBuffer.UVKind);
  66660. defines.push("#define UV1");
  66661. }
  66662. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  66663. if (alphaTexture.coordinatesIndex === 1) {
  66664. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  66665. defines.push("#define UV2");
  66666. }
  66667. }
  66668. }
  66669. }
  66670. // Bones
  66671. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  66672. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  66673. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  66674. if (mesh.numBoneInfluencers > 4) {
  66675. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  66676. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  66677. }
  66678. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  66679. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  66680. }
  66681. else {
  66682. defines.push("#define NUM_BONE_INFLUENCERS 0");
  66683. }
  66684. // Morph targets
  66685. var manager = mesh.morphTargetManager;
  66686. var morphInfluencers = 0;
  66687. if (manager) {
  66688. if (manager.numInfluencers > 0) {
  66689. defines.push("#define MORPHTARGETS");
  66690. morphInfluencers = manager.numInfluencers;
  66691. defines.push("#define NUM_MORPH_INFLUENCERS " + morphInfluencers);
  66692. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, { "NUM_MORPH_INFLUENCERS": morphInfluencers });
  66693. }
  66694. }
  66695. // Instances
  66696. if (useInstances) {
  66697. defines.push("#define INSTANCES");
  66698. attribs.push("world0");
  66699. attribs.push("world1");
  66700. attribs.push("world2");
  66701. attribs.push("world3");
  66702. }
  66703. // Get correct effect
  66704. var join = defines.join("\n");
  66705. if (this._cachedDefines !== join) {
  66706. this._cachedDefines = join;
  66707. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "lightData", "depthValues", "biasAndScale", "morphTargetInfluences"], ["diffuseSampler"], join, undefined, undefined, undefined, { maxSimultaneousMorphTargets: morphInfluencers });
  66708. }
  66709. if (!this._effect.isReady()) {
  66710. return false;
  66711. }
  66712. if (this.useBlurExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  66713. if (!this._blurPostProcesses || !this._blurPostProcesses.length) {
  66714. this._initializeBlurRTTAndPostProcesses();
  66715. }
  66716. }
  66717. if (this._kernelBlurXPostprocess && !this._kernelBlurXPostprocess.isReady()) {
  66718. return false;
  66719. }
  66720. if (this._kernelBlurYPostprocess && !this._kernelBlurYPostprocess.isReady()) {
  66721. return false;
  66722. }
  66723. if (this._boxBlurPostprocess && !this._boxBlurPostprocess.isReady()) {
  66724. return false;
  66725. }
  66726. return true;
  66727. };
  66728. /**
  66729. * Prepare all the defines in a material relying on a shadow map at the specified light index.
  66730. * @param defines Defines of the material we want to update
  66731. * @param lightIndex Index of the light in the enabled light list of the material
  66732. */
  66733. ShadowGenerator.prototype.prepareDefines = function (defines, lightIndex) {
  66734. var scene = this._scene;
  66735. var light = this._light;
  66736. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  66737. return;
  66738. }
  66739. defines["SHADOW" + lightIndex] = true;
  66740. if (this.useContactHardeningShadow) {
  66741. defines["SHADOWPCSS" + lightIndex] = true;
  66742. if (this._filteringQuality === ShadowGenerator.QUALITY_LOW) {
  66743. defines["SHADOWLOWQUALITY" + lightIndex] = true;
  66744. }
  66745. else if (this._filteringQuality === ShadowGenerator.QUALITY_MEDIUM) {
  66746. defines["SHADOWMEDIUMQUALITY" + lightIndex] = true;
  66747. }
  66748. // else default to high.
  66749. }
  66750. if (this.usePercentageCloserFiltering) {
  66751. defines["SHADOWPCF" + lightIndex] = true;
  66752. if (this._filteringQuality === ShadowGenerator.QUALITY_LOW) {
  66753. defines["SHADOWLOWQUALITY" + lightIndex] = true;
  66754. }
  66755. else if (this._filteringQuality === ShadowGenerator.QUALITY_MEDIUM) {
  66756. defines["SHADOWMEDIUMQUALITY" + lightIndex] = true;
  66757. }
  66758. // else default to high.
  66759. }
  66760. else if (this.usePoissonSampling) {
  66761. defines["SHADOWPOISSON" + lightIndex] = true;
  66762. }
  66763. else if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  66764. defines["SHADOWESM" + lightIndex] = true;
  66765. }
  66766. else if (this.useCloseExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  66767. defines["SHADOWCLOSEESM" + lightIndex] = true;
  66768. }
  66769. if (light.needCube()) {
  66770. defines["SHADOWCUBE" + lightIndex] = true;
  66771. }
  66772. };
  66773. /**
  66774. * Binds the shadow related information inside of an effect (information like near, far, darkness...
  66775. * defined in the generator but impacting the effect).
  66776. * @param lightIndex Index of the light in the enabled light list of the material owning the effect
  66777. * @param effect The effect we are binfing the information for
  66778. */
  66779. ShadowGenerator.prototype.bindShadowLight = function (lightIndex, effect) {
  66780. var light = this._light;
  66781. var scene = this._scene;
  66782. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  66783. return;
  66784. }
  66785. var camera = scene.activeCamera;
  66786. if (!camera) {
  66787. return;
  66788. }
  66789. var shadowMap = this.getShadowMap();
  66790. if (!shadowMap) {
  66791. return;
  66792. }
  66793. if (!light.needCube()) {
  66794. effect.setMatrix("lightMatrix" + lightIndex, this.getTransformMatrix());
  66795. }
  66796. // Only PCF uses depth stencil texture.
  66797. if (this._filter === ShadowGenerator.FILTER_PCF) {
  66798. effect.setDepthStencilTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  66799. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), shadowMap.getSize().width, 1 / shadowMap.getSize().width, this.frustumEdgeFalloff, lightIndex);
  66800. }
  66801. else if (this._filter === ShadowGenerator.FILTER_PCSS) {
  66802. effect.setDepthStencilTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  66803. effect.setTexture("depthSampler" + lightIndex, this.getShadowMapForRendering());
  66804. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), 1 / shadowMap.getSize().width, this._contactHardeningLightSizeUVRatio * shadowMap.getSize().width, this.frustumEdgeFalloff, lightIndex);
  66805. }
  66806. else {
  66807. effect.setTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  66808. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), this.blurScale / shadowMap.getSize().width, this.depthScale, this.frustumEdgeFalloff, lightIndex);
  66809. }
  66810. light._uniformBuffer.updateFloat2("depthValues", this.getLight().getDepthMinZ(camera), this.getLight().getDepthMinZ(camera) + this.getLight().getDepthMaxZ(camera), lightIndex);
  66811. };
  66812. /**
  66813. * Gets the transformation matrix used to project the meshes into the map from the light point of view.
  66814. * (eq to shadow prjection matrix * light transform matrix)
  66815. * @returns The transform matrix used to create the shadow map
  66816. */
  66817. ShadowGenerator.prototype.getTransformMatrix = function () {
  66818. var scene = this._scene;
  66819. if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
  66820. return this._transformMatrix;
  66821. }
  66822. this._currentRenderID = scene.getRenderId();
  66823. this._currentFaceIndexCache = this._currentFaceIndex;
  66824. var lightPosition = this._light.position;
  66825. if (this._light.computeTransformedInformation()) {
  66826. lightPosition = this._light.transformedPosition;
  66827. }
  66828. BABYLON.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
  66829. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) === 1.0) {
  66830. this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light
  66831. }
  66832. if (this._light.needProjectionMatrixCompute() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  66833. this._cachedPosition.copyFrom(lightPosition);
  66834. this._cachedDirection.copyFrom(this._lightDirection);
  66835. BABYLON.Matrix.LookAtLHToRef(lightPosition, lightPosition.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  66836. var shadowMap = this.getShadowMap();
  66837. if (shadowMap) {
  66838. var renderList = shadowMap.renderList;
  66839. if (renderList) {
  66840. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, renderList);
  66841. }
  66842. }
  66843. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  66844. }
  66845. return this._transformMatrix;
  66846. };
  66847. /**
  66848. * Recreates the shadow map dependencies like RTT and post processes. This can be used during the switch between
  66849. * Cube and 2D textures for instance.
  66850. */
  66851. ShadowGenerator.prototype.recreateShadowMap = function () {
  66852. var shadowMap = this._shadowMap;
  66853. if (!shadowMap) {
  66854. return;
  66855. }
  66856. // Track render list.
  66857. var renderList = shadowMap.renderList;
  66858. // Clean up existing data.
  66859. this._disposeRTTandPostProcesses();
  66860. // Reinitializes.
  66861. this._initializeGenerator();
  66862. // Reaffect the filter to ensure a correct fallback if necessary.
  66863. this.filter = this.filter;
  66864. // Reaffect the filter.
  66865. this._applyFilterValues();
  66866. // Reaffect Render List.
  66867. this._shadowMap.renderList = renderList;
  66868. };
  66869. ShadowGenerator.prototype._disposeBlurPostProcesses = function () {
  66870. if (this._shadowMap2) {
  66871. this._shadowMap2.dispose();
  66872. this._shadowMap2 = null;
  66873. }
  66874. if (this._boxBlurPostprocess) {
  66875. this._boxBlurPostprocess.dispose();
  66876. this._boxBlurPostprocess = null;
  66877. }
  66878. if (this._kernelBlurXPostprocess) {
  66879. this._kernelBlurXPostprocess.dispose();
  66880. this._kernelBlurXPostprocess = null;
  66881. }
  66882. if (this._kernelBlurYPostprocess) {
  66883. this._kernelBlurYPostprocess.dispose();
  66884. this._kernelBlurYPostprocess = null;
  66885. }
  66886. this._blurPostProcesses = [];
  66887. };
  66888. ShadowGenerator.prototype._disposeRTTandPostProcesses = function () {
  66889. if (this._shadowMap) {
  66890. this._shadowMap.dispose();
  66891. this._shadowMap = null;
  66892. }
  66893. this._disposeBlurPostProcesses();
  66894. };
  66895. /**
  66896. * Disposes the ShadowGenerator.
  66897. * Returns nothing.
  66898. */
  66899. ShadowGenerator.prototype.dispose = function () {
  66900. this._disposeRTTandPostProcesses();
  66901. if (this._light) {
  66902. this._light._shadowGenerator = null;
  66903. this._light._markMeshesAsLightDirty();
  66904. }
  66905. };
  66906. /**
  66907. * Serializes the shadow generator setup to a json object.
  66908. * @returns The serialized JSON object
  66909. */
  66910. ShadowGenerator.prototype.serialize = function () {
  66911. var serializationObject = {};
  66912. var shadowMap = this.getShadowMap();
  66913. if (!shadowMap) {
  66914. return serializationObject;
  66915. }
  66916. serializationObject.lightId = this._light.id;
  66917. serializationObject.mapSize = shadowMap.getRenderSize();
  66918. serializationObject.useExponentialShadowMap = this.useExponentialShadowMap;
  66919. serializationObject.useBlurExponentialShadowMap = this.useBlurExponentialShadowMap;
  66920. serializationObject.useCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  66921. serializationObject.useBlurCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  66922. serializationObject.usePoissonSampling = this.usePoissonSampling;
  66923. serializationObject.forceBackFacesOnly = this.forceBackFacesOnly;
  66924. serializationObject.depthScale = this.depthScale;
  66925. serializationObject.darkness = this.getDarkness();
  66926. serializationObject.blurBoxOffset = this.blurBoxOffset;
  66927. serializationObject.blurKernel = this.blurKernel;
  66928. serializationObject.blurScale = this.blurScale;
  66929. serializationObject.useKernelBlur = this.useKernelBlur;
  66930. serializationObject.transparencyShadow = this._transparencyShadow;
  66931. serializationObject.bias = this.bias;
  66932. serializationObject.normalBias = this.normalBias;
  66933. serializationObject.usePercentageCloserFiltering = this.usePercentageCloserFiltering;
  66934. serializationObject.useContactHardeningShadow = this.useContactHardeningShadow;
  66935. serializationObject.filteringQuality = this.filteringQuality;
  66936. serializationObject.contactHardeningLightSizeUVRatio = this.contactHardeningLightSizeUVRatio;
  66937. serializationObject.renderList = [];
  66938. if (shadowMap.renderList) {
  66939. for (var meshIndex = 0; meshIndex < shadowMap.renderList.length; meshIndex++) {
  66940. var mesh = shadowMap.renderList[meshIndex];
  66941. serializationObject.renderList.push(mesh.id);
  66942. }
  66943. }
  66944. return serializationObject;
  66945. };
  66946. /**
  66947. * Parses a serialized ShadowGenerator and returns a new ShadowGenerator.
  66948. * @param parsedShadowGenerator The JSON object to parse
  66949. * @param scene The scene to create the shadow map for
  66950. * @returns The parsed shadow generator
  66951. */
  66952. ShadowGenerator.Parse = function (parsedShadowGenerator, scene) {
  66953. //casting to point light, as light is missing the position attr and typescript complains.
  66954. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  66955. var shadowGenerator = new ShadowGenerator(parsedShadowGenerator.mapSize, light);
  66956. var shadowMap = shadowGenerator.getShadowMap();
  66957. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  66958. var meshes = scene.getMeshesByID(parsedShadowGenerator.renderList[meshIndex]);
  66959. meshes.forEach(function (mesh) {
  66960. if (!shadowMap) {
  66961. return;
  66962. }
  66963. if (!shadowMap.renderList) {
  66964. shadowMap.renderList = [];
  66965. }
  66966. shadowMap.renderList.push(mesh);
  66967. });
  66968. }
  66969. if (parsedShadowGenerator.usePoissonSampling) {
  66970. shadowGenerator.usePoissonSampling = true;
  66971. }
  66972. else if (parsedShadowGenerator.useExponentialShadowMap) {
  66973. shadowGenerator.useExponentialShadowMap = true;
  66974. }
  66975. else if (parsedShadowGenerator.useBlurExponentialShadowMap) {
  66976. shadowGenerator.useBlurExponentialShadowMap = true;
  66977. }
  66978. else if (parsedShadowGenerator.useCloseExponentialShadowMap) {
  66979. shadowGenerator.useCloseExponentialShadowMap = true;
  66980. }
  66981. else if (parsedShadowGenerator.useBlurCloseExponentialShadowMap) {
  66982. shadowGenerator.useBlurCloseExponentialShadowMap = true;
  66983. }
  66984. else if (parsedShadowGenerator.usePercentageCloserFiltering) {
  66985. shadowGenerator.usePercentageCloserFiltering = true;
  66986. }
  66987. else if (parsedShadowGenerator.useContactHardeningShadow) {
  66988. shadowGenerator.useContactHardeningShadow = true;
  66989. }
  66990. if (parsedShadowGenerator.filteringQuality) {
  66991. shadowGenerator.filteringQuality = parsedShadowGenerator.filteringQuality;
  66992. }
  66993. if (parsedShadowGenerator.contactHardeningLightSizeUVRatio) {
  66994. shadowGenerator.contactHardeningLightSizeUVRatio = parsedShadowGenerator.contactHardeningLightSizeUVRatio;
  66995. }
  66996. // Backward compat
  66997. else if (parsedShadowGenerator.useVarianceShadowMap) {
  66998. shadowGenerator.useExponentialShadowMap = true;
  66999. }
  67000. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  67001. shadowGenerator.useBlurExponentialShadowMap = true;
  67002. }
  67003. if (parsedShadowGenerator.depthScale) {
  67004. shadowGenerator.depthScale = parsedShadowGenerator.depthScale;
  67005. }
  67006. if (parsedShadowGenerator.blurScale) {
  67007. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  67008. }
  67009. if (parsedShadowGenerator.blurBoxOffset) {
  67010. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  67011. }
  67012. if (parsedShadowGenerator.useKernelBlur) {
  67013. shadowGenerator.useKernelBlur = parsedShadowGenerator.useKernelBlur;
  67014. }
  67015. if (parsedShadowGenerator.blurKernel) {
  67016. shadowGenerator.blurKernel = parsedShadowGenerator.blurKernel;
  67017. }
  67018. if (parsedShadowGenerator.bias !== undefined) {
  67019. shadowGenerator.bias = parsedShadowGenerator.bias;
  67020. }
  67021. if (parsedShadowGenerator.normalBias !== undefined) {
  67022. shadowGenerator.normalBias = parsedShadowGenerator.normalBias;
  67023. }
  67024. if (parsedShadowGenerator.darkness) {
  67025. shadowGenerator.setDarkness(parsedShadowGenerator.darkness);
  67026. }
  67027. if (parsedShadowGenerator.transparencyShadow) {
  67028. shadowGenerator.setTransparencyShadow(true);
  67029. }
  67030. shadowGenerator.forceBackFacesOnly = parsedShadowGenerator.forceBackFacesOnly;
  67031. return shadowGenerator;
  67032. };
  67033. /**
  67034. * Shadow generator mode None: no filtering applied.
  67035. */
  67036. ShadowGenerator.FILTER_NONE = 0;
  67037. /**
  67038. * Shadow generator mode ESM: Exponential Shadow Mapping.
  67039. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  67040. */
  67041. ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP = 1;
  67042. /**
  67043. * Shadow generator mode Poisson Sampling: Percentage Closer Filtering.
  67044. * (Multiple Tap around evenly distributed around the pixel are used to evaluate the shadow strength)
  67045. */
  67046. ShadowGenerator.FILTER_POISSONSAMPLING = 2;
  67047. /**
  67048. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping.
  67049. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  67050. */
  67051. ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP = 3;
  67052. /**
  67053. * Shadow generator mode ESM: Exponential Shadow Mapping using the inverse of the exponential preventing
  67054. * edge artifacts on steep falloff.
  67055. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  67056. */
  67057. ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP = 4;
  67058. /**
  67059. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping using the inverse of the exponential preventing
  67060. * edge artifacts on steep falloff.
  67061. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  67062. */
  67063. ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP = 5;
  67064. /**
  67065. * Shadow generator mode PCF: Percentage Closer Filtering
  67066. * benefits from Webgl 2 shadow samplers. Fallback to Poisson Sampling in Webgl 1
  67067. * (https://developer.nvidia.com/gpugems/GPUGems/gpugems_ch11.html)
  67068. */
  67069. ShadowGenerator.FILTER_PCF = 6;
  67070. /**
  67071. * Shadow generator mode PCSS: Percentage Closering Soft Shadow.
  67072. * benefits from Webgl 2 shadow samplers. Fallback to Poisson Sampling in Webgl 1
  67073. * Contact Hardening
  67074. */
  67075. ShadowGenerator.FILTER_PCSS = 7;
  67076. /**
  67077. * Reserved for PCF and PCSS
  67078. * Highest Quality.
  67079. *
  67080. * Execute PCF on a 5*5 kernel improving a lot the shadow aliasing artifacts.
  67081. *
  67082. * Execute PCSS with 32 taps blocker search and 64 taps PCF.
  67083. */
  67084. ShadowGenerator.QUALITY_HIGH = 0;
  67085. /**
  67086. * Reserved for PCF and PCSS
  67087. * Good tradeoff for quality/perf cross devices
  67088. *
  67089. * Execute PCF on a 3*3 kernel.
  67090. *
  67091. * Execute PCSS with 16 taps blocker search and 32 taps PCF.
  67092. */
  67093. ShadowGenerator.QUALITY_MEDIUM = 1;
  67094. /**
  67095. * Reserved for PCF and PCSS
  67096. * The lowest quality but the fastest.
  67097. *
  67098. * Execute PCF on a 1*1 kernel.
  67099. *
  67100. * Execute PCSS with 16 taps blocker search and 16 taps PCF.
  67101. */
  67102. ShadowGenerator.QUALITY_LOW = 2;
  67103. return ShadowGenerator;
  67104. }());
  67105. BABYLON.ShadowGenerator = ShadowGenerator;
  67106. })(BABYLON || (BABYLON = {}));
  67107. //# sourceMappingURL=babylon.shadowGenerator.js.map
  67108. var BABYLON;
  67109. (function (BABYLON) {
  67110. var DefaultLoadingScreen = /** @class */ (function () {
  67111. function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
  67112. if (_loadingText === void 0) { _loadingText = ""; }
  67113. if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; }
  67114. var _this = this;
  67115. this._renderingCanvas = _renderingCanvas;
  67116. this._loadingText = _loadingText;
  67117. this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
  67118. // Resize
  67119. this._resizeLoadingUI = function () {
  67120. var canvasRect = _this._renderingCanvas.getBoundingClientRect();
  67121. var canvasPositioning = window.getComputedStyle(_this._renderingCanvas).position;
  67122. if (!_this._loadingDiv) {
  67123. return;
  67124. }
  67125. _this._loadingDiv.style.position = (canvasPositioning === "fixed") ? "fixed" : "absolute";
  67126. _this._loadingDiv.style.left = canvasRect.left + "px";
  67127. _this._loadingDiv.style.top = canvasRect.top + "px";
  67128. _this._loadingDiv.style.width = canvasRect.width + "px";
  67129. _this._loadingDiv.style.height = canvasRect.height + "px";
  67130. };
  67131. }
  67132. DefaultLoadingScreen.prototype.displayLoadingUI = function () {
  67133. if (this._loadingDiv) {
  67134. // Do not add a loading screen if there is already one
  67135. return;
  67136. }
  67137. this._loadingDiv = document.createElement("div");
  67138. this._loadingDiv.id = "babylonjsLoadingDiv";
  67139. this._loadingDiv.style.opacity = "0";
  67140. this._loadingDiv.style.transition = "opacity 1.5s ease";
  67141. this._loadingDiv.style.pointerEvents = "none";
  67142. // Loading text
  67143. this._loadingTextDiv = document.createElement("div");
  67144. this._loadingTextDiv.style.position = "absolute";
  67145. this._loadingTextDiv.style.left = "0";
  67146. this._loadingTextDiv.style.top = "50%";
  67147. this._loadingTextDiv.style.marginTop = "80px";
  67148. this._loadingTextDiv.style.width = "100%";
  67149. this._loadingTextDiv.style.height = "20px";
  67150. this._loadingTextDiv.style.fontFamily = "Arial";
  67151. this._loadingTextDiv.style.fontSize = "14px";
  67152. this._loadingTextDiv.style.color = "white";
  67153. this._loadingTextDiv.style.textAlign = "center";
  67154. this._loadingTextDiv.innerHTML = "Loading";
  67155. this._loadingDiv.appendChild(this._loadingTextDiv);
  67156. //set the predefined text
  67157. this._loadingTextDiv.innerHTML = this._loadingText;
  67158. // Generating keyframes
  67159. var style = document.createElement('style');
  67160. style.type = 'text/css';
  67161. 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 }";
  67162. style.innerHTML = keyFrames;
  67163. document.getElementsByTagName('head')[0].appendChild(style);
  67164. // Loading img
  67165. var imgBack = new Image();
  67166. 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";
  67167. imgBack.style.position = "absolute";
  67168. imgBack.style.left = "50%";
  67169. imgBack.style.top = "50%";
  67170. imgBack.style.marginLeft = "-60px";
  67171. imgBack.style.marginTop = "-60px";
  67172. imgBack.style.animation = "spin1 2s infinite ease-in-out";
  67173. imgBack.style.webkitAnimation = "spin1 2s infinite ease-in-out";
  67174. imgBack.style.transformOrigin = "50% 50%";
  67175. imgBack.style.webkitTransformOrigin = "50% 50%";
  67176. this._loadingDiv.appendChild(imgBack);
  67177. this._resizeLoadingUI();
  67178. window.addEventListener("resize", this._resizeLoadingUI);
  67179. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  67180. document.body.appendChild(this._loadingDiv);
  67181. this._loadingDiv.style.opacity = "1";
  67182. };
  67183. DefaultLoadingScreen.prototype.hideLoadingUI = function () {
  67184. var _this = this;
  67185. if (!this._loadingDiv) {
  67186. return;
  67187. }
  67188. var onTransitionEnd = function () {
  67189. if (!_this._loadingDiv) {
  67190. return;
  67191. }
  67192. document.body.removeChild(_this._loadingDiv);
  67193. window.removeEventListener("resize", _this._resizeLoadingUI);
  67194. _this._loadingDiv = null;
  67195. };
  67196. this._loadingDiv.style.opacity = "0";
  67197. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  67198. };
  67199. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", {
  67200. set: function (text) {
  67201. this._loadingText = text;
  67202. if (this._loadingTextDiv) {
  67203. this._loadingTextDiv.innerHTML = this._loadingText;
  67204. }
  67205. },
  67206. enumerable: true,
  67207. configurable: true
  67208. });
  67209. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", {
  67210. get: function () {
  67211. return this._loadingDivBackgroundColor;
  67212. },
  67213. set: function (color) {
  67214. this._loadingDivBackgroundColor = color;
  67215. if (!this._loadingDiv) {
  67216. return;
  67217. }
  67218. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  67219. },
  67220. enumerable: true,
  67221. configurable: true
  67222. });
  67223. return DefaultLoadingScreen;
  67224. }());
  67225. BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;
  67226. })(BABYLON || (BABYLON = {}));
  67227. //# sourceMappingURL=babylon.loadingScreen.js.map
  67228. var BABYLON;
  67229. (function (BABYLON) {
  67230. var SceneLoaderProgressEvent = /** @class */ (function () {
  67231. function SceneLoaderProgressEvent(lengthComputable, loaded, total) {
  67232. this.lengthComputable = lengthComputable;
  67233. this.loaded = loaded;
  67234. this.total = total;
  67235. }
  67236. SceneLoaderProgressEvent.FromProgressEvent = function (event) {
  67237. return new SceneLoaderProgressEvent(event.lengthComputable, event.loaded, event.total);
  67238. };
  67239. return SceneLoaderProgressEvent;
  67240. }());
  67241. BABYLON.SceneLoaderProgressEvent = SceneLoaderProgressEvent;
  67242. var SceneLoader = /** @class */ (function () {
  67243. function SceneLoader() {
  67244. }
  67245. Object.defineProperty(SceneLoader, "NO_LOGGING", {
  67246. get: function () {
  67247. return 0;
  67248. },
  67249. enumerable: true,
  67250. configurable: true
  67251. });
  67252. Object.defineProperty(SceneLoader, "MINIMAL_LOGGING", {
  67253. get: function () {
  67254. return 1;
  67255. },
  67256. enumerable: true,
  67257. configurable: true
  67258. });
  67259. Object.defineProperty(SceneLoader, "SUMMARY_LOGGING", {
  67260. get: function () {
  67261. return 2;
  67262. },
  67263. enumerable: true,
  67264. configurable: true
  67265. });
  67266. Object.defineProperty(SceneLoader, "DETAILED_LOGGING", {
  67267. get: function () {
  67268. return 3;
  67269. },
  67270. enumerable: true,
  67271. configurable: true
  67272. });
  67273. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  67274. get: function () {
  67275. return SceneLoader._ForceFullSceneLoadingForIncremental;
  67276. },
  67277. set: function (value) {
  67278. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  67279. },
  67280. enumerable: true,
  67281. configurable: true
  67282. });
  67283. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  67284. get: function () {
  67285. return SceneLoader._ShowLoadingScreen;
  67286. },
  67287. set: function (value) {
  67288. SceneLoader._ShowLoadingScreen = value;
  67289. },
  67290. enumerable: true,
  67291. configurable: true
  67292. });
  67293. Object.defineProperty(SceneLoader, "loggingLevel", {
  67294. get: function () {
  67295. return SceneLoader._loggingLevel;
  67296. },
  67297. set: function (value) {
  67298. SceneLoader._loggingLevel = value;
  67299. },
  67300. enumerable: true,
  67301. configurable: true
  67302. });
  67303. Object.defineProperty(SceneLoader, "CleanBoneMatrixWeights", {
  67304. get: function () {
  67305. return SceneLoader._CleanBoneMatrixWeights;
  67306. },
  67307. set: function (value) {
  67308. SceneLoader._CleanBoneMatrixWeights = value;
  67309. },
  67310. enumerable: true,
  67311. configurable: true
  67312. });
  67313. SceneLoader._getDefaultPlugin = function () {
  67314. return SceneLoader._registeredPlugins[".babylon"];
  67315. };
  67316. SceneLoader._getPluginForExtension = function (extension) {
  67317. var registeredPlugin = SceneLoader._registeredPlugins[extension];
  67318. if (registeredPlugin) {
  67319. return registeredPlugin;
  67320. }
  67321. 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");
  67322. return SceneLoader._getDefaultPlugin();
  67323. };
  67324. SceneLoader._getPluginForDirectLoad = function (data) {
  67325. for (var extension in SceneLoader._registeredPlugins) {
  67326. var plugin = SceneLoader._registeredPlugins[extension].plugin;
  67327. if (plugin.canDirectLoad && plugin.canDirectLoad(data)) {
  67328. return SceneLoader._registeredPlugins[extension];
  67329. }
  67330. }
  67331. return SceneLoader._getDefaultPlugin();
  67332. };
  67333. SceneLoader._getPluginForFilename = function (sceneFilename) {
  67334. if (sceneFilename.name) {
  67335. sceneFilename = sceneFilename.name;
  67336. }
  67337. var queryStringPosition = sceneFilename.indexOf("?");
  67338. if (queryStringPosition !== -1) {
  67339. sceneFilename = sceneFilename.substring(0, queryStringPosition);
  67340. }
  67341. var dotPosition = sceneFilename.lastIndexOf(".");
  67342. var extension = sceneFilename.substring(dotPosition, sceneFilename.length).toLowerCase();
  67343. return SceneLoader._getPluginForExtension(extension);
  67344. };
  67345. // use babylon file loader directly if sceneFilename is prefixed with "data:"
  67346. SceneLoader._getDirectLoad = function (sceneFilename) {
  67347. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  67348. return sceneFilename.substr(5);
  67349. }
  67350. return null;
  67351. };
  67352. SceneLoader._loadData = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, onDispose, pluginExtension) {
  67353. var directLoad = SceneLoader._getDirectLoad(sceneFilename);
  67354. var registeredPlugin = pluginExtension ? SceneLoader._getPluginForExtension(pluginExtension) : (directLoad ? SceneLoader._getPluginForDirectLoad(sceneFilename) : SceneLoader._getPluginForFilename(sceneFilename));
  67355. var plugin;
  67356. if (registeredPlugin.plugin.createPlugin) {
  67357. plugin = registeredPlugin.plugin.createPlugin();
  67358. }
  67359. else {
  67360. plugin = registeredPlugin.plugin;
  67361. }
  67362. var useArrayBuffer = registeredPlugin.isBinary;
  67363. var database;
  67364. SceneLoader.OnPluginActivatedObservable.notifyObservers(plugin);
  67365. var dataCallback = function (data, responseURL) {
  67366. if (scene.isDisposed) {
  67367. onError("Scene has been disposed");
  67368. return;
  67369. }
  67370. scene.database = database;
  67371. onSuccess(plugin, data, responseURL);
  67372. };
  67373. var request = null;
  67374. var pluginDisposed = false;
  67375. var onDisposeObservable = plugin.onDisposeObservable;
  67376. if (onDisposeObservable) {
  67377. onDisposeObservable.add(function () {
  67378. pluginDisposed = true;
  67379. if (request) {
  67380. request.abort();
  67381. request = null;
  67382. }
  67383. onDispose();
  67384. });
  67385. }
  67386. var manifestChecked = function () {
  67387. if (pluginDisposed) {
  67388. return;
  67389. }
  67390. var url = rootUrl + sceneFilename;
  67391. request = BABYLON.Tools.LoadFile(url, dataCallback, onProgress ? function (event) {
  67392. onProgress(SceneLoaderProgressEvent.FromProgressEvent(event));
  67393. } : undefined, database, useArrayBuffer, function (request, exception) {
  67394. onError("Failed to load scene." + (exception ? "" : " " + exception.message), exception);
  67395. });
  67396. };
  67397. if (directLoad) {
  67398. dataCallback(directLoad);
  67399. return plugin;
  67400. }
  67401. if (rootUrl.indexOf("file:") === -1) {
  67402. var engine = scene.getEngine();
  67403. var canUseOfflineSupport = engine.enableOfflineSupport;
  67404. if (canUseOfflineSupport) {
  67405. // Also check for exceptions
  67406. var exceptionFound = false;
  67407. for (var _i = 0, _a = scene.disableOfflineSupportExceptionRules; _i < _a.length; _i++) {
  67408. var regex = _a[_i];
  67409. if (regex.test(rootUrl + sceneFilename)) {
  67410. exceptionFound = true;
  67411. break;
  67412. }
  67413. }
  67414. canUseOfflineSupport = !exceptionFound;
  67415. }
  67416. if (canUseOfflineSupport) {
  67417. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  67418. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked, engine.disableManifestCheck);
  67419. }
  67420. else {
  67421. manifestChecked();
  67422. }
  67423. }
  67424. // Loading file from disk via input file or drag'n'drop
  67425. else {
  67426. var fileOrString = sceneFilename;
  67427. if (fileOrString.name) { // File
  67428. request = BABYLON.Tools.ReadFile(fileOrString, dataCallback, onProgress, useArrayBuffer);
  67429. }
  67430. else if (BABYLON.FilesInput.FilesToLoad[sceneFilename]) {
  67431. request = BABYLON.Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[sceneFilename], dataCallback, onProgress, useArrayBuffer);
  67432. }
  67433. else {
  67434. onError("Unable to find file named " + sceneFilename);
  67435. }
  67436. }
  67437. return plugin;
  67438. };
  67439. // Public functions
  67440. SceneLoader.GetPluginForExtension = function (extension) {
  67441. return SceneLoader._getPluginForExtension(extension).plugin;
  67442. };
  67443. SceneLoader.IsPluginForExtensionAvailable = function (extension) {
  67444. return !!SceneLoader._registeredPlugins[extension];
  67445. };
  67446. SceneLoader.RegisterPlugin = function (plugin) {
  67447. if (typeof plugin.extensions === "string") {
  67448. var extension = plugin.extensions;
  67449. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  67450. plugin: plugin,
  67451. isBinary: false
  67452. };
  67453. }
  67454. else {
  67455. var extensions = plugin.extensions;
  67456. Object.keys(extensions).forEach(function (extension) {
  67457. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  67458. plugin: plugin,
  67459. isBinary: extensions[extension].isBinary
  67460. };
  67461. });
  67462. }
  67463. };
  67464. /**
  67465. * Import meshes into a scene
  67466. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  67467. * @param rootUrl a string that defines the root url for scene and resources OR the concatenation of rootURL and filename (eg. http://example.com/test.glb)
  67468. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene (default: empty string)
  67469. * @param scene the instance of BABYLON.Scene to append to
  67470. * @param onSuccess a callback with a list of imported meshes, particleSystems, and skeletons when import succeeds
  67471. * @param onProgress a callback with a progress event for each file being loaded
  67472. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  67473. * @param pluginExtension the extension used to determine the plugin
  67474. * @returns The loaded plugin
  67475. */
  67476. SceneLoader.ImportMesh = function (meshNames, rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  67477. if (sceneFilename === void 0) { sceneFilename = ""; }
  67478. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  67479. if (onSuccess === void 0) { onSuccess = null; }
  67480. if (onProgress === void 0) { onProgress = null; }
  67481. if (onError === void 0) { onError = null; }
  67482. if (pluginExtension === void 0) { pluginExtension = null; }
  67483. if (!scene) {
  67484. BABYLON.Tools.Error("No scene available to import mesh to");
  67485. return null;
  67486. }
  67487. if (!sceneFilename) {
  67488. sceneFilename = BABYLON.Tools.GetFilename(rootUrl);
  67489. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl);
  67490. }
  67491. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  67492. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  67493. return null;
  67494. }
  67495. var loadingToken = {};
  67496. scene._addPendingData(loadingToken);
  67497. var disposeHandler = function () {
  67498. scene._removePendingData(loadingToken);
  67499. };
  67500. var errorHandler = function (message, exception) {
  67501. var errorMessage = "Unable to import meshes from " + rootUrl + sceneFilename + ": " + message;
  67502. if (onError) {
  67503. onError(scene, errorMessage, exception);
  67504. }
  67505. else {
  67506. BABYLON.Tools.Error(errorMessage);
  67507. // should the exception be thrown?
  67508. }
  67509. disposeHandler();
  67510. };
  67511. var progressHandler = onProgress ? function (event) {
  67512. try {
  67513. onProgress(event);
  67514. }
  67515. catch (e) {
  67516. errorHandler("Error in onProgress callback", e);
  67517. }
  67518. } : undefined;
  67519. var successHandler = function (meshes, particleSystems, skeletons, animationGroups) {
  67520. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  67521. if (onSuccess) {
  67522. try {
  67523. onSuccess(meshes, particleSystems, skeletons, animationGroups);
  67524. }
  67525. catch (e) {
  67526. errorHandler("Error in onSuccess callback", e);
  67527. }
  67528. }
  67529. scene._removePendingData(loadingToken);
  67530. };
  67531. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  67532. if (plugin.rewriteRootURL) {
  67533. rootUrl = plugin.rewriteRootURL(rootUrl, responseURL);
  67534. }
  67535. if (sceneFilename === "") {
  67536. if (sceneFilename === "") {
  67537. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl, true);
  67538. }
  67539. }
  67540. if (plugin.importMesh) {
  67541. var syncedPlugin = plugin;
  67542. var meshes = new Array();
  67543. var particleSystems = new Array();
  67544. var skeletons = new Array();
  67545. if (!syncedPlugin.importMesh(meshNames, scene, data, rootUrl, meshes, particleSystems, skeletons, errorHandler)) {
  67546. return;
  67547. }
  67548. scene.loadingPluginName = plugin.name;
  67549. successHandler(meshes, particleSystems, skeletons, []);
  67550. }
  67551. else {
  67552. var asyncedPlugin = plugin;
  67553. asyncedPlugin.importMeshAsync(meshNames, scene, data, rootUrl, progressHandler).then(function (result) {
  67554. scene.loadingPluginName = plugin.name;
  67555. successHandler(result.meshes, result.particleSystems, result.skeletons, result.animationGroups);
  67556. }).catch(function (error) {
  67557. errorHandler(error.message, error);
  67558. });
  67559. }
  67560. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  67561. };
  67562. /**
  67563. * Import meshes into a scene
  67564. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  67565. * @param rootUrl a string that defines the root url for scene and resources OR the concatenation of rootURL and filename (eg. http://example.com/test.glb)
  67566. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene (default: empty string)
  67567. * @param scene the instance of BABYLON.Scene to append to
  67568. * @param onProgress a callback with a progress event for each file being loaded
  67569. * @param pluginExtension the extension used to determine the plugin
  67570. * @returns The loaded list of imported meshes, particle systems, skeletons, and animation groups
  67571. */
  67572. SceneLoader.ImportMeshAsync = function (meshNames, rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  67573. if (sceneFilename === void 0) { sceneFilename = ""; }
  67574. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  67575. if (onProgress === void 0) { onProgress = null; }
  67576. if (pluginExtension === void 0) { pluginExtension = null; }
  67577. return new Promise(function (resolve, reject) {
  67578. SceneLoader.ImportMesh(meshNames, rootUrl, sceneFilename, scene, function (meshes, particleSystems, skeletons, animationGroups) {
  67579. resolve({
  67580. meshes: meshes,
  67581. particleSystems: particleSystems,
  67582. skeletons: skeletons,
  67583. animationGroups: animationGroups
  67584. });
  67585. }, onProgress, function (scene, message, exception) {
  67586. reject(exception || new Error(message));
  67587. }, pluginExtension);
  67588. });
  67589. };
  67590. /**
  67591. * Load a scene
  67592. * @param rootUrl a string that defines the root url for scene and resources OR the concatenation of rootURL and filename (eg. http://example.com/test.glb)
  67593. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene (default: empty string)
  67594. * @param engine is the instance of BABYLON.Engine to use to create the scene
  67595. * @param onSuccess a callback with the scene when import succeeds
  67596. * @param onProgress a callback with a progress event for each file being loaded
  67597. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  67598. * @param pluginExtension the extension used to determine the plugin
  67599. * @returns The loaded plugin
  67600. */
  67601. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onSuccess, onProgress, onError, pluginExtension) {
  67602. if (onSuccess === void 0) { onSuccess = null; }
  67603. if (onProgress === void 0) { onProgress = null; }
  67604. if (onError === void 0) { onError = null; }
  67605. if (pluginExtension === void 0) { pluginExtension = null; }
  67606. return SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onSuccess, onProgress, onError, pluginExtension);
  67607. };
  67608. /**
  67609. * Load a scene
  67610. * @param rootUrl a string that defines the root url for scene and resources OR the concatenation of rootURL and filename (eg. http://example.com/test.glb)
  67611. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene (default: empty string)
  67612. * @param engine is the instance of BABYLON.Engine to use to create the scene
  67613. * @param onProgress a callback with a progress event for each file being loaded
  67614. * @param pluginExtension the extension used to determine the plugin
  67615. * @returns The loaded scene
  67616. */
  67617. SceneLoader.LoadAsync = function (rootUrl, sceneFilename, engine, onProgress, pluginExtension) {
  67618. if (onProgress === void 0) { onProgress = null; }
  67619. if (pluginExtension === void 0) { pluginExtension = null; }
  67620. return new Promise(function (resolve, reject) {
  67621. SceneLoader.Load(rootUrl, sceneFilename, engine, function (scene) {
  67622. resolve(scene);
  67623. }, onProgress, function (scene, message, exception) {
  67624. reject(exception || new Error(message));
  67625. }, pluginExtension);
  67626. });
  67627. };
  67628. /**
  67629. * Append a scene
  67630. * @param rootUrl a string that defines the root url for scene and resources OR the concatenation of rootURL and filename (eg. http://example.com/test.glb)
  67631. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene (default: empty string)
  67632. * @param scene is the instance of BABYLON.Scene to append to
  67633. * @param onSuccess a callback with the scene when import succeeds
  67634. * @param onProgress a callback with a progress event for each file being loaded
  67635. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  67636. * @param pluginExtension the extension used to determine the plugin
  67637. * @returns The loaded plugin
  67638. */
  67639. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  67640. if (sceneFilename === void 0) { sceneFilename = ""; }
  67641. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  67642. if (onSuccess === void 0) { onSuccess = null; }
  67643. if (onProgress === void 0) { onProgress = null; }
  67644. if (onError === void 0) { onError = null; }
  67645. if (pluginExtension === void 0) { pluginExtension = null; }
  67646. if (!scene) {
  67647. BABYLON.Tools.Error("No scene available to append to");
  67648. return null;
  67649. }
  67650. if (!sceneFilename) {
  67651. sceneFilename = BABYLON.Tools.GetFilename(rootUrl);
  67652. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl);
  67653. }
  67654. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  67655. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  67656. return null;
  67657. }
  67658. if (SceneLoader.ShowLoadingScreen) {
  67659. scene.getEngine().displayLoadingUI();
  67660. }
  67661. var loadingToken = {};
  67662. scene._addPendingData(loadingToken);
  67663. var disposeHandler = function () {
  67664. scene._removePendingData(loadingToken);
  67665. scene.getEngine().hideLoadingUI();
  67666. };
  67667. var errorHandler = function (message, exception) {
  67668. var errorMessage = "Unable to load from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  67669. if (onError) {
  67670. onError(scene, errorMessage, exception);
  67671. }
  67672. else {
  67673. BABYLON.Tools.Error(errorMessage);
  67674. // should the exception be thrown?
  67675. }
  67676. disposeHandler();
  67677. };
  67678. var progressHandler = onProgress ? function (event) {
  67679. try {
  67680. onProgress(event);
  67681. }
  67682. catch (e) {
  67683. errorHandler("Error in onProgress callback", e);
  67684. }
  67685. } : undefined;
  67686. var successHandler = function () {
  67687. if (onSuccess) {
  67688. try {
  67689. onSuccess(scene);
  67690. }
  67691. catch (e) {
  67692. errorHandler("Error in onSuccess callback", e);
  67693. }
  67694. }
  67695. scene._removePendingData(loadingToken);
  67696. };
  67697. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  67698. if (sceneFilename === "") {
  67699. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl, true);
  67700. }
  67701. if (plugin.load) {
  67702. var syncedPlugin = plugin;
  67703. if (!syncedPlugin.load(scene, data, rootUrl, errorHandler)) {
  67704. return;
  67705. }
  67706. scene.loadingPluginName = plugin.name;
  67707. successHandler();
  67708. }
  67709. else {
  67710. var asyncedPlugin = plugin;
  67711. asyncedPlugin.loadAsync(scene, data, rootUrl, progressHandler).then(function () {
  67712. scene.loadingPluginName = plugin.name;
  67713. successHandler();
  67714. }).catch(function (error) {
  67715. errorHandler(error.message, error);
  67716. });
  67717. }
  67718. if (SceneLoader.ShowLoadingScreen) {
  67719. scene.executeWhenReady(function () {
  67720. scene.getEngine().hideLoadingUI();
  67721. });
  67722. }
  67723. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  67724. };
  67725. /**
  67726. * Append a scene
  67727. * @param rootUrl a string that defines the root url for scene and resources OR the concatenation of rootURL and filename (eg. http://example.com/test.glb)
  67728. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene (default: empty string)
  67729. * @param scene is the instance of BABYLON.Scene to append to
  67730. * @param onProgress a callback with a progress event for each file being loaded
  67731. * @param pluginExtension the extension used to determine the plugin
  67732. * @returns The given scene
  67733. */
  67734. SceneLoader.AppendAsync = function (rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  67735. if (sceneFilename === void 0) { sceneFilename = ""; }
  67736. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  67737. if (onProgress === void 0) { onProgress = null; }
  67738. if (pluginExtension === void 0) { pluginExtension = null; }
  67739. return new Promise(function (resolve, reject) {
  67740. SceneLoader.Append(rootUrl, sceneFilename, scene, function (scene) {
  67741. resolve(scene);
  67742. }, onProgress, function (scene, message, exception) {
  67743. reject(exception || new Error(message));
  67744. }, pluginExtension);
  67745. });
  67746. };
  67747. /**
  67748. * Load a scene into an asset container
  67749. * @param rootUrl a string that defines the root url for scene and resources OR the concatenation of rootURL and filename (eg. http://example.com/test.glb)
  67750. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene (default: empty string)
  67751. * @param scene is the instance of BABYLON.Scene to append to (default: last created scene)
  67752. * @param onSuccess a callback with the scene when import succeeds
  67753. * @param onProgress a callback with a progress event for each file being loaded
  67754. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  67755. * @param pluginExtension the extension used to determine the plugin
  67756. * @returns The loaded plugin
  67757. */
  67758. SceneLoader.LoadAssetContainer = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  67759. if (sceneFilename === void 0) { sceneFilename = ""; }
  67760. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  67761. if (onSuccess === void 0) { onSuccess = null; }
  67762. if (onProgress === void 0) { onProgress = null; }
  67763. if (onError === void 0) { onError = null; }
  67764. if (pluginExtension === void 0) { pluginExtension = null; }
  67765. if (!scene) {
  67766. BABYLON.Tools.Error("No scene available to load asset container to");
  67767. return null;
  67768. }
  67769. if (!sceneFilename) {
  67770. sceneFilename = BABYLON.Tools.GetFilename(rootUrl);
  67771. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl);
  67772. }
  67773. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  67774. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  67775. return null;
  67776. }
  67777. var loadingToken = {};
  67778. scene._addPendingData(loadingToken);
  67779. var disposeHandler = function () {
  67780. scene._removePendingData(loadingToken);
  67781. };
  67782. var errorHandler = function (message, exception) {
  67783. var errorMessage = "Unable to load assets from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  67784. if (onError) {
  67785. onError(scene, errorMessage, exception);
  67786. }
  67787. else {
  67788. BABYLON.Tools.Error(errorMessage);
  67789. // should the exception be thrown?
  67790. }
  67791. disposeHandler();
  67792. };
  67793. var progressHandler = onProgress ? function (event) {
  67794. try {
  67795. onProgress(event);
  67796. }
  67797. catch (e) {
  67798. errorHandler("Error in onProgress callback", e);
  67799. }
  67800. } : undefined;
  67801. var successHandler = function (assets) {
  67802. if (onSuccess) {
  67803. try {
  67804. onSuccess(assets);
  67805. }
  67806. catch (e) {
  67807. errorHandler("Error in onSuccess callback", e);
  67808. }
  67809. }
  67810. scene._removePendingData(loadingToken);
  67811. };
  67812. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  67813. if (plugin.loadAssetContainer) {
  67814. var syncedPlugin = plugin;
  67815. var assetContainer = syncedPlugin.loadAssetContainer(scene, data, rootUrl, errorHandler);
  67816. if (!assetContainer) {
  67817. return;
  67818. }
  67819. scene.loadingPluginName = plugin.name;
  67820. successHandler(assetContainer);
  67821. }
  67822. else if (plugin.loadAssetContainerAsync) {
  67823. var asyncedPlugin = plugin;
  67824. asyncedPlugin.loadAssetContainerAsync(scene, data, rootUrl, progressHandler).then(function (assetContainer) {
  67825. scene.loadingPluginName = plugin.name;
  67826. successHandler(assetContainer);
  67827. }).catch(function (error) {
  67828. errorHandler(error.message, error);
  67829. });
  67830. }
  67831. else {
  67832. errorHandler("LoadAssetContainer is not supported by this plugin. Plugin did not provide a loadAssetContainer or loadAssetContainerAsync method.");
  67833. }
  67834. if (SceneLoader.ShowLoadingScreen) {
  67835. scene.executeWhenReady(function () {
  67836. scene.getEngine().hideLoadingUI();
  67837. });
  67838. }
  67839. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  67840. };
  67841. /**
  67842. * Load a scene into an asset container
  67843. * @param rootUrl a string that defines the root url for scene and resources OR the concatenation of rootURL and filename (eg. http://example.com/test.glb)
  67844. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene (default: empty string)
  67845. * @param scene is the instance of BABYLON.Scene to append to
  67846. * @param onProgress a callback with a progress event for each file being loaded
  67847. * @param pluginExtension the extension used to determine the plugin
  67848. * @returns The loaded asset container
  67849. */
  67850. SceneLoader.LoadAssetContainerAsync = function (rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  67851. if (sceneFilename === void 0) { sceneFilename = ""; }
  67852. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  67853. if (onProgress === void 0) { onProgress = null; }
  67854. if (pluginExtension === void 0) { pluginExtension = null; }
  67855. return new Promise(function (resolve, reject) {
  67856. SceneLoader.LoadAssetContainer(rootUrl, sceneFilename, scene, function (assetContainer) {
  67857. resolve(assetContainer);
  67858. }, onProgress, function (scene, message, exception) {
  67859. reject(exception || new Error(message));
  67860. }, pluginExtension);
  67861. });
  67862. };
  67863. // Flags
  67864. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  67865. SceneLoader._ShowLoadingScreen = true;
  67866. SceneLoader._CleanBoneMatrixWeights = false;
  67867. SceneLoader._loggingLevel = SceneLoader.NO_LOGGING;
  67868. // Members
  67869. SceneLoader.OnPluginActivatedObservable = new BABYLON.Observable();
  67870. SceneLoader._registeredPlugins = {};
  67871. return SceneLoader;
  67872. }());
  67873. BABYLON.SceneLoader = SceneLoader;
  67874. ;
  67875. })(BABYLON || (BABYLON = {}));
  67876. //# sourceMappingURL=babylon.sceneLoader.js.map
  67877. var BABYLON;
  67878. (function (BABYLON) {
  67879. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  67880. for (var index = 0, cache = parsedData.materials.length; index < cache; index++) {
  67881. var parsedMaterial = parsedData.materials[index];
  67882. if (parsedMaterial.id === id) {
  67883. return BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  67884. }
  67885. }
  67886. return null;
  67887. };
  67888. var isDescendantOf = function (mesh, names, hierarchyIds) {
  67889. for (var i in names) {
  67890. if (mesh.name === names[i]) {
  67891. hierarchyIds.push(mesh.id);
  67892. return true;
  67893. }
  67894. }
  67895. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  67896. hierarchyIds.push(mesh.id);
  67897. return true;
  67898. }
  67899. return false;
  67900. };
  67901. var logOperation = function (operation, producer) {
  67902. return operation + " of " + (producer ? producer.file + " from " + producer.name + " version: " + producer.version + ", exporter version: " + producer.exporter_version : "unknown");
  67903. };
  67904. var loadAssetContainer = function (scene, data, rootUrl, onError, addToScene) {
  67905. if (addToScene === void 0) { addToScene = false; }
  67906. var container = new BABYLON.AssetContainer(scene);
  67907. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  67908. // when SceneLoader.debugLogging = true (default), or exception encountered.
  67909. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  67910. // and avoid problems with multiple concurrent .babylon loads.
  67911. var log = "importScene has failed JSON parse";
  67912. try {
  67913. var parsedData = JSON.parse(data);
  67914. log = "";
  67915. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  67916. var index;
  67917. var cache;
  67918. // Lights
  67919. if (parsedData.lights !== undefined && parsedData.lights !== null) {
  67920. for (index = 0, cache = parsedData.lights.length; index < cache; index++) {
  67921. var parsedLight = parsedData.lights[index];
  67922. var light = BABYLON.Light.Parse(parsedLight, scene);
  67923. if (light) {
  67924. container.lights.push(light);
  67925. log += (index === 0 ? "\n\tLights:" : "");
  67926. log += "\n\t\t" + light.toString(fullDetails);
  67927. }
  67928. }
  67929. }
  67930. // Animations
  67931. if (parsedData.animations !== undefined && parsedData.animations !== null) {
  67932. for (index = 0, cache = parsedData.animations.length; index < cache; index++) {
  67933. var parsedAnimation = parsedData.animations[index];
  67934. var animation = BABYLON.Animation.Parse(parsedAnimation);
  67935. scene.animations.push(animation);
  67936. container.animations.push(animation);
  67937. log += (index === 0 ? "\n\tAnimations:" : "");
  67938. log += "\n\t\t" + animation.toString(fullDetails);
  67939. }
  67940. }
  67941. // Materials
  67942. if (parsedData.materials !== undefined && parsedData.materials !== null) {
  67943. for (index = 0, cache = parsedData.materials.length; index < cache; index++) {
  67944. var parsedMaterial = parsedData.materials[index];
  67945. var mat = BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  67946. container.materials.push(mat);
  67947. log += (index === 0 ? "\n\tMaterials:" : "");
  67948. log += "\n\t\t" + mat.toString(fullDetails);
  67949. }
  67950. }
  67951. if (parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  67952. for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) {
  67953. var parsedMultiMaterial = parsedData.multiMaterials[index];
  67954. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  67955. container.multiMaterials.push(mmat);
  67956. log += (index === 0 ? "\n\tMultiMaterials:" : "");
  67957. log += "\n\t\t" + mmat.toString(fullDetails);
  67958. }
  67959. }
  67960. // Morph targets
  67961. if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
  67962. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  67963. var managerData = _a[_i];
  67964. container.morphTargetManagers.push(BABYLON.MorphTargetManager.Parse(managerData, scene));
  67965. }
  67966. }
  67967. // Skeletons
  67968. if (parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  67969. for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) {
  67970. var parsedSkeleton = parsedData.skeletons[index];
  67971. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  67972. container.skeletons.push(skeleton);
  67973. log += (index === 0 ? "\n\tSkeletons:" : "");
  67974. log += "\n\t\t" + skeleton.toString(fullDetails);
  67975. }
  67976. }
  67977. // Geometries
  67978. var geometries = parsedData.geometries;
  67979. if (geometries !== undefined && geometries !== null) {
  67980. var addedGeometry = new Array();
  67981. // Boxes
  67982. var boxes = geometries.boxes;
  67983. if (boxes !== undefined && boxes !== null) {
  67984. for (index = 0, cache = boxes.length; index < cache; index++) {
  67985. var parsedBox = boxes[index];
  67986. addedGeometry.push(BABYLON.BoxGeometry.Parse(parsedBox, scene));
  67987. }
  67988. }
  67989. // Spheres
  67990. var spheres = geometries.spheres;
  67991. if (spheres !== undefined && spheres !== null) {
  67992. for (index = 0, cache = spheres.length; index < cache; index++) {
  67993. var parsedSphere = spheres[index];
  67994. addedGeometry.push(BABYLON.SphereGeometry.Parse(parsedSphere, scene));
  67995. }
  67996. }
  67997. // Cylinders
  67998. var cylinders = geometries.cylinders;
  67999. if (cylinders !== undefined && cylinders !== null) {
  68000. for (index = 0, cache = cylinders.length; index < cache; index++) {
  68001. var parsedCylinder = cylinders[index];
  68002. addedGeometry.push(BABYLON.CylinderGeometry.Parse(parsedCylinder, scene));
  68003. }
  68004. }
  68005. // Toruses
  68006. var toruses = geometries.toruses;
  68007. if (toruses !== undefined && toruses !== null) {
  68008. for (index = 0, cache = toruses.length; index < cache; index++) {
  68009. var parsedTorus = toruses[index];
  68010. addedGeometry.push(BABYLON.TorusGeometry.Parse(parsedTorus, scene));
  68011. }
  68012. }
  68013. // Grounds
  68014. var grounds = geometries.grounds;
  68015. if (grounds !== undefined && grounds !== null) {
  68016. for (index = 0, cache = grounds.length; index < cache; index++) {
  68017. var parsedGround = grounds[index];
  68018. addedGeometry.push(BABYLON.GroundGeometry.Parse(parsedGround, scene));
  68019. }
  68020. }
  68021. // Planes
  68022. var planes = geometries.planes;
  68023. if (planes !== undefined && planes !== null) {
  68024. for (index = 0, cache = planes.length; index < cache; index++) {
  68025. var parsedPlane = planes[index];
  68026. addedGeometry.push(BABYLON.PlaneGeometry.Parse(parsedPlane, scene));
  68027. }
  68028. }
  68029. // TorusKnots
  68030. var torusKnots = geometries.torusKnots;
  68031. if (torusKnots !== undefined && torusKnots !== null) {
  68032. for (index = 0, cache = torusKnots.length; index < cache; index++) {
  68033. var parsedTorusKnot = torusKnots[index];
  68034. addedGeometry.push(BABYLON.TorusKnotGeometry.Parse(parsedTorusKnot, scene));
  68035. }
  68036. }
  68037. // VertexData
  68038. var vertexData = geometries.vertexData;
  68039. if (vertexData !== undefined && vertexData !== null) {
  68040. for (index = 0, cache = vertexData.length; index < cache; index++) {
  68041. var parsedVertexData = vertexData[index];
  68042. addedGeometry.push(BABYLON.Geometry.Parse(parsedVertexData, scene, rootUrl));
  68043. }
  68044. }
  68045. addedGeometry.forEach(function (g) {
  68046. if (g) {
  68047. container.geometries.push(g);
  68048. }
  68049. });
  68050. }
  68051. // Transform nodes
  68052. if (parsedData.transformNodes !== undefined && parsedData.transformNodes !== null) {
  68053. for (index = 0, cache = parsedData.transformNodes.length; index < cache; index++) {
  68054. var parsedTransformNode = parsedData.transformNodes[index];
  68055. var node = BABYLON.TransformNode.Parse(parsedTransformNode, scene, rootUrl);
  68056. container.transformNodes.push(node);
  68057. }
  68058. }
  68059. // Meshes
  68060. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  68061. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  68062. var parsedMesh = parsedData.meshes[index];
  68063. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  68064. container.meshes.push(mesh);
  68065. log += (index === 0 ? "\n\tMeshes:" : "");
  68066. log += "\n\t\t" + mesh.toString(fullDetails);
  68067. }
  68068. }
  68069. // Cameras
  68070. if (parsedData.cameras !== undefined && parsedData.cameras !== null) {
  68071. for (index = 0, cache = parsedData.cameras.length; index < cache; index++) {
  68072. var parsedCamera = parsedData.cameras[index];
  68073. var camera = BABYLON.Camera.Parse(parsedCamera, scene);
  68074. container.cameras.push(camera);
  68075. log += (index === 0 ? "\n\tCameras:" : "");
  68076. log += "\n\t\t" + camera.toString(fullDetails);
  68077. }
  68078. }
  68079. // Browsing all the graph to connect the dots
  68080. for (index = 0, cache = scene.cameras.length; index < cache; index++) {
  68081. var camera = scene.cameras[index];
  68082. if (camera._waitingParentId) {
  68083. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  68084. camera._waitingParentId = null;
  68085. }
  68086. }
  68087. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  68088. var light_1 = scene.lights[index];
  68089. if (light_1 && light_1._waitingParentId) {
  68090. light_1.parent = scene.getLastEntryByID(light_1._waitingParentId);
  68091. light_1._waitingParentId = null;
  68092. }
  68093. }
  68094. // Sounds
  68095. // TODO: add sound
  68096. var loadedSounds = [];
  68097. var loadedSound;
  68098. if (BABYLON.AudioEngine && parsedData.sounds !== undefined && parsedData.sounds !== null) {
  68099. for (index = 0, cache = parsedData.sounds.length; index < cache; index++) {
  68100. var parsedSound = parsedData.sounds[index];
  68101. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  68102. if (!parsedSound.url)
  68103. parsedSound.url = parsedSound.name;
  68104. if (!loadedSounds[parsedSound.url]) {
  68105. loadedSound = BABYLON.Sound.Parse(parsedSound, scene, rootUrl);
  68106. loadedSounds[parsedSound.url] = loadedSound;
  68107. container.sounds.push(loadedSound);
  68108. }
  68109. else {
  68110. container.sounds.push(BABYLON.Sound.Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.url]));
  68111. }
  68112. }
  68113. else {
  68114. container.sounds.push(new BABYLON.Sound(parsedSound.name, null, scene));
  68115. }
  68116. }
  68117. }
  68118. loadedSounds = [];
  68119. // Connect parents & children and parse actions
  68120. for (index = 0, cache = scene.transformNodes.length; index < cache; index++) {
  68121. var transformNode = scene.transformNodes[index];
  68122. if (transformNode._waitingParentId) {
  68123. transformNode.parent = scene.getLastEntryByID(transformNode._waitingParentId);
  68124. transformNode._waitingParentId = null;
  68125. }
  68126. }
  68127. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  68128. var mesh = scene.meshes[index];
  68129. if (mesh._waitingParentId) {
  68130. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  68131. mesh._waitingParentId = null;
  68132. }
  68133. if (mesh._waitingActions) {
  68134. BABYLON.ActionManager.Parse(mesh._waitingActions, mesh, scene);
  68135. mesh._waitingActions = null;
  68136. }
  68137. }
  68138. // freeze world matrix application
  68139. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  68140. var currentMesh = scene.meshes[index];
  68141. if (currentMesh._waitingFreezeWorldMatrix) {
  68142. currentMesh.freezeWorldMatrix();
  68143. currentMesh._waitingFreezeWorldMatrix = null;
  68144. }
  68145. else {
  68146. currentMesh.computeWorldMatrix(true);
  68147. }
  68148. }
  68149. // Particles Systems
  68150. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  68151. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  68152. var parsedParticleSystem = parsedData.particleSystems[index];
  68153. if (parsedParticleSystem.activeParticleCount) {
  68154. var ps = BABYLON.GPUParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  68155. container.particleSystems.push(ps);
  68156. }
  68157. else {
  68158. var ps = BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  68159. container.particleSystems.push(ps);
  68160. }
  68161. }
  68162. }
  68163. // Lens flares
  68164. if (parsedData.lensFlareSystems !== undefined && parsedData.lensFlareSystems !== null) {
  68165. for (index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) {
  68166. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  68167. var lf = BABYLON.LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl);
  68168. container.lensFlareSystems.push(lf);
  68169. }
  68170. }
  68171. // Shadows
  68172. if (parsedData.shadowGenerators !== undefined && parsedData.shadowGenerators !== null) {
  68173. for (index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) {
  68174. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  68175. var sg = BABYLON.ShadowGenerator.Parse(parsedShadowGenerator, scene);
  68176. container.shadowGenerators.push(sg);
  68177. }
  68178. }
  68179. // Lights exclusions / inclusions
  68180. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  68181. var light_2 = scene.lights[index];
  68182. // Excluded check
  68183. if (light_2._excludedMeshesIds.length > 0) {
  68184. for (var excludedIndex = 0; excludedIndex < light_2._excludedMeshesIds.length; excludedIndex++) {
  68185. var excludedMesh = scene.getMeshByID(light_2._excludedMeshesIds[excludedIndex]);
  68186. if (excludedMesh) {
  68187. light_2.excludedMeshes.push(excludedMesh);
  68188. }
  68189. }
  68190. light_2._excludedMeshesIds = [];
  68191. }
  68192. // Included check
  68193. if (light_2._includedOnlyMeshesIds.length > 0) {
  68194. for (var includedOnlyIndex = 0; includedOnlyIndex < light_2._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  68195. var includedOnlyMesh = scene.getMeshByID(light_2._includedOnlyMeshesIds[includedOnlyIndex]);
  68196. if (includedOnlyMesh) {
  68197. light_2.includedOnlyMeshes.push(includedOnlyMesh);
  68198. }
  68199. }
  68200. light_2._includedOnlyMeshesIds = [];
  68201. }
  68202. }
  68203. // Effect layers
  68204. if (parsedData.effectLayers) {
  68205. for (index = 0; index < parsedData.effectLayers.length; index++) {
  68206. var effectLayer = BABYLON.EffectLayer.Parse(parsedData.effectLayers[index], scene, rootUrl);
  68207. container.effectLayers.push(effectLayer);
  68208. }
  68209. }
  68210. // Actions (scene)
  68211. if (parsedData.actions !== undefined && parsedData.actions !== null) {
  68212. BABYLON.ActionManager.Parse(parsedData.actions, null, scene);
  68213. }
  68214. if (!addToScene) {
  68215. container.removeAllFromScene();
  68216. }
  68217. }
  68218. catch (err) {
  68219. var msg = logOperation("loadAssts", parsedData ? parsedData.producer : "Unknown") + log;
  68220. if (onError) {
  68221. onError(msg, err);
  68222. }
  68223. else {
  68224. BABYLON.Tools.Log(msg);
  68225. throw err;
  68226. }
  68227. }
  68228. finally {
  68229. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  68230. BABYLON.Tools.Log(logOperation("loadAssts", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  68231. }
  68232. }
  68233. return container;
  68234. };
  68235. BABYLON.SceneLoader.RegisterPlugin({
  68236. name: "babylon.js",
  68237. extensions: ".babylon",
  68238. canDirectLoad: function (data) {
  68239. if (data.indexOf("babylon") !== -1) { // We consider that the producer string is filled
  68240. return true;
  68241. }
  68242. return false;
  68243. },
  68244. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons, onError) {
  68245. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  68246. // when SceneLoader.debugLogging = true (default), or exception encountered.
  68247. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  68248. // and avoid problems with multiple concurrent .babylon loads.
  68249. var log = "importMesh has failed JSON parse";
  68250. try {
  68251. var parsedData = JSON.parse(data);
  68252. log = "";
  68253. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  68254. if (!meshesNames) {
  68255. meshesNames = null;
  68256. }
  68257. else if (!Array.isArray(meshesNames)) {
  68258. meshesNames = [meshesNames];
  68259. }
  68260. var hierarchyIds = new Array();
  68261. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  68262. var loadedSkeletonsIds = [];
  68263. var loadedMaterialsIds = [];
  68264. var index;
  68265. var cache;
  68266. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  68267. var parsedMesh = parsedData.meshes[index];
  68268. if (meshesNames === null || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  68269. if (meshesNames !== null) {
  68270. // Remove found mesh name from list.
  68271. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  68272. }
  68273. //Geometry?
  68274. if (parsedMesh.geometryId !== undefined && parsedMesh.geometryId !== null) {
  68275. //does the file contain geometries?
  68276. if (parsedData.geometries !== undefined && parsedData.geometries !== null) {
  68277. //find the correct geometry and add it to the scene
  68278. var found = false;
  68279. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  68280. if (found === true || !parsedData.geometries[geometryType] || !(Array.isArray(parsedData.geometries[geometryType]))) {
  68281. return;
  68282. }
  68283. else {
  68284. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  68285. if (parsedGeometryData.id === parsedMesh.geometryId) {
  68286. switch (geometryType) {
  68287. case "boxes":
  68288. BABYLON.BoxGeometry.Parse(parsedGeometryData, scene);
  68289. break;
  68290. case "spheres":
  68291. BABYLON.SphereGeometry.Parse(parsedGeometryData, scene);
  68292. break;
  68293. case "cylinders":
  68294. BABYLON.CylinderGeometry.Parse(parsedGeometryData, scene);
  68295. break;
  68296. case "toruses":
  68297. BABYLON.TorusGeometry.Parse(parsedGeometryData, scene);
  68298. break;
  68299. case "grounds":
  68300. BABYLON.GroundGeometry.Parse(parsedGeometryData, scene);
  68301. break;
  68302. case "planes":
  68303. BABYLON.PlaneGeometry.Parse(parsedGeometryData, scene);
  68304. break;
  68305. case "torusKnots":
  68306. BABYLON.TorusKnotGeometry.Parse(parsedGeometryData, scene);
  68307. break;
  68308. case "vertexData":
  68309. BABYLON.Geometry.Parse(parsedGeometryData, scene, rootUrl);
  68310. break;
  68311. }
  68312. found = true;
  68313. }
  68314. });
  68315. }
  68316. });
  68317. if (found === false) {
  68318. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  68319. }
  68320. }
  68321. }
  68322. // Material ?
  68323. if (parsedMesh.materialId) {
  68324. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  68325. if (materialFound === false && parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  68326. for (var multimatIndex = 0, multimatCache = parsedData.multiMaterials.length; multimatIndex < multimatCache; multimatIndex++) {
  68327. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  68328. if (parsedMultiMaterial.id === parsedMesh.materialId) {
  68329. for (var matIndex = 0, matCache = parsedMultiMaterial.materials.length; matIndex < matCache; matIndex++) {
  68330. var subMatId = parsedMultiMaterial.materials[matIndex];
  68331. loadedMaterialsIds.push(subMatId);
  68332. var mat = parseMaterialById(subMatId, parsedData, scene, rootUrl);
  68333. if (mat) {
  68334. log += "\n\tMaterial " + mat.toString(fullDetails);
  68335. }
  68336. }
  68337. loadedMaterialsIds.push(parsedMultiMaterial.id);
  68338. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  68339. if (mmat) {
  68340. materialFound = true;
  68341. log += "\n\tMulti-Material " + mmat.toString(fullDetails);
  68342. }
  68343. break;
  68344. }
  68345. }
  68346. }
  68347. if (materialFound === false) {
  68348. loadedMaterialsIds.push(parsedMesh.materialId);
  68349. var mat = parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  68350. if (!mat) {
  68351. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  68352. }
  68353. else {
  68354. log += "\n\tMaterial " + mat.toString(fullDetails);
  68355. }
  68356. }
  68357. }
  68358. // Skeleton ?
  68359. if (parsedMesh.skeletonId > -1 && parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  68360. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  68361. if (skeletonAlreadyLoaded === false) {
  68362. for (var skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) {
  68363. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  68364. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  68365. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  68366. skeletons.push(skeleton);
  68367. loadedSkeletonsIds.push(parsedSkeleton.id);
  68368. log += "\n\tSkeleton " + skeleton.toString(fullDetails);
  68369. }
  68370. }
  68371. }
  68372. }
  68373. // Morph targets ?
  68374. if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
  68375. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  68376. var managerData = _a[_i];
  68377. BABYLON.MorphTargetManager.Parse(managerData, scene);
  68378. }
  68379. }
  68380. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  68381. meshes.push(mesh);
  68382. log += "\n\tMesh " + mesh.toString(fullDetails);
  68383. }
  68384. }
  68385. // Connecting parents
  68386. var currentMesh;
  68387. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  68388. currentMesh = scene.meshes[index];
  68389. if (currentMesh._waitingParentId) {
  68390. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  68391. currentMesh._waitingParentId = null;
  68392. }
  68393. }
  68394. // freeze and compute world matrix application
  68395. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  68396. currentMesh = scene.meshes[index];
  68397. if (currentMesh._waitingFreezeWorldMatrix) {
  68398. currentMesh.freezeWorldMatrix();
  68399. currentMesh._waitingFreezeWorldMatrix = null;
  68400. }
  68401. else {
  68402. currentMesh.computeWorldMatrix(true);
  68403. }
  68404. }
  68405. }
  68406. // Particles
  68407. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  68408. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  68409. var parsedParticleSystem = parsedData.particleSystems[index];
  68410. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  68411. particleSystems.push(BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl));
  68412. }
  68413. }
  68414. }
  68415. return true;
  68416. }
  68417. catch (err) {
  68418. var msg = logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + log;
  68419. if (onError) {
  68420. onError(msg, err);
  68421. }
  68422. else {
  68423. BABYLON.Tools.Log(msg);
  68424. throw err;
  68425. }
  68426. }
  68427. finally {
  68428. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  68429. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  68430. }
  68431. }
  68432. return false;
  68433. },
  68434. load: function (scene, data, rootUrl, onError) {
  68435. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  68436. // when SceneLoader.debugLogging = true (default), or exception encountered.
  68437. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  68438. // and avoid problems with multiple concurrent .babylon loads.
  68439. var log = "importScene has failed JSON parse";
  68440. try {
  68441. var parsedData = JSON.parse(data);
  68442. log = "";
  68443. // Scene
  68444. if (parsedData.useDelayedTextureLoading !== undefined && parsedData.useDelayedTextureLoading !== null) {
  68445. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  68446. }
  68447. if (parsedData.autoClear !== undefined && parsedData.autoClear !== null) {
  68448. scene.autoClear = parsedData.autoClear;
  68449. }
  68450. if (parsedData.clearColor !== undefined && parsedData.clearColor !== null) {
  68451. scene.clearColor = BABYLON.Color4.FromArray(parsedData.clearColor);
  68452. }
  68453. if (parsedData.ambientColor !== undefined && parsedData.ambientColor !== null) {
  68454. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  68455. }
  68456. if (parsedData.gravity !== undefined && parsedData.gravity !== null) {
  68457. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  68458. }
  68459. // Fog
  68460. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  68461. scene.fogMode = parsedData.fogMode;
  68462. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  68463. scene.fogStart = parsedData.fogStart;
  68464. scene.fogEnd = parsedData.fogEnd;
  68465. scene.fogDensity = parsedData.fogDensity;
  68466. log += "\tFog mode for scene: ";
  68467. switch (scene.fogMode) {
  68468. // getters not compiling, so using hardcoded
  68469. case 1:
  68470. log += "exp\n";
  68471. break;
  68472. case 2:
  68473. log += "exp2\n";
  68474. break;
  68475. case 3:
  68476. log += "linear\n";
  68477. break;
  68478. }
  68479. }
  68480. //Physics
  68481. if (parsedData.physicsEnabled) {
  68482. var physicsPlugin;
  68483. if (parsedData.physicsEngine === "cannon") {
  68484. physicsPlugin = new BABYLON.CannonJSPlugin();
  68485. }
  68486. else if (parsedData.physicsEngine === "oimo") {
  68487. physicsPlugin = new BABYLON.OimoJSPlugin();
  68488. }
  68489. log = "\tPhysics engine " + (parsedData.physicsEngine ? parsedData.physicsEngine : "oimo") + " enabled\n";
  68490. //else - default engine, which is currently oimo
  68491. var physicsGravity = parsedData.physicsGravity ? BABYLON.Vector3.FromArray(parsedData.physicsGravity) : null;
  68492. scene.enablePhysics(physicsGravity, physicsPlugin);
  68493. }
  68494. // Metadata
  68495. if (parsedData.metadata !== undefined && parsedData.metadata !== null) {
  68496. scene.metadata = parsedData.metadata;
  68497. }
  68498. //collisions, if defined. otherwise, default is true
  68499. if (parsedData.collisionsEnabled !== undefined && parsedData.collisionsEnabled !== null) {
  68500. scene.collisionsEnabled = parsedData.collisionsEnabled;
  68501. }
  68502. scene.workerCollisions = !!parsedData.workerCollisions;
  68503. var container = loadAssetContainer(scene, data, rootUrl, onError, true);
  68504. if (!container) {
  68505. return false;
  68506. }
  68507. if (parsedData.autoAnimate) {
  68508. scene.beginAnimation(scene, parsedData.autoAnimateFrom, parsedData.autoAnimateTo, parsedData.autoAnimateLoop, parsedData.autoAnimateSpeed || 1.0);
  68509. }
  68510. if (parsedData.activeCameraID !== undefined && parsedData.activeCameraID !== null) {
  68511. scene.setActiveCameraByID(parsedData.activeCameraID);
  68512. }
  68513. // Environment texture
  68514. if (parsedData.environmentTexture !== undefined && parsedData.environmentTexture !== null) {
  68515. if (parsedData.environmentTextureType && parsedData.environmentTextureType === "BABYLON.HDRCubeTexture") {
  68516. var hdrSize = (parsedData.environmentTextureSize) ? parsedData.environmentTextureSize : 128;
  68517. var hdrTexture = new BABYLON.HDRCubeTexture(rootUrl + parsedData.environmentTexture, scene, hdrSize);
  68518. if (parsedData.environmentTextureRotationY) {
  68519. hdrTexture.rotationY = parsedData.environmentTextureRotationY;
  68520. }
  68521. scene.environmentTexture = hdrTexture;
  68522. }
  68523. else {
  68524. var cubeTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(rootUrl + parsedData.environmentTexture, scene);
  68525. if (parsedData.environmentTextureRotationY) {
  68526. cubeTexture.rotationY = parsedData.environmentTextureRotationY;
  68527. }
  68528. scene.environmentTexture = cubeTexture;
  68529. }
  68530. if (parsedData.createDefaultSkybox === true) {
  68531. var skyboxScale = (scene.activeCamera !== undefined && scene.activeCamera !== null) ? (scene.activeCamera.maxZ - scene.activeCamera.minZ) / 2 : 1000;
  68532. var skyboxBlurLevel = parsedData.skyboxBlurLevel || 0;
  68533. scene.createDefaultSkybox(undefined, true, skyboxScale, skyboxBlurLevel);
  68534. }
  68535. }
  68536. // Finish
  68537. return true;
  68538. }
  68539. catch (err) {
  68540. var msg = logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + log;
  68541. if (onError) {
  68542. onError(msg, err);
  68543. }
  68544. else {
  68545. BABYLON.Tools.Log(msg);
  68546. throw err;
  68547. }
  68548. }
  68549. finally {
  68550. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  68551. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  68552. }
  68553. }
  68554. return false;
  68555. },
  68556. loadAssetContainer: function (scene, data, rootUrl, onError) {
  68557. var container = loadAssetContainer(scene, data, rootUrl, onError);
  68558. return container;
  68559. }
  68560. });
  68561. })(BABYLON || (BABYLON = {}));
  68562. //# sourceMappingURL=babylon.babylonFileLoader.js.map
  68563. var BABYLON;
  68564. (function (BABYLON) {
  68565. var FilesInput = /** @class */ (function () {
  68566. function FilesInput(engine, scene, sceneLoadedCallback, progressCallback, additionalRenderLoopLogicCallback, textureLoadingCallback, startingProcessingFilesCallback, onReloadCallback, errorCallback) {
  68567. this.onProcessFileCallback = function () { return true; };
  68568. this._engine = engine;
  68569. this._currentScene = scene;
  68570. this._sceneLoadedCallback = sceneLoadedCallback;
  68571. this._progressCallback = progressCallback;
  68572. this._additionalRenderLoopLogicCallback = additionalRenderLoopLogicCallback;
  68573. this._textureLoadingCallback = textureLoadingCallback;
  68574. this._startingProcessingFilesCallback = startingProcessingFilesCallback;
  68575. this._onReloadCallback = onReloadCallback;
  68576. this._errorCallback = errorCallback;
  68577. }
  68578. FilesInput.prototype.monitorElementForDragNDrop = function (elementToMonitor) {
  68579. var _this = this;
  68580. if (elementToMonitor) {
  68581. this._elementToMonitor = elementToMonitor;
  68582. this._dragEnterHandler = function (e) { _this.drag(e); };
  68583. this._dragOverHandler = function (e) { _this.drag(e); };
  68584. this._dropHandler = function (e) { _this.drop(e); };
  68585. this._elementToMonitor.addEventListener("dragenter", this._dragEnterHandler, false);
  68586. this._elementToMonitor.addEventListener("dragover", this._dragOverHandler, false);
  68587. this._elementToMonitor.addEventListener("drop", this._dropHandler, false);
  68588. }
  68589. };
  68590. FilesInput.prototype.dispose = function () {
  68591. if (!this._elementToMonitor) {
  68592. return;
  68593. }
  68594. this._elementToMonitor.removeEventListener("dragenter", this._dragEnterHandler);
  68595. this._elementToMonitor.removeEventListener("dragover", this._dragOverHandler);
  68596. this._elementToMonitor.removeEventListener("drop", this._dropHandler);
  68597. };
  68598. FilesInput.prototype.renderFunction = function () {
  68599. if (this._additionalRenderLoopLogicCallback) {
  68600. this._additionalRenderLoopLogicCallback();
  68601. }
  68602. if (this._currentScene) {
  68603. if (this._textureLoadingCallback) {
  68604. var remaining = this._currentScene.getWaitingItemsCount();
  68605. if (remaining > 0) {
  68606. this._textureLoadingCallback(remaining);
  68607. }
  68608. }
  68609. this._currentScene.render();
  68610. }
  68611. };
  68612. FilesInput.prototype.drag = function (e) {
  68613. e.stopPropagation();
  68614. e.preventDefault();
  68615. };
  68616. FilesInput.prototype.drop = function (eventDrop) {
  68617. eventDrop.stopPropagation();
  68618. eventDrop.preventDefault();
  68619. this.loadFiles(eventDrop);
  68620. };
  68621. FilesInput.prototype._traverseFolder = function (folder, files, remaining, callback) {
  68622. var _this = this;
  68623. var reader = folder.createReader();
  68624. var relativePath = folder.fullPath.replace(/^\//, "").replace(/(.+?)\/?$/, "$1/");
  68625. reader.readEntries(function (entries) {
  68626. remaining.count += entries.length;
  68627. for (var _i = 0, entries_1 = entries; _i < entries_1.length; _i++) {
  68628. var entry = entries_1[_i];
  68629. if (entry.isFile) {
  68630. entry.file(function (file) {
  68631. file.correctName = relativePath + file.name;
  68632. files.push(file);
  68633. if (--remaining.count === 0) {
  68634. callback();
  68635. }
  68636. });
  68637. }
  68638. else if (entry.isDirectory) {
  68639. _this._traverseFolder(entry, files, remaining, callback);
  68640. }
  68641. }
  68642. if (--remaining.count) {
  68643. callback();
  68644. }
  68645. });
  68646. };
  68647. FilesInput.prototype._processFiles = function (files) {
  68648. for (var i = 0; i < files.length; i++) {
  68649. var name = files[i].correctName.toLowerCase();
  68650. var extension = name.split('.').pop();
  68651. if (!this.onProcessFileCallback(files[i], name, extension)) {
  68652. continue;
  68653. }
  68654. if ((extension === "babylon" || extension === "stl" || extension === "obj" || extension === "gltf" || extension === "glb")
  68655. && name.indexOf(".binary.babylon") === -1 && name.indexOf(".incremental.babylon") === -1) {
  68656. this._sceneFileToLoad = files[i];
  68657. }
  68658. else {
  68659. FilesInput.FilesToLoad[name] = files[i];
  68660. }
  68661. }
  68662. };
  68663. FilesInput.prototype.loadFiles = function (event) {
  68664. var _this = this;
  68665. if (this._startingProcessingFilesCallback)
  68666. this._startingProcessingFilesCallback();
  68667. // Handling data transfer via drag'n'drop
  68668. if (event && event.dataTransfer && event.dataTransfer.files) {
  68669. this._filesToLoad = event.dataTransfer.files;
  68670. }
  68671. // Handling files from input files
  68672. if (event && event.target && event.target.files) {
  68673. this._filesToLoad = event.target.files;
  68674. }
  68675. if (this._filesToLoad && this._filesToLoad.length > 0) {
  68676. var files_1 = new Array();
  68677. var folders = [];
  68678. var items = event.dataTransfer ? event.dataTransfer.items : null;
  68679. for (var i = 0; i < this._filesToLoad.length; i++) {
  68680. var fileToLoad = this._filesToLoad[i];
  68681. var name_1 = fileToLoad.name.toLowerCase();
  68682. var entry = void 0;
  68683. fileToLoad.correctName = name_1;
  68684. if (items) {
  68685. var item = items[i];
  68686. if (item.getAsEntry) {
  68687. entry = item.getAsEntry();
  68688. }
  68689. else if (item.webkitGetAsEntry) {
  68690. entry = item.webkitGetAsEntry();
  68691. }
  68692. }
  68693. if (!entry) {
  68694. files_1.push(fileToLoad);
  68695. }
  68696. else {
  68697. if (entry.isDirectory) {
  68698. folders.push(entry);
  68699. }
  68700. else {
  68701. files_1.push(fileToLoad);
  68702. }
  68703. }
  68704. }
  68705. if (folders.length === 0) {
  68706. this._processFiles(files_1);
  68707. this._processReload();
  68708. }
  68709. else {
  68710. var remaining = { count: folders.length };
  68711. for (var _i = 0, folders_1 = folders; _i < folders_1.length; _i++) {
  68712. var folder = folders_1[_i];
  68713. this._traverseFolder(folder, files_1, remaining, function () {
  68714. _this._processFiles(files_1);
  68715. if (remaining.count === 0) {
  68716. _this._processReload();
  68717. }
  68718. });
  68719. }
  68720. }
  68721. }
  68722. };
  68723. FilesInput.prototype._processReload = function () {
  68724. if (this._onReloadCallback) {
  68725. this._onReloadCallback(this._sceneFileToLoad);
  68726. }
  68727. else {
  68728. this.reload();
  68729. }
  68730. };
  68731. FilesInput.prototype.reload = function () {
  68732. var _this = this;
  68733. // If a scene file has been provided
  68734. if (this._sceneFileToLoad) {
  68735. if (this._currentScene) {
  68736. if (BABYLON.Tools.errorsCount > 0) {
  68737. BABYLON.Tools.ClearLogCache();
  68738. }
  68739. this._engine.stopRenderLoop();
  68740. }
  68741. BABYLON.SceneLoader.LoadAsync("file:", this._sceneFileToLoad, this._engine, function (progress) {
  68742. if (_this._progressCallback) {
  68743. _this._progressCallback(progress);
  68744. }
  68745. }).then(function (scene) {
  68746. if (_this._currentScene) {
  68747. _this._currentScene.dispose();
  68748. }
  68749. _this._currentScene = scene;
  68750. if (_this._sceneLoadedCallback) {
  68751. _this._sceneLoadedCallback(_this._sceneFileToLoad, _this._currentScene);
  68752. }
  68753. // Wait for textures and shaders to be ready
  68754. _this._currentScene.executeWhenReady(function () {
  68755. _this._engine.runRenderLoop(function () {
  68756. _this.renderFunction();
  68757. });
  68758. });
  68759. }).catch(function (error) {
  68760. if (_this._errorCallback) {
  68761. _this._errorCallback(_this._sceneFileToLoad, _this._currentScene, error.message);
  68762. }
  68763. });
  68764. }
  68765. else {
  68766. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  68767. }
  68768. };
  68769. FilesInput.FilesToLoad = {};
  68770. return FilesInput;
  68771. }());
  68772. BABYLON.FilesInput = FilesInput;
  68773. })(BABYLON || (BABYLON = {}));
  68774. //# sourceMappingURL=babylon.filesInput.js.map
  68775. var BABYLON;
  68776. (function (BABYLON) {
  68777. /**
  68778. * This class implement a typical dictionary using a string as key and the generic type T as value.
  68779. * The underlying implementation relies on an associative array to ensure the best performances.
  68780. * The value can be anything including 'null' but except 'undefined'
  68781. */
  68782. var StringDictionary = /** @class */ (function () {
  68783. function StringDictionary() {
  68784. this._count = 0;
  68785. this._data = {};
  68786. }
  68787. /**
  68788. * This will clear this dictionary and copy the content from the 'source' one.
  68789. * If the T value is a custom object, it won't be copied/cloned, the same object will be used
  68790. * @param source the dictionary to take the content from and copy to this dictionary
  68791. */
  68792. StringDictionary.prototype.copyFrom = function (source) {
  68793. var _this = this;
  68794. this.clear();
  68795. source.forEach(function (t, v) { return _this.add(t, v); });
  68796. };
  68797. /**
  68798. * Get a value based from its key
  68799. * @param key the given key to get the matching value from
  68800. * @return the value if found, otherwise undefined is returned
  68801. */
  68802. StringDictionary.prototype.get = function (key) {
  68803. var val = this._data[key];
  68804. if (val !== undefined) {
  68805. return val;
  68806. }
  68807. return undefined;
  68808. };
  68809. /**
  68810. * Get a value from its key or add it if it doesn't exist.
  68811. * This method will ensure you that a given key/data will be present in the dictionary.
  68812. * @param key the given key to get the matching value from
  68813. * @param factory the factory that will create the value if the key is not present in the dictionary.
  68814. * The factory will only be invoked if there's no data for the given key.
  68815. * @return the value corresponding to the key.
  68816. */
  68817. StringDictionary.prototype.getOrAddWithFactory = function (key, factory) {
  68818. var val = this.get(key);
  68819. if (val !== undefined) {
  68820. return val;
  68821. }
  68822. val = factory(key);
  68823. if (val) {
  68824. this.add(key, val);
  68825. }
  68826. return val;
  68827. };
  68828. /**
  68829. * Get a value from its key if present in the dictionary otherwise add it
  68830. * @param key the key to get the value from
  68831. * @param val if there's no such key/value pair in the dictionary add it with this value
  68832. * @return the value corresponding to the key
  68833. */
  68834. StringDictionary.prototype.getOrAdd = function (key, val) {
  68835. var curVal = this.get(key);
  68836. if (curVal !== undefined) {
  68837. return curVal;
  68838. }
  68839. this.add(key, val);
  68840. return val;
  68841. };
  68842. /**
  68843. * Check if there's a given key in the dictionary
  68844. * @param key the key to check for
  68845. * @return true if the key is present, false otherwise
  68846. */
  68847. StringDictionary.prototype.contains = function (key) {
  68848. return this._data[key] !== undefined;
  68849. };
  68850. /**
  68851. * Add a new key and its corresponding value
  68852. * @param key the key to add
  68853. * @param value the value corresponding to the key
  68854. * @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
  68855. */
  68856. StringDictionary.prototype.add = function (key, value) {
  68857. if (this._data[key] !== undefined) {
  68858. return false;
  68859. }
  68860. this._data[key] = value;
  68861. ++this._count;
  68862. return true;
  68863. };
  68864. StringDictionary.prototype.set = function (key, value) {
  68865. if (this._data[key] === undefined) {
  68866. return false;
  68867. }
  68868. this._data[key] = value;
  68869. return true;
  68870. };
  68871. /**
  68872. * Get the element of the given key and remove it from the dictionary
  68873. * @param key
  68874. */
  68875. StringDictionary.prototype.getAndRemove = function (key) {
  68876. var val = this.get(key);
  68877. if (val !== undefined) {
  68878. delete this._data[key];
  68879. --this._count;
  68880. return val;
  68881. }
  68882. return null;
  68883. };
  68884. /**
  68885. * Remove a key/value from the dictionary.
  68886. * @param key the key to remove
  68887. * @return true if the item was successfully deleted, false if no item with such key exist in the dictionary
  68888. */
  68889. StringDictionary.prototype.remove = function (key) {
  68890. if (this.contains(key)) {
  68891. delete this._data[key];
  68892. --this._count;
  68893. return true;
  68894. }
  68895. return false;
  68896. };
  68897. /**
  68898. * Clear the whole content of the dictionary
  68899. */
  68900. StringDictionary.prototype.clear = function () {
  68901. this._data = {};
  68902. this._count = 0;
  68903. };
  68904. Object.defineProperty(StringDictionary.prototype, "count", {
  68905. get: function () {
  68906. return this._count;
  68907. },
  68908. enumerable: true,
  68909. configurable: true
  68910. });
  68911. /**
  68912. * Execute a callback on each key/val of the dictionary.
  68913. * Note that you can remove any element in this dictionary in the callback implementation
  68914. * @param callback the callback to execute on a given key/value pair
  68915. */
  68916. StringDictionary.prototype.forEach = function (callback) {
  68917. for (var cur in this._data) {
  68918. var val = this._data[cur];
  68919. callback(cur, val);
  68920. }
  68921. };
  68922. /**
  68923. * Execute a callback on every occurrence of the dictionary until it returns a valid TRes object.
  68924. * If the callback returns null or undefined the method will iterate to the next key/value pair
  68925. * Note that you can remove any element in this dictionary in the callback implementation
  68926. * @param callback the callback to execute, if it return a valid T instanced object the enumeration will stop and the object will be returned
  68927. */
  68928. StringDictionary.prototype.first = function (callback) {
  68929. for (var cur in this._data) {
  68930. var val = this._data[cur];
  68931. var res = callback(cur, val);
  68932. if (res) {
  68933. return res;
  68934. }
  68935. }
  68936. return null;
  68937. };
  68938. return StringDictionary;
  68939. }());
  68940. BABYLON.StringDictionary = StringDictionary;
  68941. })(BABYLON || (BABYLON = {}));
  68942. //# sourceMappingURL=babylon.stringDictionary.js.map
  68943. var BABYLON;
  68944. (function (BABYLON) {
  68945. var Tags = /** @class */ (function () {
  68946. function Tags() {
  68947. }
  68948. Tags.EnableFor = function (obj) {
  68949. obj._tags = obj._tags || {};
  68950. obj.hasTags = function () {
  68951. return Tags.HasTags(obj);
  68952. };
  68953. obj.addTags = function (tagsString) {
  68954. return Tags.AddTagsTo(obj, tagsString);
  68955. };
  68956. obj.removeTags = function (tagsString) {
  68957. return Tags.RemoveTagsFrom(obj, tagsString);
  68958. };
  68959. obj.matchesTagsQuery = function (tagsQuery) {
  68960. return Tags.MatchesQuery(obj, tagsQuery);
  68961. };
  68962. };
  68963. Tags.DisableFor = function (obj) {
  68964. delete obj._tags;
  68965. delete obj.hasTags;
  68966. delete obj.addTags;
  68967. delete obj.removeTags;
  68968. delete obj.matchesTagsQuery;
  68969. };
  68970. Tags.HasTags = function (obj) {
  68971. if (!obj._tags) {
  68972. return false;
  68973. }
  68974. return !BABYLON.Tools.IsEmpty(obj._tags);
  68975. };
  68976. Tags.GetTags = function (obj, asString) {
  68977. if (asString === void 0) { asString = true; }
  68978. if (!obj._tags) {
  68979. return null;
  68980. }
  68981. if (asString) {
  68982. var tagsArray = [];
  68983. for (var tag in obj._tags) {
  68984. if (obj._tags.hasOwnProperty(tag) && obj._tags[tag] === true) {
  68985. tagsArray.push(tag);
  68986. }
  68987. }
  68988. return tagsArray.join(" ");
  68989. }
  68990. else {
  68991. return obj._tags;
  68992. }
  68993. };
  68994. // the tags 'true' and 'false' are reserved and cannot be used as tags
  68995. // a tag cannot start with '||', '&&', and '!'
  68996. // it cannot contain whitespaces
  68997. Tags.AddTagsTo = function (obj, tagsString) {
  68998. if (!tagsString) {
  68999. return;
  69000. }
  69001. if (typeof tagsString !== "string") {
  69002. return;
  69003. }
  69004. var tags = tagsString.split(" ");
  69005. tags.forEach(function (tag, index, array) {
  69006. Tags._AddTagTo(obj, tag);
  69007. });
  69008. };
  69009. Tags._AddTagTo = function (obj, tag) {
  69010. tag = tag.trim();
  69011. if (tag === "" || tag === "true" || tag === "false") {
  69012. return;
  69013. }
  69014. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  69015. return;
  69016. }
  69017. Tags.EnableFor(obj);
  69018. obj._tags[tag] = true;
  69019. };
  69020. Tags.RemoveTagsFrom = function (obj, tagsString) {
  69021. if (!Tags.HasTags(obj)) {
  69022. return;
  69023. }
  69024. var tags = tagsString.split(" ");
  69025. for (var t in tags) {
  69026. Tags._RemoveTagFrom(obj, tags[t]);
  69027. }
  69028. };
  69029. Tags._RemoveTagFrom = function (obj, tag) {
  69030. delete obj._tags[tag];
  69031. };
  69032. Tags.MatchesQuery = function (obj, tagsQuery) {
  69033. if (tagsQuery === undefined) {
  69034. return true;
  69035. }
  69036. if (tagsQuery === "") {
  69037. return Tags.HasTags(obj);
  69038. }
  69039. return BABYLON.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  69040. };
  69041. return Tags;
  69042. }());
  69043. BABYLON.Tags = Tags;
  69044. })(BABYLON || (BABYLON = {}));
  69045. //# sourceMappingURL=babylon.tags.js.map
  69046. var BABYLON;
  69047. (function (BABYLON) {
  69048. /**
  69049. * Class used to evalaute queries containing `and` and `or` operators
  69050. */
  69051. var AndOrNotEvaluator = /** @class */ (function () {
  69052. function AndOrNotEvaluator() {
  69053. }
  69054. /**
  69055. * Evaluate a query
  69056. * @param query defines the query to evaluate
  69057. * @param evaluateCallback defines the callback used to filter result
  69058. * @returns true if the query matches
  69059. */
  69060. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  69061. if (!query.match(/\([^\(\)]*\)/g)) {
  69062. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  69063. }
  69064. else {
  69065. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  69066. // remove parenthesis
  69067. r = r.slice(1, r.length - 1);
  69068. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  69069. });
  69070. }
  69071. if (query === "true") {
  69072. return true;
  69073. }
  69074. if (query === "false") {
  69075. return false;
  69076. }
  69077. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  69078. };
  69079. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  69080. evaluateCallback = evaluateCallback || (function (r) {
  69081. return r === "true" ? true : false;
  69082. });
  69083. var result;
  69084. var or = parenthesisContent.split("||");
  69085. for (var i in or) {
  69086. if (or.hasOwnProperty(i)) {
  69087. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  69088. var and = ori.split("&&");
  69089. if (and.length > 1) {
  69090. for (var j = 0; j < and.length; ++j) {
  69091. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  69092. if (andj !== "true" && andj !== "false") {
  69093. if (andj[0] === "!") {
  69094. result = !evaluateCallback(andj.substring(1));
  69095. }
  69096. else {
  69097. result = evaluateCallback(andj);
  69098. }
  69099. }
  69100. else {
  69101. result = andj === "true" ? true : false;
  69102. }
  69103. if (!result) { // no need to continue since 'false && ... && ...' will always return false
  69104. ori = "false";
  69105. break;
  69106. }
  69107. }
  69108. }
  69109. if (result || ori === "true") { // no need to continue since 'true || ... || ...' will always return true
  69110. result = true;
  69111. break;
  69112. }
  69113. // result equals false (or undefined)
  69114. if (ori !== "true" && ori !== "false") {
  69115. if (ori[0] === "!") {
  69116. result = !evaluateCallback(ori.substring(1));
  69117. }
  69118. else {
  69119. result = evaluateCallback(ori);
  69120. }
  69121. }
  69122. else {
  69123. result = ori === "true" ? true : false;
  69124. }
  69125. }
  69126. }
  69127. // the whole parenthesis scope is replaced by 'true' or 'false'
  69128. return result ? "true" : "false";
  69129. };
  69130. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  69131. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  69132. // remove whitespaces
  69133. r = r.replace(/[\s]/g, function () { return ""; });
  69134. return r.length % 2 ? "!" : "";
  69135. });
  69136. booleanString = booleanString.trim();
  69137. if (booleanString === "!true") {
  69138. booleanString = "false";
  69139. }
  69140. else if (booleanString === "!false") {
  69141. booleanString = "true";
  69142. }
  69143. return booleanString;
  69144. };
  69145. return AndOrNotEvaluator;
  69146. }());
  69147. BABYLON.AndOrNotEvaluator = AndOrNotEvaluator;
  69148. })(BABYLON || (BABYLON = {}));
  69149. //# sourceMappingURL=babylon.andOrNotEvaluator.js.map
  69150. var BABYLON;
  69151. (function (BABYLON) {
  69152. /**
  69153. * Class used to enable access to IndexedDB
  69154. * @see @https://developer.mozilla.org/en-US/docs/Web/API/IndexedDB_API
  69155. */
  69156. var Database = /** @class */ (function () {
  69157. /**
  69158. * Creates a new Database
  69159. * @param urlToScene defines the url to load the scene
  69160. * @param callbackManifestChecked defines the callback to use when manifest is checked
  69161. * @param disableManifestCheck defines a boolean indicating that we want to skip the manifest validation (it will be considered validated and up to date)
  69162. */
  69163. function Database(urlToScene, callbackManifestChecked, disableManifestCheck) {
  69164. if (disableManifestCheck === void 0) { disableManifestCheck = false; }
  69165. var _this = this;
  69166. // Handling various flavors of prefixed version of IndexedDB
  69167. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  69168. this.callbackManifestChecked = callbackManifestChecked;
  69169. this.currentSceneUrl = Database._ReturnFullUrlLocation(urlToScene);
  69170. this.db = null;
  69171. this._enableSceneOffline = false;
  69172. this._enableTexturesOffline = false;
  69173. this.manifestVersionFound = 0;
  69174. this.mustUpdateRessources = false;
  69175. this.hasReachedQuota = false;
  69176. if (!Database.IDBStorageEnabled) {
  69177. this.callbackManifestChecked(true);
  69178. }
  69179. else {
  69180. if (disableManifestCheck) {
  69181. this._enableSceneOffline = true;
  69182. this._enableTexturesOffline = true;
  69183. this.manifestVersionFound = 1;
  69184. BABYLON.Tools.SetImmediate(function () {
  69185. _this.callbackManifestChecked(true);
  69186. });
  69187. }
  69188. else {
  69189. this._checkManifestFile();
  69190. }
  69191. }
  69192. }
  69193. Object.defineProperty(Database.prototype, "enableSceneOffline", {
  69194. /**
  69195. * Gets a boolean indicating if scene must be saved in the database
  69196. */
  69197. get: function () {
  69198. return this._enableSceneOffline;
  69199. },
  69200. enumerable: true,
  69201. configurable: true
  69202. });
  69203. Object.defineProperty(Database.prototype, "enableTexturesOffline", {
  69204. /**
  69205. * Gets a boolean indicating if textures must be saved in the database
  69206. */
  69207. get: function () {
  69208. return this._enableTexturesOffline;
  69209. },
  69210. enumerable: true,
  69211. configurable: true
  69212. });
  69213. Database.prototype._checkManifestFile = function () {
  69214. var _this = this;
  69215. var noManifestFile = function () {
  69216. _this._enableSceneOffline = false;
  69217. _this._enableTexturesOffline = false;
  69218. _this.callbackManifestChecked(false);
  69219. };
  69220. var timeStampUsed = false;
  69221. var manifestURL = this.currentSceneUrl + ".manifest";
  69222. var xhr = new XMLHttpRequest();
  69223. if (navigator.onLine) {
  69224. // Adding a timestamp to by-pass browsers' cache
  69225. timeStampUsed = true;
  69226. manifestURL = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + Date.now();
  69227. }
  69228. xhr.open("GET", manifestURL, true);
  69229. xhr.addEventListener("load", function () {
  69230. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  69231. try {
  69232. var manifestFile = JSON.parse(xhr.response);
  69233. _this._enableSceneOffline = manifestFile.enableSceneOffline;
  69234. _this._enableTexturesOffline = manifestFile.enableTexturesOffline;
  69235. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  69236. _this.manifestVersionFound = manifestFile.version;
  69237. }
  69238. if (_this.callbackManifestChecked) {
  69239. _this.callbackManifestChecked(true);
  69240. }
  69241. }
  69242. catch (ex) {
  69243. noManifestFile();
  69244. }
  69245. }
  69246. else {
  69247. noManifestFile();
  69248. }
  69249. }, false);
  69250. xhr.addEventListener("error", function (event) {
  69251. if (timeStampUsed) {
  69252. timeStampUsed = false;
  69253. // Let's retry without the timeStamp
  69254. // It could fail when coupled with HTML5 Offline API
  69255. var retryManifestURL = _this.currentSceneUrl + ".manifest";
  69256. xhr.open("GET", retryManifestURL, true);
  69257. xhr.send();
  69258. }
  69259. else {
  69260. noManifestFile();
  69261. }
  69262. }, false);
  69263. try {
  69264. xhr.send();
  69265. }
  69266. catch (ex) {
  69267. BABYLON.Tools.Error("Error on XHR send request.");
  69268. this.callbackManifestChecked(false);
  69269. }
  69270. };
  69271. /**
  69272. * Open the database and make it available
  69273. * @param successCallback defines the callback to call on success
  69274. * @param errorCallback defines the callback to call on error
  69275. */
  69276. Database.prototype.openAsync = function (successCallback, errorCallback) {
  69277. var _this = this;
  69278. var handleError = function () {
  69279. _this.isSupported = false;
  69280. if (errorCallback)
  69281. errorCallback();
  69282. };
  69283. if (!this.idbFactory || !(this._enableSceneOffline || this._enableTexturesOffline)) {
  69284. // Your browser doesn't support IndexedDB
  69285. this.isSupported = false;
  69286. if (errorCallback)
  69287. errorCallback();
  69288. }
  69289. else {
  69290. // If the DB hasn't been opened or created yet
  69291. if (!this.db) {
  69292. this.hasReachedQuota = false;
  69293. this.isSupported = true;
  69294. var request = this.idbFactory.open("babylonjs", 1);
  69295. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  69296. request.onerror = function (event) {
  69297. handleError();
  69298. };
  69299. // executes when a version change transaction cannot complete due to other active transactions
  69300. request.onblocked = function (event) {
  69301. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  69302. handleError();
  69303. };
  69304. // DB has been opened successfully
  69305. request.onsuccess = function (event) {
  69306. _this.db = request.result;
  69307. successCallback();
  69308. };
  69309. // Initialization of the DB. Creating Scenes & Textures stores
  69310. request.onupgradeneeded = function (event) {
  69311. _this.db = (event.target).result;
  69312. if (_this.db) {
  69313. try {
  69314. _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  69315. _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  69316. _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  69317. }
  69318. catch (ex) {
  69319. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  69320. handleError();
  69321. }
  69322. }
  69323. };
  69324. }
  69325. // DB has already been created and opened
  69326. else {
  69327. if (successCallback)
  69328. successCallback();
  69329. }
  69330. }
  69331. };
  69332. /**
  69333. * Loads an image from the database
  69334. * @param url defines the url to load from
  69335. * @param image defines the target DOM image
  69336. */
  69337. Database.prototype.loadImageFromDB = function (url, image) {
  69338. var _this = this;
  69339. var completeURL = Database._ReturnFullUrlLocation(url);
  69340. var saveAndLoadImage = function () {
  69341. if (!_this.hasReachedQuota && _this.db !== null) {
  69342. // the texture is not yet in the DB, let's try to save it
  69343. _this._saveImageIntoDBAsync(completeURL, image);
  69344. }
  69345. // If the texture is not in the DB and we've reached the DB quota limit
  69346. // let's load it directly from the web
  69347. else {
  69348. image.src = url;
  69349. }
  69350. };
  69351. if (!this.mustUpdateRessources) {
  69352. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  69353. }
  69354. // First time we're download the images or update requested in the manifest file by a version change
  69355. else {
  69356. saveAndLoadImage();
  69357. }
  69358. };
  69359. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  69360. if (this.isSupported && this.db !== null) {
  69361. var texture;
  69362. var transaction = this.db.transaction(["textures"]);
  69363. transaction.onabort = function (event) {
  69364. image.src = url;
  69365. };
  69366. transaction.oncomplete = function (event) {
  69367. var blobTextureURL;
  69368. if (texture) {
  69369. var URL = window.URL || window.webkitURL;
  69370. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  69371. image.onerror = function () {
  69372. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  69373. image.src = url;
  69374. };
  69375. image.src = blobTextureURL;
  69376. }
  69377. else {
  69378. notInDBCallback();
  69379. }
  69380. };
  69381. var getRequest = transaction.objectStore("textures").get(url);
  69382. getRequest.onsuccess = function (event) {
  69383. texture = (event.target).result;
  69384. };
  69385. getRequest.onerror = function (event) {
  69386. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  69387. image.src = url;
  69388. };
  69389. }
  69390. else {
  69391. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  69392. image.src = url;
  69393. }
  69394. };
  69395. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  69396. var _this = this;
  69397. if (this.isSupported) {
  69398. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  69399. var generateBlobUrl = function () {
  69400. var blobTextureURL;
  69401. if (blob) {
  69402. var URL = window.URL || window.webkitURL;
  69403. try {
  69404. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  69405. }
  69406. // Chrome is raising a type error if we're setting the oneTimeOnly parameter
  69407. catch (ex) {
  69408. blobTextureURL = URL.createObjectURL(blob);
  69409. }
  69410. }
  69411. if (blobTextureURL) {
  69412. image.src = blobTextureURL;
  69413. }
  69414. };
  69415. if (Database.IsUASupportingBlobStorage) { // Create XHR
  69416. var xhr = new XMLHttpRequest(), blob;
  69417. xhr.open("GET", url, true);
  69418. xhr.responseType = "blob";
  69419. xhr.addEventListener("load", function () {
  69420. if (xhr.status === 200 && _this.db) {
  69421. // Blob as response (XHR2)
  69422. blob = xhr.response;
  69423. var transaction = _this.db.transaction(["textures"], "readwrite");
  69424. // the transaction could abort because of a QuotaExceededError error
  69425. transaction.onabort = function (event) {
  69426. try {
  69427. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  69428. var srcElement = (event.srcElement || event.target);
  69429. var error = srcElement.error;
  69430. if (error && error.name === "QuotaExceededError") {
  69431. _this.hasReachedQuota = true;
  69432. }
  69433. }
  69434. catch (ex) { }
  69435. generateBlobUrl();
  69436. };
  69437. transaction.oncomplete = function (event) {
  69438. generateBlobUrl();
  69439. };
  69440. var newTexture = { textureUrl: url, data: blob };
  69441. try {
  69442. // Put the blob into the dabase
  69443. var addRequest = transaction.objectStore("textures").put(newTexture);
  69444. addRequest.onsuccess = function (event) {
  69445. };
  69446. addRequest.onerror = function (event) {
  69447. generateBlobUrl();
  69448. };
  69449. }
  69450. catch (ex) {
  69451. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  69452. if (ex.code === 25) {
  69453. Database.IsUASupportingBlobStorage = false;
  69454. }
  69455. image.src = url;
  69456. }
  69457. }
  69458. else {
  69459. image.src = url;
  69460. }
  69461. }, false);
  69462. xhr.addEventListener("error", function (event) {
  69463. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  69464. image.src = url;
  69465. }, false);
  69466. xhr.send();
  69467. }
  69468. else {
  69469. image.src = url;
  69470. }
  69471. }
  69472. else {
  69473. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  69474. image.src = url;
  69475. }
  69476. };
  69477. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  69478. var _this = this;
  69479. var updateVersion = function () {
  69480. // the version is not yet in the DB or we need to update it
  69481. _this._saveVersionIntoDBAsync(url, versionLoaded);
  69482. };
  69483. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  69484. };
  69485. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  69486. var _this = this;
  69487. if (this.isSupported && this.db) {
  69488. var version;
  69489. try {
  69490. var transaction = this.db.transaction(["versions"]);
  69491. transaction.oncomplete = function (event) {
  69492. if (version) {
  69493. // If the version in the JSON file is different from the version in DB
  69494. if (_this.manifestVersionFound !== version.data) {
  69495. _this.mustUpdateRessources = true;
  69496. updateInDBCallback();
  69497. }
  69498. else {
  69499. callback(version.data);
  69500. }
  69501. }
  69502. // version was not found in DB
  69503. else {
  69504. _this.mustUpdateRessources = true;
  69505. updateInDBCallback();
  69506. }
  69507. };
  69508. transaction.onabort = function (event) {
  69509. callback(-1);
  69510. };
  69511. var getRequest = transaction.objectStore("versions").get(url);
  69512. getRequest.onsuccess = function (event) {
  69513. version = (event.target).result;
  69514. };
  69515. getRequest.onerror = function (event) {
  69516. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  69517. callback(-1);
  69518. };
  69519. }
  69520. catch (ex) {
  69521. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  69522. callback(-1);
  69523. }
  69524. }
  69525. else {
  69526. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  69527. callback(-1);
  69528. }
  69529. };
  69530. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  69531. var _this = this;
  69532. if (this.isSupported && !this.hasReachedQuota && this.db) {
  69533. try {
  69534. // Open a transaction to the database
  69535. var transaction = this.db.transaction(["versions"], "readwrite");
  69536. // the transaction could abort because of a QuotaExceededError error
  69537. transaction.onabort = function (event) {
  69538. try { //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  69539. var error = event.srcElement['error'];
  69540. if (error && error.name === "QuotaExceededError") {
  69541. _this.hasReachedQuota = true;
  69542. }
  69543. }
  69544. catch (ex) { }
  69545. callback(-1);
  69546. };
  69547. transaction.oncomplete = function (event) {
  69548. callback(_this.manifestVersionFound);
  69549. };
  69550. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  69551. // Put the scene into the database
  69552. var addRequest = transaction.objectStore("versions").put(newVersion);
  69553. addRequest.onsuccess = function (event) {
  69554. };
  69555. addRequest.onerror = function (event) {
  69556. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  69557. };
  69558. }
  69559. catch (ex) {
  69560. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  69561. callback(-1);
  69562. }
  69563. }
  69564. else {
  69565. callback(-1);
  69566. }
  69567. };
  69568. /**
  69569. * Loads a file from database
  69570. * @param url defines the URL to load from
  69571. * @param sceneLoaded defines a callback to call on success
  69572. * @param progressCallBack defines a callback to call when progress changed
  69573. * @param errorCallback defines a callback to call on error
  69574. * @param useArrayBuffer defines a boolean to use array buffer instead of text string
  69575. */
  69576. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  69577. var _this = this;
  69578. var completeUrl = Database._ReturnFullUrlLocation(url);
  69579. var saveAndLoadFile = function () {
  69580. // the scene is not yet in the DB, let's try to save it
  69581. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  69582. };
  69583. this._checkVersionFromDB(completeUrl, function (version) {
  69584. if (version !== -1) {
  69585. if (!_this.mustUpdateRessources) {
  69586. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  69587. }
  69588. else {
  69589. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  69590. }
  69591. }
  69592. else {
  69593. if (errorCallback) {
  69594. errorCallback();
  69595. }
  69596. }
  69597. });
  69598. };
  69599. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  69600. if (this.isSupported && this.db) {
  69601. var targetStore;
  69602. if (url.indexOf(".babylon") !== -1) {
  69603. targetStore = "scenes";
  69604. }
  69605. else {
  69606. targetStore = "textures";
  69607. }
  69608. var file;
  69609. var transaction = this.db.transaction([targetStore]);
  69610. transaction.oncomplete = function (event) {
  69611. if (file) {
  69612. callback(file.data);
  69613. }
  69614. // file was not found in DB
  69615. else {
  69616. notInDBCallback();
  69617. }
  69618. };
  69619. transaction.onabort = function (event) {
  69620. notInDBCallback();
  69621. };
  69622. var getRequest = transaction.objectStore(targetStore).get(url);
  69623. getRequest.onsuccess = function (event) {
  69624. file = (event.target).result;
  69625. };
  69626. getRequest.onerror = function (event) {
  69627. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  69628. notInDBCallback();
  69629. };
  69630. }
  69631. else {
  69632. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  69633. callback();
  69634. }
  69635. };
  69636. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
  69637. var _this = this;
  69638. if (this.isSupported) {
  69639. var targetStore;
  69640. if (url.indexOf(".babylon") !== -1) {
  69641. targetStore = "scenes";
  69642. }
  69643. else {
  69644. targetStore = "textures";
  69645. }
  69646. // Create XHR
  69647. var xhr = new XMLHttpRequest();
  69648. var fileData;
  69649. xhr.open("GET", url, true);
  69650. if (useArrayBuffer) {
  69651. xhr.responseType = "arraybuffer";
  69652. }
  69653. if (progressCallback) {
  69654. xhr.onprogress = progressCallback;
  69655. }
  69656. xhr.addEventListener("load", function () {
  69657. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  69658. // Blob as response (XHR2)
  69659. //fileData = xhr.responseText;
  69660. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  69661. if (!_this.hasReachedQuota && _this.db) {
  69662. // Open a transaction to the database
  69663. var transaction = _this.db.transaction([targetStore], "readwrite");
  69664. // the transaction could abort because of a QuotaExceededError error
  69665. transaction.onabort = function (event) {
  69666. try {
  69667. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  69668. var error = event.srcElement['error'];
  69669. if (error && error.name === "QuotaExceededError") {
  69670. _this.hasReachedQuota = true;
  69671. }
  69672. }
  69673. catch (ex) { }
  69674. callback(fileData);
  69675. };
  69676. transaction.oncomplete = function (event) {
  69677. callback(fileData);
  69678. };
  69679. var newFile;
  69680. if (targetStore === "scenes") {
  69681. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  69682. }
  69683. else {
  69684. newFile = { textureUrl: url, data: fileData };
  69685. }
  69686. try {
  69687. // Put the scene into the database
  69688. var addRequest = transaction.objectStore(targetStore).put(newFile);
  69689. addRequest.onsuccess = function (event) {
  69690. };
  69691. addRequest.onerror = function (event) {
  69692. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  69693. };
  69694. }
  69695. catch (ex) {
  69696. callback(fileData);
  69697. }
  69698. }
  69699. else {
  69700. callback(fileData);
  69701. }
  69702. }
  69703. else {
  69704. callback();
  69705. }
  69706. }, false);
  69707. xhr.addEventListener("error", function (event) {
  69708. BABYLON.Tools.Error("error on XHR request.");
  69709. callback();
  69710. }, false);
  69711. xhr.send();
  69712. }
  69713. else {
  69714. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  69715. callback();
  69716. }
  69717. };
  69718. /** Gets a boolean indicating if the user agent supports blob storage (this value will be updated after creating the first Database object) */
  69719. Database.IsUASupportingBlobStorage = true;
  69720. /** Gets a boolean indicating if Database storate is enabled */
  69721. Database.IDBStorageEnabled = true;
  69722. Database._ParseURL = function (url) {
  69723. var a = document.createElement('a');
  69724. a.href = url;
  69725. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  69726. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  69727. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  69728. return absLocation;
  69729. };
  69730. Database._ReturnFullUrlLocation = function (url) {
  69731. if (url.indexOf("http:/") === -1 && url.indexOf("https:/") === -1) {
  69732. return (Database._ParseURL(window.location.href) + url);
  69733. }
  69734. else {
  69735. return url;
  69736. }
  69737. };
  69738. return Database;
  69739. }());
  69740. BABYLON.Database = Database;
  69741. })(BABYLON || (BABYLON = {}));
  69742. //# sourceMappingURL=babylon.database.js.map
  69743. var BABYLON;
  69744. (function (BABYLON) {
  69745. var FresnelParameters = /** @class */ (function () {
  69746. function FresnelParameters() {
  69747. this._isEnabled = true;
  69748. this.leftColor = BABYLON.Color3.White();
  69749. this.rightColor = BABYLON.Color3.Black();
  69750. this.bias = 0;
  69751. this.power = 1;
  69752. }
  69753. Object.defineProperty(FresnelParameters.prototype, "isEnabled", {
  69754. get: function () {
  69755. return this._isEnabled;
  69756. },
  69757. set: function (value) {
  69758. if (this._isEnabled === value) {
  69759. return;
  69760. }
  69761. this._isEnabled = value;
  69762. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  69763. },
  69764. enumerable: true,
  69765. configurable: true
  69766. });
  69767. FresnelParameters.prototype.clone = function () {
  69768. var newFresnelParameters = new FresnelParameters();
  69769. BABYLON.Tools.DeepCopy(this, newFresnelParameters);
  69770. return newFresnelParameters;
  69771. };
  69772. FresnelParameters.prototype.serialize = function () {
  69773. var serializationObject = {};
  69774. serializationObject.isEnabled = this.isEnabled;
  69775. serializationObject.leftColor = this.leftColor.asArray();
  69776. serializationObject.rightColor = this.rightColor.asArray();
  69777. serializationObject.bias = this.bias;
  69778. serializationObject.power = this.power;
  69779. return serializationObject;
  69780. };
  69781. FresnelParameters.Parse = function (parsedFresnelParameters) {
  69782. var fresnelParameters = new FresnelParameters();
  69783. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  69784. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  69785. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  69786. fresnelParameters.bias = parsedFresnelParameters.bias;
  69787. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  69788. return fresnelParameters;
  69789. };
  69790. return FresnelParameters;
  69791. }());
  69792. BABYLON.FresnelParameters = FresnelParameters;
  69793. })(BABYLON || (BABYLON = {}));
  69794. //# sourceMappingURL=babylon.fresnelParameters.js.map
  69795. var BABYLON;
  69796. (function (BABYLON) {
  69797. var MultiMaterial = /** @class */ (function (_super) {
  69798. __extends(MultiMaterial, _super);
  69799. function MultiMaterial(name, scene) {
  69800. var _this = _super.call(this, name, scene, true) || this;
  69801. scene.multiMaterials.push(_this);
  69802. _this.subMaterials = new Array();
  69803. _this.storeEffectOnSubMeshes = true; // multimaterial is considered like a push material
  69804. return _this;
  69805. }
  69806. Object.defineProperty(MultiMaterial.prototype, "subMaterials", {
  69807. get: function () {
  69808. return this._subMaterials;
  69809. },
  69810. set: function (value) {
  69811. this._subMaterials = value;
  69812. this._hookArray(value);
  69813. },
  69814. enumerable: true,
  69815. configurable: true
  69816. });
  69817. MultiMaterial.prototype._hookArray = function (array) {
  69818. var _this = this;
  69819. var oldPush = array.push;
  69820. array.push = function () {
  69821. var items = [];
  69822. for (var _i = 0; _i < arguments.length; _i++) {
  69823. items[_i] = arguments[_i];
  69824. }
  69825. var result = oldPush.apply(array, items);
  69826. _this._markAllSubMeshesAsTexturesDirty();
  69827. return result;
  69828. };
  69829. var oldSplice = array.splice;
  69830. array.splice = function (index, deleteCount) {
  69831. var deleted = oldSplice.apply(array, [index, deleteCount]);
  69832. _this._markAllSubMeshesAsTexturesDirty();
  69833. return deleted;
  69834. };
  69835. };
  69836. // Properties
  69837. MultiMaterial.prototype.getSubMaterial = function (index) {
  69838. if (index < 0 || index >= this.subMaterials.length) {
  69839. return this.getScene().defaultMaterial;
  69840. }
  69841. return this.subMaterials[index];
  69842. };
  69843. MultiMaterial.prototype.getActiveTextures = function () {
  69844. return (_a = _super.prototype.getActiveTextures.call(this)).concat.apply(_a, this.subMaterials.map(function (subMaterial) {
  69845. if (subMaterial) {
  69846. return subMaterial.getActiveTextures();
  69847. }
  69848. else {
  69849. return [];
  69850. }
  69851. }));
  69852. var _a;
  69853. };
  69854. // Methods
  69855. MultiMaterial.prototype.getClassName = function () {
  69856. return "MultiMaterial";
  69857. };
  69858. MultiMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  69859. for (var index = 0; index < this.subMaterials.length; index++) {
  69860. var subMaterial = this.subMaterials[index];
  69861. if (subMaterial) {
  69862. if (subMaterial.storeEffectOnSubMeshes) {
  69863. if (!subMaterial.isReadyForSubMesh(mesh, subMesh, useInstances)) {
  69864. return false;
  69865. }
  69866. continue;
  69867. }
  69868. if (!subMaterial.isReady(mesh)) {
  69869. return false;
  69870. }
  69871. }
  69872. }
  69873. return true;
  69874. };
  69875. MultiMaterial.prototype.clone = function (name, cloneChildren) {
  69876. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  69877. for (var index = 0; index < this.subMaterials.length; index++) {
  69878. var subMaterial = null;
  69879. var current = this.subMaterials[index];
  69880. if (cloneChildren && current) {
  69881. subMaterial = current.clone(name + "-" + current.name);
  69882. }
  69883. else {
  69884. subMaterial = this.subMaterials[index];
  69885. }
  69886. newMultiMaterial.subMaterials.push(subMaterial);
  69887. }
  69888. return newMultiMaterial;
  69889. };
  69890. MultiMaterial.prototype.serialize = function () {
  69891. var serializationObject = {};
  69892. serializationObject.name = this.name;
  69893. serializationObject.id = this.id;
  69894. if (BABYLON.Tags) {
  69895. serializationObject.tags = BABYLON.Tags.GetTags(this);
  69896. }
  69897. serializationObject.materials = [];
  69898. for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
  69899. var subMat = this.subMaterials[matIndex];
  69900. if (subMat) {
  69901. serializationObject.materials.push(subMat.id);
  69902. }
  69903. else {
  69904. serializationObject.materials.push(null);
  69905. }
  69906. }
  69907. return serializationObject;
  69908. };
  69909. MultiMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  69910. var scene = this.getScene();
  69911. if (!scene) {
  69912. return;
  69913. }
  69914. var index = scene.multiMaterials.indexOf(this);
  69915. if (index >= 0) {
  69916. scene.multiMaterials.splice(index, 1);
  69917. }
  69918. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  69919. };
  69920. return MultiMaterial;
  69921. }(BABYLON.Material));
  69922. BABYLON.MultiMaterial = MultiMaterial;
  69923. })(BABYLON || (BABYLON = {}));
  69924. //# sourceMappingURL=babylon.multiMaterial.js.map
  69925. var BABYLON;
  69926. (function (BABYLON) {
  69927. var FreeCameraTouchInput = /** @class */ (function () {
  69928. function FreeCameraTouchInput() {
  69929. this._offsetX = null;
  69930. this._offsetY = null;
  69931. this._pointerPressed = new Array();
  69932. this.touchAngularSensibility = 200000.0;
  69933. this.touchMoveSensibility = 250.0;
  69934. }
  69935. FreeCameraTouchInput.prototype.attachControl = function (element, noPreventDefault) {
  69936. var _this = this;
  69937. var previousPosition = null;
  69938. if (this._pointerInput === undefined) {
  69939. this._onLostFocus = function (evt) {
  69940. _this._offsetX = null;
  69941. _this._offsetY = null;
  69942. };
  69943. this._pointerInput = function (p, s) {
  69944. var evt = p.event;
  69945. if (evt.pointerType === "mouse") {
  69946. return;
  69947. }
  69948. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  69949. if (!noPreventDefault) {
  69950. evt.preventDefault();
  69951. }
  69952. _this._pointerPressed.push(evt.pointerId);
  69953. if (_this._pointerPressed.length !== 1) {
  69954. return;
  69955. }
  69956. previousPosition = {
  69957. x: evt.clientX,
  69958. y: evt.clientY
  69959. };
  69960. }
  69961. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  69962. if (!noPreventDefault) {
  69963. evt.preventDefault();
  69964. }
  69965. var index = _this._pointerPressed.indexOf(evt.pointerId);
  69966. if (index === -1) {
  69967. return;
  69968. }
  69969. _this._pointerPressed.splice(index, 1);
  69970. if (index != 0) {
  69971. return;
  69972. }
  69973. previousPosition = null;
  69974. _this._offsetX = null;
  69975. _this._offsetY = null;
  69976. }
  69977. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  69978. if (!noPreventDefault) {
  69979. evt.preventDefault();
  69980. }
  69981. if (!previousPosition) {
  69982. return;
  69983. }
  69984. var index = _this._pointerPressed.indexOf(evt.pointerId);
  69985. if (index != 0) {
  69986. return;
  69987. }
  69988. _this._offsetX = evt.clientX - previousPosition.x;
  69989. _this._offsetY = -(evt.clientY - previousPosition.y);
  69990. }
  69991. };
  69992. }
  69993. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  69994. if (this._onLostFocus) {
  69995. element.addEventListener("blur", this._onLostFocus);
  69996. }
  69997. };
  69998. FreeCameraTouchInput.prototype.detachControl = function (element) {
  69999. if (this._pointerInput && element) {
  70000. if (this._observer) {
  70001. this.camera.getScene().onPointerObservable.remove(this._observer);
  70002. this._observer = null;
  70003. }
  70004. if (this._onLostFocus) {
  70005. element.removeEventListener("blur", this._onLostFocus);
  70006. this._onLostFocus = null;
  70007. }
  70008. this._pointerPressed = [];
  70009. this._offsetX = null;
  70010. this._offsetY = null;
  70011. }
  70012. };
  70013. FreeCameraTouchInput.prototype.checkInputs = function () {
  70014. if (this._offsetX && this._offsetY) {
  70015. var camera = this.camera;
  70016. camera.cameraRotation.y += this._offsetX / this.touchAngularSensibility;
  70017. if (this._pointerPressed.length > 1) {
  70018. camera.cameraRotation.x += -this._offsetY / this.touchAngularSensibility;
  70019. }
  70020. else {
  70021. var speed = camera._computeLocalCameraSpeed();
  70022. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.touchMoveSensibility);
  70023. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, camera._cameraRotationMatrix);
  70024. camera.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, camera._cameraRotationMatrix));
  70025. }
  70026. }
  70027. };
  70028. FreeCameraTouchInput.prototype.getClassName = function () {
  70029. return "FreeCameraTouchInput";
  70030. };
  70031. FreeCameraTouchInput.prototype.getSimpleName = function () {
  70032. return "touch";
  70033. };
  70034. __decorate([
  70035. BABYLON.serialize()
  70036. ], FreeCameraTouchInput.prototype, "touchAngularSensibility", void 0);
  70037. __decorate([
  70038. BABYLON.serialize()
  70039. ], FreeCameraTouchInput.prototype, "touchMoveSensibility", void 0);
  70040. return FreeCameraTouchInput;
  70041. }());
  70042. BABYLON.FreeCameraTouchInput = FreeCameraTouchInput;
  70043. BABYLON.CameraInputTypes["FreeCameraTouchInput"] = FreeCameraTouchInput;
  70044. })(BABYLON || (BABYLON = {}));
  70045. //# sourceMappingURL=babylon.freeCameraTouchInput.js.map
  70046. var BABYLON;
  70047. (function (BABYLON) {
  70048. // We're mainly based on the logic defined into the FreeCamera code
  70049. var TouchCamera = /** @class */ (function (_super) {
  70050. __extends(TouchCamera, _super);
  70051. //-- end properties for backward compatibility for inputs
  70052. function TouchCamera(name, position, scene) {
  70053. var _this = _super.call(this, name, position, scene) || this;
  70054. _this.inputs.addTouch();
  70055. _this._setupInputs();
  70056. return _this;
  70057. }
  70058. Object.defineProperty(TouchCamera.prototype, "touchAngularSensibility", {
  70059. //-- Begin properties for backward compatibility for inputs
  70060. get: function () {
  70061. var touch = this.inputs.attached["touch"];
  70062. if (touch)
  70063. return touch.touchAngularSensibility;
  70064. return 0;
  70065. },
  70066. set: function (value) {
  70067. var touch = this.inputs.attached["touch"];
  70068. if (touch)
  70069. touch.touchAngularSensibility = value;
  70070. },
  70071. enumerable: true,
  70072. configurable: true
  70073. });
  70074. Object.defineProperty(TouchCamera.prototype, "touchMoveSensibility", {
  70075. get: function () {
  70076. var touch = this.inputs.attached["touch"];
  70077. if (touch)
  70078. return touch.touchMoveSensibility;
  70079. return 0;
  70080. },
  70081. set: function (value) {
  70082. var touch = this.inputs.attached["touch"];
  70083. if (touch)
  70084. touch.touchMoveSensibility = value;
  70085. },
  70086. enumerable: true,
  70087. configurable: true
  70088. });
  70089. TouchCamera.prototype.getClassName = function () {
  70090. return "TouchCamera";
  70091. };
  70092. TouchCamera.prototype._setupInputs = function () {
  70093. var mouse = this.inputs.attached["mouse"];
  70094. if (mouse) {
  70095. mouse.touchEnabled = false;
  70096. }
  70097. };
  70098. return TouchCamera;
  70099. }(BABYLON.FreeCamera));
  70100. BABYLON.TouchCamera = TouchCamera;
  70101. })(BABYLON || (BABYLON = {}));
  70102. //# sourceMappingURL=babylon.touchCamera.js.map
  70103. var BABYLON;
  70104. (function (BABYLON) {
  70105. var ProceduralTexture = /** @class */ (function (_super) {
  70106. __extends(ProceduralTexture, _super);
  70107. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps, isCube) {
  70108. if (fallbackTexture === void 0) { fallbackTexture = null; }
  70109. if (generateMipMaps === void 0) { generateMipMaps = true; }
  70110. if (isCube === void 0) { isCube = false; }
  70111. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  70112. _this.isCube = isCube;
  70113. _this.isEnabled = true;
  70114. _this._currentRefreshId = -1;
  70115. _this._refreshRate = 1;
  70116. _this._vertexBuffers = {};
  70117. _this._uniforms = new Array();
  70118. _this._samplers = new Array();
  70119. _this._textures = {};
  70120. _this._floats = {};
  70121. _this._floatsArrays = {};
  70122. _this._colors3 = {};
  70123. _this._colors4 = {};
  70124. _this._vectors2 = {};
  70125. _this._vectors3 = {};
  70126. _this._matrices = {};
  70127. _this._fallbackTextureUsed = false;
  70128. scene.proceduralTextures.push(_this);
  70129. _this._engine = scene.getEngine();
  70130. _this.name = name;
  70131. _this.isRenderTarget = true;
  70132. _this._size = size;
  70133. _this._generateMipMaps = generateMipMaps;
  70134. _this.setFragment(fragment);
  70135. _this._fallbackTexture = fallbackTexture;
  70136. if (isCube) {
  70137. _this._texture = _this._engine.createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  70138. _this.setFloat("face", 0);
  70139. }
  70140. else {
  70141. _this._texture = _this._engine.createRenderTargetTexture(size, generateMipMaps);
  70142. }
  70143. // VBO
  70144. var vertices = [];
  70145. vertices.push(1, 1);
  70146. vertices.push(-1, 1);
  70147. vertices.push(-1, -1);
  70148. vertices.push(1, -1);
  70149. _this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(_this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  70150. _this._createIndexBuffer();
  70151. return _this;
  70152. }
  70153. ProceduralTexture.prototype._createIndexBuffer = function () {
  70154. var engine = this._engine;
  70155. // Indices
  70156. var indices = [];
  70157. indices.push(0);
  70158. indices.push(1);
  70159. indices.push(2);
  70160. indices.push(0);
  70161. indices.push(2);
  70162. indices.push(3);
  70163. this._indexBuffer = engine.createIndexBuffer(indices);
  70164. };
  70165. ProceduralTexture.prototype._rebuild = function () {
  70166. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  70167. if (vb) {
  70168. vb._rebuild();
  70169. }
  70170. this._createIndexBuffer();
  70171. if (this.refreshRate === BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  70172. this.refreshRate = BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  70173. }
  70174. };
  70175. ProceduralTexture.prototype.reset = function () {
  70176. if (this._effect === undefined) {
  70177. return;
  70178. }
  70179. var engine = this._engine;
  70180. engine._releaseEffect(this._effect);
  70181. };
  70182. ProceduralTexture.prototype.isReady = function () {
  70183. var _this = this;
  70184. var engine = this._engine;
  70185. var shaders;
  70186. if (!this._fragment) {
  70187. return false;
  70188. }
  70189. if (this._fallbackTextureUsed) {
  70190. return true;
  70191. }
  70192. if (this._fragment.fragmentElement !== undefined) {
  70193. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  70194. }
  70195. else {
  70196. shaders = { vertex: "procedural", fragment: this._fragment };
  70197. }
  70198. this._effect = engine.createEffect(shaders, [BABYLON.VertexBuffer.PositionKind], this._uniforms, this._samplers, "", undefined, undefined, function () {
  70199. _this.releaseInternalTexture();
  70200. if (_this._fallbackTexture) {
  70201. _this._texture = _this._fallbackTexture._texture;
  70202. if (_this._texture) {
  70203. _this._texture.incrementReferences();
  70204. }
  70205. }
  70206. _this._fallbackTextureUsed = true;
  70207. });
  70208. return this._effect.isReady();
  70209. };
  70210. ProceduralTexture.prototype.resetRefreshCounter = function () {
  70211. this._currentRefreshId = -1;
  70212. };
  70213. ProceduralTexture.prototype.setFragment = function (fragment) {
  70214. this._fragment = fragment;
  70215. };
  70216. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  70217. get: function () {
  70218. return this._refreshRate;
  70219. },
  70220. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  70221. set: function (value) {
  70222. this._refreshRate = value;
  70223. this.resetRefreshCounter();
  70224. },
  70225. enumerable: true,
  70226. configurable: true
  70227. });
  70228. ProceduralTexture.prototype._shouldRender = function () {
  70229. if (!this.isEnabled || !this.isReady() || !this._texture) {
  70230. return false;
  70231. }
  70232. if (this._fallbackTextureUsed) {
  70233. return false;
  70234. }
  70235. if (this._currentRefreshId === -1) { // At least render once
  70236. this._currentRefreshId = 1;
  70237. return true;
  70238. }
  70239. if (this.refreshRate === this._currentRefreshId) {
  70240. this._currentRefreshId = 1;
  70241. return true;
  70242. }
  70243. this._currentRefreshId++;
  70244. return false;
  70245. };
  70246. ProceduralTexture.prototype.getRenderSize = function () {
  70247. return this._size;
  70248. };
  70249. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  70250. if (this._fallbackTextureUsed) {
  70251. return;
  70252. }
  70253. this.releaseInternalTexture();
  70254. this._texture = this._engine.createRenderTargetTexture(size, generateMipMaps);
  70255. };
  70256. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  70257. if (this._uniforms.indexOf(uniformName) === -1) {
  70258. this._uniforms.push(uniformName);
  70259. }
  70260. };
  70261. ProceduralTexture.prototype.setTexture = function (name, texture) {
  70262. if (this._samplers.indexOf(name) === -1) {
  70263. this._samplers.push(name);
  70264. }
  70265. this._textures[name] = texture;
  70266. return this;
  70267. };
  70268. ProceduralTexture.prototype.setFloat = function (name, value) {
  70269. this._checkUniform(name);
  70270. this._floats[name] = value;
  70271. return this;
  70272. };
  70273. ProceduralTexture.prototype.setFloats = function (name, value) {
  70274. this._checkUniform(name);
  70275. this._floatsArrays[name] = value;
  70276. return this;
  70277. };
  70278. ProceduralTexture.prototype.setColor3 = function (name, value) {
  70279. this._checkUniform(name);
  70280. this._colors3[name] = value;
  70281. return this;
  70282. };
  70283. ProceduralTexture.prototype.setColor4 = function (name, value) {
  70284. this._checkUniform(name);
  70285. this._colors4[name] = value;
  70286. return this;
  70287. };
  70288. ProceduralTexture.prototype.setVector2 = function (name, value) {
  70289. this._checkUniform(name);
  70290. this._vectors2[name] = value;
  70291. return this;
  70292. };
  70293. ProceduralTexture.prototype.setVector3 = function (name, value) {
  70294. this._checkUniform(name);
  70295. this._vectors3[name] = value;
  70296. return this;
  70297. };
  70298. ProceduralTexture.prototype.setMatrix = function (name, value) {
  70299. this._checkUniform(name);
  70300. this._matrices[name] = value;
  70301. return this;
  70302. };
  70303. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  70304. var scene = this.getScene();
  70305. if (!scene) {
  70306. return;
  70307. }
  70308. var engine = this._engine;
  70309. // Render
  70310. engine.enableEffect(this._effect);
  70311. engine.setState(false);
  70312. // Texture
  70313. for (var name in this._textures) {
  70314. this._effect.setTexture(name, this._textures[name]);
  70315. }
  70316. // Float
  70317. for (name in this._floats) {
  70318. this._effect.setFloat(name, this._floats[name]);
  70319. }
  70320. // Floats
  70321. for (name in this._floatsArrays) {
  70322. this._effect.setArray(name, this._floatsArrays[name]);
  70323. }
  70324. // Color3
  70325. for (name in this._colors3) {
  70326. this._effect.setColor3(name, this._colors3[name]);
  70327. }
  70328. // Color4
  70329. for (name in this._colors4) {
  70330. var color = this._colors4[name];
  70331. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  70332. }
  70333. // Vector2
  70334. for (name in this._vectors2) {
  70335. this._effect.setVector2(name, this._vectors2[name]);
  70336. }
  70337. // Vector3
  70338. for (name in this._vectors3) {
  70339. this._effect.setVector3(name, this._vectors3[name]);
  70340. }
  70341. // Matrix
  70342. for (name in this._matrices) {
  70343. this._effect.setMatrix(name, this._matrices[name]);
  70344. }
  70345. if (!this._texture) {
  70346. return;
  70347. }
  70348. if (this.isCube) {
  70349. for (var face = 0; face < 6; face++) {
  70350. engine.bindFramebuffer(this._texture, face, undefined, undefined, true);
  70351. // VBOs
  70352. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  70353. this._effect.setFloat("face", face);
  70354. // Clear
  70355. engine.clear(scene.clearColor, true, true, true);
  70356. // Draw order
  70357. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  70358. // Mipmaps
  70359. if (face === 5) {
  70360. engine.generateMipMapsForCubemap(this._texture);
  70361. }
  70362. }
  70363. }
  70364. else {
  70365. engine.bindFramebuffer(this._texture, 0, undefined, undefined, true);
  70366. // VBOs
  70367. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  70368. // Clear
  70369. engine.clear(scene.clearColor, true, true, true);
  70370. // Draw order
  70371. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  70372. }
  70373. // Unbind
  70374. engine.unBindFramebuffer(this._texture, this.isCube);
  70375. if (this.onGenerated) {
  70376. this.onGenerated();
  70377. }
  70378. };
  70379. ProceduralTexture.prototype.clone = function () {
  70380. var textureSize = this.getSize();
  70381. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  70382. // Base texture
  70383. newTexture.hasAlpha = this.hasAlpha;
  70384. newTexture.level = this.level;
  70385. // RenderTarget Texture
  70386. newTexture.coordinatesMode = this.coordinatesMode;
  70387. return newTexture;
  70388. };
  70389. ProceduralTexture.prototype.dispose = function () {
  70390. var scene = this.getScene();
  70391. if (!scene) {
  70392. return;
  70393. }
  70394. var index = scene.proceduralTextures.indexOf(this);
  70395. if (index >= 0) {
  70396. scene.proceduralTextures.splice(index, 1);
  70397. }
  70398. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  70399. if (vertexBuffer) {
  70400. vertexBuffer.dispose();
  70401. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  70402. }
  70403. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  70404. this._indexBuffer = null;
  70405. }
  70406. _super.prototype.dispose.call(this);
  70407. };
  70408. return ProceduralTexture;
  70409. }(BABYLON.Texture));
  70410. BABYLON.ProceduralTexture = ProceduralTexture;
  70411. })(BABYLON || (BABYLON = {}));
  70412. //# sourceMappingURL=babylon.proceduralTexture.js.map
  70413. var BABYLON;
  70414. (function (BABYLON) {
  70415. var CustomProceduralTexture = /** @class */ (function (_super) {
  70416. __extends(CustomProceduralTexture, _super);
  70417. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  70418. var _this = _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps) || this;
  70419. _this._animate = true;
  70420. _this._time = 0;
  70421. _this._texturePath = texturePath;
  70422. //Try to load json
  70423. _this.loadJson(texturePath);
  70424. _this.refreshRate = 1;
  70425. return _this;
  70426. }
  70427. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  70428. var _this = this;
  70429. var noConfigFile = function () {
  70430. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  70431. try {
  70432. _this.setFragment(_this._texturePath);
  70433. }
  70434. catch (ex) {
  70435. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  70436. }
  70437. };
  70438. var configFileUrl = jsonUrl + "/config.json";
  70439. var xhr = new XMLHttpRequest();
  70440. xhr.open("GET", configFileUrl, true);
  70441. xhr.addEventListener("load", function () {
  70442. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  70443. try {
  70444. _this._config = JSON.parse(xhr.response);
  70445. _this.updateShaderUniforms();
  70446. _this.updateTextures();
  70447. _this.setFragment(_this._texturePath + "/custom");
  70448. _this._animate = _this._config.animate;
  70449. _this.refreshRate = _this._config.refreshrate;
  70450. }
  70451. catch (ex) {
  70452. noConfigFile();
  70453. }
  70454. }
  70455. else {
  70456. noConfigFile();
  70457. }
  70458. }, false);
  70459. xhr.addEventListener("error", function () {
  70460. noConfigFile();
  70461. }, false);
  70462. try {
  70463. xhr.send();
  70464. }
  70465. catch (ex) {
  70466. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  70467. }
  70468. };
  70469. CustomProceduralTexture.prototype.isReady = function () {
  70470. if (!_super.prototype.isReady.call(this)) {
  70471. return false;
  70472. }
  70473. for (var name in this._textures) {
  70474. var texture = this._textures[name];
  70475. if (!texture.isReady()) {
  70476. return false;
  70477. }
  70478. }
  70479. return true;
  70480. };
  70481. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  70482. var scene = this.getScene();
  70483. if (this._animate && scene) {
  70484. this._time += scene.getAnimationRatio() * 0.03;
  70485. this.updateShaderUniforms();
  70486. }
  70487. _super.prototype.render.call(this, useCameraPostProcess);
  70488. };
  70489. CustomProceduralTexture.prototype.updateTextures = function () {
  70490. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  70491. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  70492. }
  70493. };
  70494. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  70495. if (this._config) {
  70496. for (var j = 0; j < this._config.uniforms.length; j++) {
  70497. var uniform = this._config.uniforms[j];
  70498. switch (uniform.type) {
  70499. case "float":
  70500. this.setFloat(uniform.name, uniform.value);
  70501. break;
  70502. case "color3":
  70503. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  70504. break;
  70505. case "color4":
  70506. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  70507. break;
  70508. case "vector2":
  70509. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  70510. break;
  70511. case "vector3":
  70512. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  70513. break;
  70514. }
  70515. }
  70516. }
  70517. this.setFloat("time", this._time);
  70518. };
  70519. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  70520. get: function () {
  70521. return this._animate;
  70522. },
  70523. set: function (value) {
  70524. this._animate = value;
  70525. },
  70526. enumerable: true,
  70527. configurable: true
  70528. });
  70529. return CustomProceduralTexture;
  70530. }(BABYLON.ProceduralTexture));
  70531. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  70532. })(BABYLON || (BABYLON = {}));
  70533. //# sourceMappingURL=babylon.customProceduralTexture.js.map
  70534. var BABYLON;
  70535. (function (BABYLON) {
  70536. var FreeCameraGamepadInput = /** @class */ (function () {
  70537. function FreeCameraGamepadInput() {
  70538. this.gamepadAngularSensibility = 200;
  70539. this.gamepadMoveSensibility = 40;
  70540. // private members
  70541. this._cameraTransform = BABYLON.Matrix.Identity();
  70542. this._deltaTransform = BABYLON.Vector3.Zero();
  70543. this._vector3 = BABYLON.Vector3.Zero();
  70544. this._vector2 = BABYLON.Vector2.Zero();
  70545. }
  70546. FreeCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  70547. var _this = this;
  70548. var manager = this.camera.getScene().gamepadManager;
  70549. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  70550. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  70551. // prioritize XBOX gamepads.
  70552. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  70553. _this.gamepad = gamepad;
  70554. }
  70555. }
  70556. });
  70557. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  70558. if (_this.gamepad === gamepad) {
  70559. _this.gamepad = null;
  70560. }
  70561. });
  70562. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  70563. };
  70564. FreeCameraGamepadInput.prototype.detachControl = function (element) {
  70565. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  70566. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  70567. this.gamepad = null;
  70568. };
  70569. FreeCameraGamepadInput.prototype.checkInputs = function () {
  70570. if (this.gamepad && this.gamepad.leftStick) {
  70571. var camera = this.camera;
  70572. var LSValues = this.gamepad.leftStick;
  70573. var normalizedLX = LSValues.x / this.gamepadMoveSensibility;
  70574. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  70575. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  70576. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  70577. var RSValues = this.gamepad.rightStick;
  70578. if (RSValues) {
  70579. var normalizedRX = RSValues.x / this.gamepadAngularSensibility;
  70580. var normalizedRY = RSValues.y / this.gamepadAngularSensibility;
  70581. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  70582. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  70583. }
  70584. else {
  70585. RSValues = { x: 0, y: 0 };
  70586. }
  70587. if (!camera.rotationQuaternion) {
  70588. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, this._cameraTransform);
  70589. }
  70590. else {
  70591. camera.rotationQuaternion.toRotationMatrix(this._cameraTransform);
  70592. }
  70593. var speed = camera._computeLocalCameraSpeed() * 50.0;
  70594. this._vector3.copyFromFloats(LSValues.x * speed, 0, -LSValues.y * speed);
  70595. BABYLON.Vector3.TransformCoordinatesToRef(this._vector3, this._cameraTransform, this._deltaTransform);
  70596. camera.cameraDirection.addInPlace(this._deltaTransform);
  70597. this._vector2.copyFromFloats(RSValues.y, RSValues.x);
  70598. camera.cameraRotation.addInPlace(this._vector2);
  70599. }
  70600. };
  70601. FreeCameraGamepadInput.prototype.getClassName = function () {
  70602. return "FreeCameraGamepadInput";
  70603. };
  70604. FreeCameraGamepadInput.prototype.getSimpleName = function () {
  70605. return "gamepad";
  70606. };
  70607. __decorate([
  70608. BABYLON.serialize()
  70609. ], FreeCameraGamepadInput.prototype, "gamepadAngularSensibility", void 0);
  70610. __decorate([
  70611. BABYLON.serialize()
  70612. ], FreeCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  70613. return FreeCameraGamepadInput;
  70614. }());
  70615. BABYLON.FreeCameraGamepadInput = FreeCameraGamepadInput;
  70616. BABYLON.CameraInputTypes["FreeCameraGamepadInput"] = FreeCameraGamepadInput;
  70617. })(BABYLON || (BABYLON = {}));
  70618. //# sourceMappingURL=babylon.freeCameraGamepadInput.js.map
  70619. var BABYLON;
  70620. (function (BABYLON) {
  70621. var ArcRotateCameraGamepadInput = /** @class */ (function () {
  70622. function ArcRotateCameraGamepadInput() {
  70623. this.gamepadRotationSensibility = 80;
  70624. this.gamepadMoveSensibility = 40;
  70625. }
  70626. ArcRotateCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  70627. var _this = this;
  70628. var manager = this.camera.getScene().gamepadManager;
  70629. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  70630. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  70631. // prioritize XBOX gamepads.
  70632. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  70633. _this.gamepad = gamepad;
  70634. }
  70635. }
  70636. });
  70637. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  70638. if (_this.gamepad === gamepad) {
  70639. _this.gamepad = null;
  70640. }
  70641. });
  70642. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  70643. };
  70644. ArcRotateCameraGamepadInput.prototype.detachControl = function (element) {
  70645. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  70646. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  70647. this.gamepad = null;
  70648. };
  70649. ArcRotateCameraGamepadInput.prototype.checkInputs = function () {
  70650. if (this.gamepad) {
  70651. var camera = this.camera;
  70652. var RSValues = this.gamepad.rightStick;
  70653. if (RSValues) {
  70654. if (RSValues.x != 0) {
  70655. var normalizedRX = RSValues.x / this.gamepadRotationSensibility;
  70656. if (normalizedRX != 0 && Math.abs(normalizedRX) > 0.005) {
  70657. camera.inertialAlphaOffset += normalizedRX;
  70658. }
  70659. }
  70660. if (RSValues.y != 0) {
  70661. var normalizedRY = RSValues.y / this.gamepadRotationSensibility;
  70662. if (normalizedRY != 0 && Math.abs(normalizedRY) > 0.005) {
  70663. camera.inertialBetaOffset += normalizedRY;
  70664. }
  70665. }
  70666. }
  70667. var LSValues = this.gamepad.leftStick;
  70668. if (LSValues && LSValues.y != 0) {
  70669. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  70670. if (normalizedLY != 0 && Math.abs(normalizedLY) > 0.005) {
  70671. this.camera.inertialRadiusOffset -= normalizedLY;
  70672. }
  70673. }
  70674. }
  70675. };
  70676. ArcRotateCameraGamepadInput.prototype.getClassName = function () {
  70677. return "ArcRotateCameraGamepadInput";
  70678. };
  70679. ArcRotateCameraGamepadInput.prototype.getSimpleName = function () {
  70680. return "gamepad";
  70681. };
  70682. __decorate([
  70683. BABYLON.serialize()
  70684. ], ArcRotateCameraGamepadInput.prototype, "gamepadRotationSensibility", void 0);
  70685. __decorate([
  70686. BABYLON.serialize()
  70687. ], ArcRotateCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  70688. return ArcRotateCameraGamepadInput;
  70689. }());
  70690. BABYLON.ArcRotateCameraGamepadInput = ArcRotateCameraGamepadInput;
  70691. BABYLON.CameraInputTypes["ArcRotateCameraGamepadInput"] = ArcRotateCameraGamepadInput;
  70692. })(BABYLON || (BABYLON = {}));
  70693. //# sourceMappingURL=babylon.arcRotateCameraGamepadInput.js.map
  70694. var BABYLON;
  70695. (function (BABYLON) {
  70696. var GamepadManager = /** @class */ (function () {
  70697. function GamepadManager(_scene) {
  70698. var _this = this;
  70699. this._scene = _scene;
  70700. this._babylonGamepads = [];
  70701. this._oneGamepadConnected = false;
  70702. this._isMonitoring = false;
  70703. this.onGamepadDisconnectedObservable = new BABYLON.Observable();
  70704. if (!BABYLON.Tools.IsWindowObjectExist()) {
  70705. this._gamepadEventSupported = false;
  70706. }
  70707. else {
  70708. this._gamepadEventSupported = 'GamepadEvent' in window;
  70709. this._gamepadSupport = (navigator.getGamepads ||
  70710. navigator.webkitGetGamepads || navigator.msGetGamepads || navigator.webkitGamepads);
  70711. }
  70712. this.onGamepadConnectedObservable = new BABYLON.Observable(function (observer) {
  70713. // This will be used to raise the onGamepadConnected for all gamepads ALREADY connected
  70714. for (var i in _this._babylonGamepads) {
  70715. var gamepad = _this._babylonGamepads[i];
  70716. if (gamepad && gamepad._isConnected) {
  70717. _this.onGamepadConnectedObservable.notifyObserver(observer, gamepad);
  70718. }
  70719. }
  70720. });
  70721. this._onGamepadConnectedEvent = function (evt) {
  70722. var gamepad = evt.gamepad;
  70723. if (gamepad.index in _this._babylonGamepads) {
  70724. if (_this._babylonGamepads[gamepad.index].isConnected) {
  70725. return;
  70726. }
  70727. }
  70728. var newGamepad;
  70729. if (_this._babylonGamepads[gamepad.index]) {
  70730. newGamepad = _this._babylonGamepads[gamepad.index];
  70731. newGamepad.browserGamepad = gamepad;
  70732. newGamepad._isConnected = true;
  70733. }
  70734. else {
  70735. newGamepad = _this._addNewGamepad(gamepad);
  70736. }
  70737. _this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  70738. _this._startMonitoringGamepads();
  70739. };
  70740. this._onGamepadDisconnectedEvent = function (evt) {
  70741. var gamepad = evt.gamepad;
  70742. // Remove the gamepad from the list of gamepads to monitor.
  70743. for (var i in _this._babylonGamepads) {
  70744. if (_this._babylonGamepads[i].index === gamepad.index) {
  70745. var disconnectedGamepad = _this._babylonGamepads[i];
  70746. disconnectedGamepad._isConnected = false;
  70747. _this.onGamepadDisconnectedObservable.notifyObservers(disconnectedGamepad);
  70748. break;
  70749. }
  70750. }
  70751. };
  70752. if (this._gamepadSupport) {
  70753. //first add already-connected gamepads
  70754. this._updateGamepadObjects();
  70755. if (this._babylonGamepads.length) {
  70756. this._startMonitoringGamepads();
  70757. }
  70758. // Checking if the gamepad connected event is supported (like in Firefox)
  70759. if (this._gamepadEventSupported) {
  70760. window.addEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  70761. window.addEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent, false);
  70762. }
  70763. else {
  70764. this._startMonitoringGamepads();
  70765. }
  70766. }
  70767. }
  70768. Object.defineProperty(GamepadManager.prototype, "gamepads", {
  70769. get: function () {
  70770. return this._babylonGamepads;
  70771. },
  70772. enumerable: true,
  70773. configurable: true
  70774. });
  70775. GamepadManager.prototype.getGamepadByType = function (type) {
  70776. if (type === void 0) { type = BABYLON.Gamepad.XBOX; }
  70777. for (var _i = 0, _a = this._babylonGamepads; _i < _a.length; _i++) {
  70778. var gamepad = _a[_i];
  70779. if (gamepad && gamepad.type === type) {
  70780. return gamepad;
  70781. }
  70782. }
  70783. return null;
  70784. };
  70785. GamepadManager.prototype.dispose = function () {
  70786. if (this._gamepadEventSupported) {
  70787. if (this._onGamepadConnectedEvent) {
  70788. window.removeEventListener('gamepadconnected', this._onGamepadConnectedEvent);
  70789. }
  70790. if (this._onGamepadDisconnectedEvent) {
  70791. window.removeEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent);
  70792. }
  70793. this._onGamepadConnectedEvent = null;
  70794. this._onGamepadDisconnectedEvent = null;
  70795. }
  70796. this._babylonGamepads.forEach(function (gamepad) {
  70797. gamepad.dispose();
  70798. });
  70799. this.onGamepadConnectedObservable.clear();
  70800. this.onGamepadDisconnectedObservable.clear();
  70801. this._oneGamepadConnected = false;
  70802. this._stopMonitoringGamepads();
  70803. this._babylonGamepads = [];
  70804. };
  70805. GamepadManager.prototype._addNewGamepad = function (gamepad) {
  70806. if (!this._oneGamepadConnected) {
  70807. this._oneGamepadConnected = true;
  70808. }
  70809. var newGamepad;
  70810. var xboxOne = (gamepad.id.search("Xbox One") !== -1);
  70811. if (xboxOne || gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  70812. newGamepad = new BABYLON.Xbox360Pad(gamepad.id, gamepad.index, gamepad, xboxOne);
  70813. }
  70814. // if pose is supported, use the (WebVR) pose enabled controller
  70815. else if (gamepad.pose) {
  70816. newGamepad = BABYLON.PoseEnabledControllerHelper.InitiateController(gamepad);
  70817. }
  70818. else {
  70819. newGamepad = new BABYLON.GenericPad(gamepad.id, gamepad.index, gamepad);
  70820. }
  70821. this._babylonGamepads[newGamepad.index] = newGamepad;
  70822. return newGamepad;
  70823. };
  70824. GamepadManager.prototype._startMonitoringGamepads = function () {
  70825. if (!this._isMonitoring) {
  70826. this._isMonitoring = true;
  70827. //back-comp
  70828. if (!this._scene) {
  70829. this._checkGamepadsStatus();
  70830. }
  70831. }
  70832. };
  70833. GamepadManager.prototype._stopMonitoringGamepads = function () {
  70834. this._isMonitoring = false;
  70835. };
  70836. GamepadManager.prototype._checkGamepadsStatus = function () {
  70837. var _this = this;
  70838. // Hack to be compatible Chrome
  70839. this._updateGamepadObjects();
  70840. for (var i in this._babylonGamepads) {
  70841. var gamepad = this._babylonGamepads[i];
  70842. if (!gamepad || !gamepad.isConnected) {
  70843. continue;
  70844. }
  70845. gamepad.update();
  70846. }
  70847. if (this._isMonitoring && !this._scene) {
  70848. BABYLON.Tools.QueueNewFrame(function () { _this._checkGamepadsStatus(); });
  70849. }
  70850. };
  70851. // This function is called only on Chrome, which does not properly support
  70852. // connection/disconnection events and forces you to recopy again the gamepad object
  70853. GamepadManager.prototype._updateGamepadObjects = function () {
  70854. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  70855. for (var i = 0; i < gamepads.length; i++) {
  70856. var gamepad = gamepads[i];
  70857. if (gamepad) {
  70858. if (!this._babylonGamepads[gamepad.index]) {
  70859. var newGamepad = this._addNewGamepad(gamepad);
  70860. this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  70861. }
  70862. else {
  70863. // Forced to copy again this object for Chrome for unknown reason
  70864. this._babylonGamepads[i].browserGamepad = gamepad;
  70865. if (!this._babylonGamepads[i].isConnected) {
  70866. this._babylonGamepads[i]._isConnected = true;
  70867. this.onGamepadConnectedObservable.notifyObservers(this._babylonGamepads[i]);
  70868. }
  70869. }
  70870. }
  70871. }
  70872. };
  70873. return GamepadManager;
  70874. }());
  70875. BABYLON.GamepadManager = GamepadManager;
  70876. })(BABYLON || (BABYLON = {}));
  70877. //# sourceMappingURL=babylon.gamepadManager.js.map
  70878. var BABYLON;
  70879. (function (BABYLON) {
  70880. var StickValues = /** @class */ (function () {
  70881. function StickValues(x, y) {
  70882. this.x = x;
  70883. this.y = y;
  70884. }
  70885. return StickValues;
  70886. }());
  70887. BABYLON.StickValues = StickValues;
  70888. var Gamepad = /** @class */ (function () {
  70889. function Gamepad(id, index, browserGamepad, leftStickX, leftStickY, rightStickX, rightStickY) {
  70890. if (leftStickX === void 0) { leftStickX = 0; }
  70891. if (leftStickY === void 0) { leftStickY = 1; }
  70892. if (rightStickX === void 0) { rightStickX = 2; }
  70893. if (rightStickY === void 0) { rightStickY = 3; }
  70894. this.id = id;
  70895. this.index = index;
  70896. this.browserGamepad = browserGamepad;
  70897. this._isConnected = true;
  70898. this._invertLeftStickY = false;
  70899. this.type = Gamepad.GAMEPAD;
  70900. this._leftStickAxisX = leftStickX;
  70901. this._leftStickAxisY = leftStickY;
  70902. this._rightStickAxisX = rightStickX;
  70903. this._rightStickAxisY = rightStickY;
  70904. if (this.browserGamepad.axes.length >= 2) {
  70905. this._leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  70906. }
  70907. if (this.browserGamepad.axes.length >= 4) {
  70908. this._rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  70909. }
  70910. }
  70911. Object.defineProperty(Gamepad.prototype, "isConnected", {
  70912. get: function () {
  70913. return this._isConnected;
  70914. },
  70915. enumerable: true,
  70916. configurable: true
  70917. });
  70918. Gamepad.prototype.onleftstickchanged = function (callback) {
  70919. this._onleftstickchanged = callback;
  70920. };
  70921. Gamepad.prototype.onrightstickchanged = function (callback) {
  70922. this._onrightstickchanged = callback;
  70923. };
  70924. Object.defineProperty(Gamepad.prototype, "leftStick", {
  70925. get: function () {
  70926. return this._leftStick;
  70927. },
  70928. set: function (newValues) {
  70929. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  70930. this._onleftstickchanged(newValues);
  70931. }
  70932. this._leftStick = newValues;
  70933. },
  70934. enumerable: true,
  70935. configurable: true
  70936. });
  70937. Object.defineProperty(Gamepad.prototype, "rightStick", {
  70938. get: function () {
  70939. return this._rightStick;
  70940. },
  70941. set: function (newValues) {
  70942. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  70943. this._onrightstickchanged(newValues);
  70944. }
  70945. this._rightStick = newValues;
  70946. },
  70947. enumerable: true,
  70948. configurable: true
  70949. });
  70950. Gamepad.prototype.update = function () {
  70951. if (this._leftStick) {
  70952. this.leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  70953. if (this._invertLeftStickY) {
  70954. this.leftStick.y *= -1;
  70955. }
  70956. }
  70957. if (this._rightStick) {
  70958. this.rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  70959. }
  70960. };
  70961. Gamepad.prototype.dispose = function () {
  70962. };
  70963. Gamepad.GAMEPAD = 0;
  70964. Gamepad.GENERIC = 1;
  70965. Gamepad.XBOX = 2;
  70966. Gamepad.POSE_ENABLED = 3;
  70967. return Gamepad;
  70968. }());
  70969. BABYLON.Gamepad = Gamepad;
  70970. var GenericPad = /** @class */ (function (_super) {
  70971. __extends(GenericPad, _super);
  70972. function GenericPad(id, index, browserGamepad) {
  70973. var _this = _super.call(this, id, index, browserGamepad) || this;
  70974. _this.onButtonDownObservable = new BABYLON.Observable();
  70975. _this.onButtonUpObservable = new BABYLON.Observable();
  70976. _this.type = Gamepad.GENERIC;
  70977. _this._buttons = new Array(browserGamepad.buttons.length);
  70978. return _this;
  70979. }
  70980. GenericPad.prototype.onbuttondown = function (callback) {
  70981. this._onbuttondown = callback;
  70982. };
  70983. GenericPad.prototype.onbuttonup = function (callback) {
  70984. this._onbuttonup = callback;
  70985. };
  70986. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  70987. if (newValue !== currentValue) {
  70988. if (newValue === 1) {
  70989. if (this._onbuttondown) {
  70990. this._onbuttondown(buttonIndex);
  70991. }
  70992. this.onButtonDownObservable.notifyObservers(buttonIndex);
  70993. }
  70994. if (newValue === 0) {
  70995. if (this._onbuttonup) {
  70996. this._onbuttonup(buttonIndex);
  70997. }
  70998. this.onButtonUpObservable.notifyObservers(buttonIndex);
  70999. }
  71000. }
  71001. return newValue;
  71002. };
  71003. GenericPad.prototype.update = function () {
  71004. _super.prototype.update.call(this);
  71005. for (var index = 0; index < this._buttons.length; index++) {
  71006. this._buttons[index] = this._setButtonValue(this.browserGamepad.buttons[index].value, this._buttons[index], index);
  71007. }
  71008. };
  71009. GenericPad.prototype.dispose = function () {
  71010. _super.prototype.dispose.call(this);
  71011. this.onButtonDownObservable.clear();
  71012. this.onButtonUpObservable.clear();
  71013. };
  71014. return GenericPad;
  71015. }(Gamepad));
  71016. BABYLON.GenericPad = GenericPad;
  71017. })(BABYLON || (BABYLON = {}));
  71018. //# sourceMappingURL=babylon.gamepad.js.map
  71019. var BABYLON;
  71020. (function (BABYLON) {
  71021. /**
  71022. * Defines supported buttons for XBox360 compatible gamepads
  71023. */
  71024. var Xbox360Button;
  71025. (function (Xbox360Button) {
  71026. /** A */
  71027. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  71028. /** B */
  71029. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  71030. /** X */
  71031. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  71032. /** Y */
  71033. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  71034. /** Start */
  71035. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  71036. /** Back */
  71037. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  71038. /** Left button */
  71039. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  71040. /** Right button */
  71041. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  71042. /** Left stick */
  71043. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  71044. /** Right stick */
  71045. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  71046. })(Xbox360Button = BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  71047. /** Defines values for XBox360 DPad */
  71048. var Xbox360Dpad;
  71049. (function (Xbox360Dpad) {
  71050. /** Up */
  71051. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  71052. /** Down */
  71053. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  71054. /** Left */
  71055. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  71056. /** Right */
  71057. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  71058. })(Xbox360Dpad = BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  71059. /**
  71060. * Defines a XBox360 gamepad
  71061. */
  71062. var Xbox360Pad = /** @class */ (function (_super) {
  71063. __extends(Xbox360Pad, _super);
  71064. /**
  71065. * Creates a new XBox360 gamepad object
  71066. * @param id defines the id of this gamepad
  71067. * @param index defines its index
  71068. * @param gamepad defines the internal HTML gamepad object
  71069. * @param xboxOne defines if it is a XBox One gamepad
  71070. */
  71071. function Xbox360Pad(id, index, gamepad, xboxOne) {
  71072. if (xboxOne === void 0) { xboxOne = false; }
  71073. var _this = _super.call(this, id, index, gamepad, 0, 1, 2, 3) || this;
  71074. _this._leftTrigger = 0;
  71075. _this._rightTrigger = 0;
  71076. /** Observable raised when a button is pressed */
  71077. _this.onButtonDownObservable = new BABYLON.Observable();
  71078. /** Observable raised when a button is released */
  71079. _this.onButtonUpObservable = new BABYLON.Observable();
  71080. /** Observable raised when a pad is pressed */
  71081. _this.onPadDownObservable = new BABYLON.Observable();
  71082. /** Observable raised when a pad is released */
  71083. _this.onPadUpObservable = new BABYLON.Observable();
  71084. _this._buttonA = 0;
  71085. _this._buttonB = 0;
  71086. _this._buttonX = 0;
  71087. _this._buttonY = 0;
  71088. _this._buttonBack = 0;
  71089. _this._buttonStart = 0;
  71090. _this._buttonLB = 0;
  71091. _this._buttonRB = 0;
  71092. _this._buttonLeftStick = 0;
  71093. _this._buttonRightStick = 0;
  71094. _this._dPadUp = 0;
  71095. _this._dPadDown = 0;
  71096. _this._dPadLeft = 0;
  71097. _this._dPadRight = 0;
  71098. _this._isXboxOnePad = false;
  71099. _this.type = BABYLON.Gamepad.XBOX;
  71100. _this._isXboxOnePad = xboxOne;
  71101. return _this;
  71102. }
  71103. /**
  71104. * Defines the callback to call when left trigger is pressed
  71105. * @param callback defines the callback to use
  71106. */
  71107. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  71108. this._onlefttriggerchanged = callback;
  71109. };
  71110. /**
  71111. * Defines the callback to call when right trigger is pressed
  71112. * @param callback defines the callback to use
  71113. */
  71114. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  71115. this._onrighttriggerchanged = callback;
  71116. };
  71117. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  71118. /**
  71119. * Gets or sets left trigger value
  71120. */
  71121. get: function () {
  71122. return this._leftTrigger;
  71123. },
  71124. set: function (newValue) {
  71125. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  71126. this._onlefttriggerchanged(newValue);
  71127. }
  71128. this._leftTrigger = newValue;
  71129. },
  71130. enumerable: true,
  71131. configurable: true
  71132. });
  71133. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  71134. /**
  71135. * Gets or sets right trigger value
  71136. */
  71137. get: function () {
  71138. return this._rightTrigger;
  71139. },
  71140. set: function (newValue) {
  71141. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  71142. this._onrighttriggerchanged(newValue);
  71143. }
  71144. this._rightTrigger = newValue;
  71145. },
  71146. enumerable: true,
  71147. configurable: true
  71148. });
  71149. /**
  71150. * Defines the callback to call when a button is pressed
  71151. * @param callback defines the callback to use
  71152. */
  71153. Xbox360Pad.prototype.onbuttondown = function (callback) {
  71154. this._onbuttondown = callback;
  71155. };
  71156. /**
  71157. * Defines the callback to call when a button is released
  71158. * @param callback defines the callback to use
  71159. */
  71160. Xbox360Pad.prototype.onbuttonup = function (callback) {
  71161. this._onbuttonup = callback;
  71162. };
  71163. /**
  71164. * Defines the callback to call when a pad is pressed
  71165. * @param callback defines the callback to use
  71166. */
  71167. Xbox360Pad.prototype.ondpaddown = function (callback) {
  71168. this._ondpaddown = callback;
  71169. };
  71170. /**
  71171. * Defines the callback to call when a pad is released
  71172. * @param callback defines the callback to use
  71173. */
  71174. Xbox360Pad.prototype.ondpadup = function (callback) {
  71175. this._ondpadup = callback;
  71176. };
  71177. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  71178. if (newValue !== currentValue) {
  71179. if (newValue === 1) {
  71180. if (this._onbuttondown) {
  71181. this._onbuttondown(buttonType);
  71182. }
  71183. this.onButtonDownObservable.notifyObservers(buttonType);
  71184. }
  71185. if (newValue === 0) {
  71186. if (this._onbuttonup) {
  71187. this._onbuttonup(buttonType);
  71188. }
  71189. this.onButtonUpObservable.notifyObservers(buttonType);
  71190. }
  71191. }
  71192. return newValue;
  71193. };
  71194. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  71195. if (newValue !== currentValue) {
  71196. if (newValue === 1) {
  71197. if (this._ondpaddown) {
  71198. this._ondpaddown(buttonType);
  71199. }
  71200. this.onPadDownObservable.notifyObservers(buttonType);
  71201. }
  71202. if (newValue === 0) {
  71203. if (this._ondpadup) {
  71204. this._ondpadup(buttonType);
  71205. }
  71206. this.onPadUpObservable.notifyObservers(buttonType);
  71207. }
  71208. }
  71209. return newValue;
  71210. };
  71211. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  71212. /** Gets or sets value of A button */
  71213. get: function () {
  71214. return this._buttonA;
  71215. },
  71216. set: function (value) {
  71217. this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
  71218. },
  71219. enumerable: true,
  71220. configurable: true
  71221. });
  71222. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  71223. /** Gets or sets value of B button */
  71224. get: function () {
  71225. return this._buttonB;
  71226. },
  71227. set: function (value) {
  71228. this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
  71229. },
  71230. enumerable: true,
  71231. configurable: true
  71232. });
  71233. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  71234. /** Gets or sets value of X button */
  71235. get: function () {
  71236. return this._buttonX;
  71237. },
  71238. set: function (value) {
  71239. this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
  71240. },
  71241. enumerable: true,
  71242. configurable: true
  71243. });
  71244. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  71245. /** Gets or sets value of Y button */
  71246. get: function () {
  71247. return this._buttonY;
  71248. },
  71249. set: function (value) {
  71250. this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
  71251. },
  71252. enumerable: true,
  71253. configurable: true
  71254. });
  71255. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  71256. /** Gets or sets value of Start button */
  71257. get: function () {
  71258. return this._buttonStart;
  71259. },
  71260. set: function (value) {
  71261. this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
  71262. },
  71263. enumerable: true,
  71264. configurable: true
  71265. });
  71266. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  71267. /** Gets or sets value of Back button */
  71268. get: function () {
  71269. return this._buttonBack;
  71270. },
  71271. set: function (value) {
  71272. this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
  71273. },
  71274. enumerable: true,
  71275. configurable: true
  71276. });
  71277. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  71278. /** Gets or sets value of Left button */
  71279. get: function () {
  71280. return this._buttonLB;
  71281. },
  71282. set: function (value) {
  71283. this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
  71284. },
  71285. enumerable: true,
  71286. configurable: true
  71287. });
  71288. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  71289. /** Gets or sets value of Right button */
  71290. get: function () {
  71291. return this._buttonRB;
  71292. },
  71293. set: function (value) {
  71294. this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
  71295. },
  71296. enumerable: true,
  71297. configurable: true
  71298. });
  71299. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  71300. /** Gets or sets value of left stick */
  71301. get: function () {
  71302. return this._buttonLeftStick;
  71303. },
  71304. set: function (value) {
  71305. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
  71306. },
  71307. enumerable: true,
  71308. configurable: true
  71309. });
  71310. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  71311. /** Gets or sets value of right stick */
  71312. get: function () {
  71313. return this._buttonRightStick;
  71314. },
  71315. set: function (value) {
  71316. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
  71317. },
  71318. enumerable: true,
  71319. configurable: true
  71320. });
  71321. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  71322. /** Gets or sets value of DPad up */
  71323. get: function () {
  71324. return this._dPadUp;
  71325. },
  71326. set: function (value) {
  71327. this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
  71328. },
  71329. enumerable: true,
  71330. configurable: true
  71331. });
  71332. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  71333. /** Gets or sets value of DPad down */
  71334. get: function () {
  71335. return this._dPadDown;
  71336. },
  71337. set: function (value) {
  71338. this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
  71339. },
  71340. enumerable: true,
  71341. configurable: true
  71342. });
  71343. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  71344. /** Gets or sets value of DPad left */
  71345. get: function () {
  71346. return this._dPadLeft;
  71347. },
  71348. set: function (value) {
  71349. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
  71350. },
  71351. enumerable: true,
  71352. configurable: true
  71353. });
  71354. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  71355. /** Gets or sets value of DPad right */
  71356. get: function () {
  71357. return this._dPadRight;
  71358. },
  71359. set: function (value) {
  71360. this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
  71361. },
  71362. enumerable: true,
  71363. configurable: true
  71364. });
  71365. /**
  71366. * Force the gamepad to synchronize with device values
  71367. */
  71368. Xbox360Pad.prototype.update = function () {
  71369. _super.prototype.update.call(this);
  71370. if (this._isXboxOnePad) {
  71371. this.buttonA = this.browserGamepad.buttons[0].value;
  71372. this.buttonB = this.browserGamepad.buttons[1].value;
  71373. this.buttonX = this.browserGamepad.buttons[2].value;
  71374. this.buttonY = this.browserGamepad.buttons[3].value;
  71375. this.buttonLB = this.browserGamepad.buttons[4].value;
  71376. this.buttonRB = this.browserGamepad.buttons[5].value;
  71377. this.leftTrigger = this.browserGamepad.axes[2];
  71378. this.rightTrigger = this.browserGamepad.axes[5];
  71379. this.buttonBack = this.browserGamepad.buttons[9].value;
  71380. this.buttonStart = this.browserGamepad.buttons[8].value;
  71381. this.buttonLeftStick = this.browserGamepad.buttons[6].value;
  71382. this.buttonRightStick = this.browserGamepad.buttons[7].value;
  71383. this.dPadUp = this.browserGamepad.buttons[11].value;
  71384. this.dPadDown = this.browserGamepad.buttons[12].value;
  71385. this.dPadLeft = this.browserGamepad.buttons[13].value;
  71386. this.dPadRight = this.browserGamepad.buttons[14].value;
  71387. }
  71388. else {
  71389. this.buttonA = this.browserGamepad.buttons[0].value;
  71390. this.buttonB = this.browserGamepad.buttons[1].value;
  71391. this.buttonX = this.browserGamepad.buttons[2].value;
  71392. this.buttonY = this.browserGamepad.buttons[3].value;
  71393. this.buttonLB = this.browserGamepad.buttons[4].value;
  71394. this.buttonRB = this.browserGamepad.buttons[5].value;
  71395. this.leftTrigger = this.browserGamepad.buttons[6].value;
  71396. this.rightTrigger = this.browserGamepad.buttons[7].value;
  71397. this.buttonBack = this.browserGamepad.buttons[8].value;
  71398. this.buttonStart = this.browserGamepad.buttons[9].value;
  71399. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  71400. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  71401. this.dPadUp = this.browserGamepad.buttons[12].value;
  71402. this.dPadDown = this.browserGamepad.buttons[13].value;
  71403. this.dPadLeft = this.browserGamepad.buttons[14].value;
  71404. this.dPadRight = this.browserGamepad.buttons[15].value;
  71405. }
  71406. };
  71407. Xbox360Pad.prototype.dispose = function () {
  71408. _super.prototype.dispose.call(this);
  71409. this.onButtonDownObservable.clear();
  71410. this.onButtonUpObservable.clear();
  71411. this.onPadDownObservable.clear();
  71412. this.onPadUpObservable.clear();
  71413. };
  71414. return Xbox360Pad;
  71415. }(BABYLON.Gamepad));
  71416. BABYLON.Xbox360Pad = Xbox360Pad;
  71417. })(BABYLON || (BABYLON = {}));
  71418. //# sourceMappingURL=babylon.xboxGamepad.js.map
  71419. var BABYLON;
  71420. (function (BABYLON) {
  71421. /**
  71422. * Defines the types of pose enabled controllers that are supported
  71423. */
  71424. var PoseEnabledControllerType;
  71425. (function (PoseEnabledControllerType) {
  71426. /**
  71427. * HTC Vive
  71428. */
  71429. PoseEnabledControllerType[PoseEnabledControllerType["VIVE"] = 0] = "VIVE";
  71430. /**
  71431. * Oculus Rift
  71432. */
  71433. PoseEnabledControllerType[PoseEnabledControllerType["OCULUS"] = 1] = "OCULUS";
  71434. /**
  71435. * Windows mixed reality
  71436. */
  71437. PoseEnabledControllerType[PoseEnabledControllerType["WINDOWS"] = 2] = "WINDOWS";
  71438. /**
  71439. * Samsung gear VR
  71440. */
  71441. PoseEnabledControllerType[PoseEnabledControllerType["GEAR_VR"] = 3] = "GEAR_VR";
  71442. /**
  71443. * Google Daydream
  71444. */
  71445. PoseEnabledControllerType[PoseEnabledControllerType["DAYDREAM"] = 4] = "DAYDREAM";
  71446. /**
  71447. * Generic
  71448. */
  71449. PoseEnabledControllerType[PoseEnabledControllerType["GENERIC"] = 5] = "GENERIC";
  71450. })(PoseEnabledControllerType = BABYLON.PoseEnabledControllerType || (BABYLON.PoseEnabledControllerType = {}));
  71451. /**
  71452. * Defines the PoseEnabledControllerHelper object that is used initialize a gamepad as the controller type it is specified as (eg. windows mixed reality controller)
  71453. */
  71454. var PoseEnabledControllerHelper = /** @class */ (function () {
  71455. function PoseEnabledControllerHelper() {
  71456. }
  71457. /**
  71458. * Initializes a gamepad as the controller type it is specified as (eg. windows mixed reality controller)
  71459. * @param vrGamepad the gamepad to initialized
  71460. * @returns a vr controller of the type the gamepad identified as
  71461. */
  71462. PoseEnabledControllerHelper.InitiateController = function (vrGamepad) {
  71463. // Oculus Touch
  71464. if (vrGamepad.id.indexOf('Oculus Touch') !== -1) {
  71465. return new BABYLON.OculusTouchController(vrGamepad);
  71466. }
  71467. // Windows Mixed Reality controllers
  71468. else if (vrGamepad.id.indexOf(BABYLON.WindowsMotionController.GAMEPAD_ID_PREFIX) === 0) {
  71469. return new BABYLON.WindowsMotionController(vrGamepad);
  71470. }
  71471. // HTC Vive
  71472. else if (vrGamepad.id.toLowerCase().indexOf('openvr') !== -1) {
  71473. return new BABYLON.ViveController(vrGamepad);
  71474. }
  71475. // Samsung/Oculus Gear VR or Oculus Go
  71476. else if (vrGamepad.id.indexOf(BABYLON.GearVRController.GAMEPAD_ID_PREFIX) === 0 || vrGamepad.id.indexOf('Oculus Go') !== -1) {
  71477. return new BABYLON.GearVRController(vrGamepad);
  71478. }
  71479. // Google Daydream
  71480. else if (vrGamepad.id.indexOf(BABYLON.DaydreamController.GAMEPAD_ID_PREFIX) === 0) {
  71481. return new BABYLON.DaydreamController(vrGamepad);
  71482. }
  71483. // Generic
  71484. else {
  71485. return new BABYLON.GenericController(vrGamepad);
  71486. }
  71487. };
  71488. return PoseEnabledControllerHelper;
  71489. }());
  71490. BABYLON.PoseEnabledControllerHelper = PoseEnabledControllerHelper;
  71491. /**
  71492. * Defines the PoseEnabledController object that contains state of a vr capable controller
  71493. */
  71494. var PoseEnabledController = /** @class */ (function (_super) {
  71495. __extends(PoseEnabledController, _super);
  71496. /**
  71497. * Creates a new PoseEnabledController from a gamepad
  71498. * @param browserGamepad the gamepad that the PoseEnabledController should be created from
  71499. */
  71500. function PoseEnabledController(browserGamepad) {
  71501. var _this = _super.call(this, browserGamepad.id, browserGamepad.index, browserGamepad) || this;
  71502. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  71503. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  71504. _this._deviceRoomRotationQuaternion = new BABYLON.Quaternion();
  71505. /**
  71506. * The device position in babylon space
  71507. */
  71508. _this.devicePosition = BABYLON.Vector3.Zero();
  71509. /**
  71510. * The device rotation in babylon space
  71511. */
  71512. _this.deviceRotationQuaternion = new BABYLON.Quaternion();
  71513. /**
  71514. * The scale factor of the device in babylon space
  71515. */
  71516. _this.deviceScaleFactor = 1;
  71517. _this._leftHandSystemQuaternion = new BABYLON.Quaternion();
  71518. /**
  71519. * Internal, matrix used to convert room space to babylon space
  71520. */
  71521. _this._deviceToWorld = BABYLON.Matrix.Identity();
  71522. /**
  71523. * Node to be used when casting a ray from the controller
  71524. */
  71525. _this._pointingPoseNode = null;
  71526. _this._workingMatrix = BABYLON.Matrix.Identity();
  71527. /**
  71528. * @hidden
  71529. */
  71530. _this._meshAttachedObservable = new BABYLON.Observable();
  71531. _this.type = BABYLON.Gamepad.POSE_ENABLED;
  71532. _this.controllerType = PoseEnabledControllerType.GENERIC;
  71533. _this.position = BABYLON.Vector3.Zero();
  71534. _this.rotationQuaternion = new BABYLON.Quaternion();
  71535. _this._calculatedPosition = BABYLON.Vector3.Zero();
  71536. _this._calculatedRotation = new BABYLON.Quaternion();
  71537. BABYLON.Quaternion.RotationYawPitchRollToRef(Math.PI, 0, 0, _this._leftHandSystemQuaternion);
  71538. return _this;
  71539. }
  71540. /**
  71541. * Updates the state of the pose enbaled controller and mesh based on the current position and rotation of the controller
  71542. */
  71543. PoseEnabledController.prototype.update = function () {
  71544. _super.prototype.update.call(this);
  71545. var pose = this.browserGamepad.pose;
  71546. this.updateFromDevice(pose);
  71547. BABYLON.Vector3.TransformCoordinatesToRef(this._calculatedPosition, this._deviceToWorld, this.devicePosition);
  71548. this._deviceToWorld.getRotationMatrixToRef(this._workingMatrix);
  71549. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  71550. this.deviceRotationQuaternion.multiplyInPlace(this._calculatedRotation);
  71551. if (this._mesh) {
  71552. this._mesh.position.copyFrom(this.devicePosition);
  71553. if (this._mesh.rotationQuaternion) {
  71554. this._mesh.rotationQuaternion.copyFrom(this.deviceRotationQuaternion);
  71555. }
  71556. }
  71557. };
  71558. /**
  71559. * Updates the state of the pose enbaled controller based on the raw pose data from the device
  71560. * @param poseData raw pose fromthe device
  71561. */
  71562. PoseEnabledController.prototype.updateFromDevice = function (poseData) {
  71563. if (poseData) {
  71564. this.rawPose = poseData;
  71565. if (poseData.position) {
  71566. this._deviceRoomPosition.copyFromFloats(poseData.position[0], poseData.position[1], -poseData.position[2]);
  71567. if (this._mesh && this._mesh.getScene().useRightHandedSystem) {
  71568. this._deviceRoomPosition.z *= -1;
  71569. }
  71570. this._deviceRoomPosition.scaleToRef(this.deviceScaleFactor, this._calculatedPosition);
  71571. this._calculatedPosition.addInPlace(this.position);
  71572. }
  71573. var pose = this.rawPose;
  71574. if (poseData.orientation && pose.orientation) {
  71575. this._deviceRoomRotationQuaternion.copyFromFloats(pose.orientation[0], pose.orientation[1], -pose.orientation[2], -pose.orientation[3]);
  71576. if (this._mesh) {
  71577. if (this._mesh.getScene().useRightHandedSystem) {
  71578. this._deviceRoomRotationQuaternion.z *= -1;
  71579. this._deviceRoomRotationQuaternion.w *= -1;
  71580. }
  71581. else {
  71582. this._deviceRoomRotationQuaternion.multiplyToRef(this._leftHandSystemQuaternion, this._deviceRoomRotationQuaternion);
  71583. }
  71584. }
  71585. // if the camera is set, rotate to the camera's rotation
  71586. this._deviceRoomRotationQuaternion.multiplyToRef(this.rotationQuaternion, this._calculatedRotation);
  71587. }
  71588. }
  71589. };
  71590. /**
  71591. * Attaches a mesh to the controller
  71592. * @param mesh the mesh to be attached
  71593. */
  71594. PoseEnabledController.prototype.attachToMesh = function (mesh) {
  71595. if (this._mesh) {
  71596. this._mesh.parent = null;
  71597. }
  71598. this._mesh = mesh;
  71599. if (this._poseControlledCamera) {
  71600. this._mesh.parent = this._poseControlledCamera;
  71601. }
  71602. if (!this._mesh.rotationQuaternion) {
  71603. this._mesh.rotationQuaternion = new BABYLON.Quaternion();
  71604. }
  71605. this._meshAttachedObservable.notifyObservers(mesh);
  71606. };
  71607. /**
  71608. * Attaches the controllers mesh to a camera
  71609. * @param camera the camera the mesh should be attached to
  71610. */
  71611. PoseEnabledController.prototype.attachToPoseControlledCamera = function (camera) {
  71612. this._poseControlledCamera = camera;
  71613. if (this._mesh) {
  71614. this._mesh.parent = this._poseControlledCamera;
  71615. }
  71616. };
  71617. /**
  71618. * Disposes of the controller
  71619. */
  71620. PoseEnabledController.prototype.dispose = function () {
  71621. if (this._mesh) {
  71622. this._mesh.dispose();
  71623. }
  71624. this._mesh = null;
  71625. _super.prototype.dispose.call(this);
  71626. };
  71627. Object.defineProperty(PoseEnabledController.prototype, "mesh", {
  71628. /**
  71629. * The mesh that is attached to the controller
  71630. */
  71631. get: function () {
  71632. return this._mesh;
  71633. },
  71634. enumerable: true,
  71635. configurable: true
  71636. });
  71637. /**
  71638. * Gets the ray of the controller in the direction the controller is pointing
  71639. * @param length the length the resulting ray should be
  71640. * @returns a ray in the direction the controller is pointing
  71641. */
  71642. PoseEnabledController.prototype.getForwardRay = function (length) {
  71643. if (length === void 0) { length = 100; }
  71644. if (!this.mesh) {
  71645. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, 1), length);
  71646. }
  71647. var m = this._pointingPoseNode ? this._pointingPoseNode.getWorldMatrix() : this.mesh.getWorldMatrix();
  71648. var origin = m.getTranslation();
  71649. var forward = new BABYLON.Vector3(0, 0, -1);
  71650. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  71651. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  71652. return new BABYLON.Ray(origin, direction, length);
  71653. };
  71654. /**
  71655. * Name of the child mesh that can be used to cast a ray from the controller
  71656. */
  71657. PoseEnabledController.POINTING_POSE = "POINTING_POSE";
  71658. return PoseEnabledController;
  71659. }(BABYLON.Gamepad));
  71660. BABYLON.PoseEnabledController = PoseEnabledController;
  71661. })(BABYLON || (BABYLON = {}));
  71662. //# sourceMappingURL=babylon.poseEnabledController.js.map
  71663. var BABYLON;
  71664. (function (BABYLON) {
  71665. /**
  71666. * Defines the WebVRController object that represents controllers tracked in 3D space
  71667. */
  71668. var WebVRController = /** @class */ (function (_super) {
  71669. __extends(WebVRController, _super);
  71670. /**
  71671. * Creates a new WebVRController from a gamepad
  71672. * @param vrGamepad the gamepad that the WebVRController should be created from
  71673. */
  71674. function WebVRController(vrGamepad) {
  71675. var _this = _super.call(this, vrGamepad) || this;
  71676. // Observables
  71677. /**
  71678. * Fired when the trigger state has changed
  71679. */
  71680. _this.onTriggerStateChangedObservable = new BABYLON.Observable();
  71681. /**
  71682. * Fired when the main button state has changed
  71683. */
  71684. _this.onMainButtonStateChangedObservable = new BABYLON.Observable();
  71685. /**
  71686. * Fired when the secondary button state has changed
  71687. */
  71688. _this.onSecondaryButtonStateChangedObservable = new BABYLON.Observable();
  71689. /**
  71690. * Fired when the pad state has changed
  71691. */
  71692. _this.onPadStateChangedObservable = new BABYLON.Observable();
  71693. /**
  71694. * Fired when controllers stick values have changed
  71695. */
  71696. _this.onPadValuesChangedObservable = new BABYLON.Observable();
  71697. /**
  71698. * X and Y axis corrisponding to the controllers joystick
  71699. */
  71700. _this.pad = { x: 0, y: 0 };
  71701. // avoid GC, store state in a tmp object
  71702. _this._changes = {
  71703. pressChanged: false,
  71704. touchChanged: false,
  71705. valueChanged: false,
  71706. changed: false
  71707. };
  71708. _this._buttons = new Array(vrGamepad.buttons.length);
  71709. _this.hand = vrGamepad.hand;
  71710. return _this;
  71711. }
  71712. /**
  71713. * Fired when a controller button's state has changed
  71714. * @param callback the callback containing the button that was modified
  71715. */
  71716. WebVRController.prototype.onButtonStateChange = function (callback) {
  71717. this._onButtonStateChange = callback;
  71718. };
  71719. Object.defineProperty(WebVRController.prototype, "defaultModel", {
  71720. /**
  71721. * The default controller model for the controller
  71722. */
  71723. get: function () {
  71724. return this._defaultModel;
  71725. },
  71726. enumerable: true,
  71727. configurable: true
  71728. });
  71729. /**
  71730. * Updates the state of the controller and mesh based on the current position and rotation of the controller
  71731. */
  71732. WebVRController.prototype.update = function () {
  71733. _super.prototype.update.call(this);
  71734. for (var index = 0; index < this._buttons.length; index++) {
  71735. this._setButtonValue(this.browserGamepad.buttons[index], this._buttons[index], index);
  71736. }
  71737. ;
  71738. if (this.leftStick.x !== this.pad.x || this.leftStick.y !== this.pad.y) {
  71739. this.pad.x = this.leftStick.x;
  71740. this.pad.y = this.leftStick.y;
  71741. this.onPadValuesChangedObservable.notifyObservers(this.pad);
  71742. }
  71743. };
  71744. WebVRController.prototype._setButtonValue = function (newState, currentState, buttonIndex) {
  71745. if (!newState) {
  71746. newState = {
  71747. pressed: false,
  71748. touched: false,
  71749. value: 0
  71750. };
  71751. }
  71752. if (!currentState) {
  71753. this._buttons[buttonIndex] = {
  71754. pressed: newState.pressed,
  71755. touched: newState.touched,
  71756. value: newState.value
  71757. };
  71758. return;
  71759. }
  71760. this._checkChanges(newState, currentState);
  71761. if (this._changes.changed) {
  71762. this._onButtonStateChange && this._onButtonStateChange(this.index, buttonIndex, newState);
  71763. this._handleButtonChange(buttonIndex, newState, this._changes);
  71764. }
  71765. this._buttons[buttonIndex].pressed = newState.pressed;
  71766. this._buttons[buttonIndex].touched = newState.touched;
  71767. // oculus triggers are never 0, thou not touched.
  71768. this._buttons[buttonIndex].value = newState.value < 0.00000001 ? 0 : newState.value;
  71769. };
  71770. WebVRController.prototype._checkChanges = function (newState, currentState) {
  71771. this._changes.pressChanged = newState.pressed !== currentState.pressed;
  71772. this._changes.touchChanged = newState.touched !== currentState.touched;
  71773. this._changes.valueChanged = newState.value !== currentState.value;
  71774. this._changes.changed = this._changes.pressChanged || this._changes.touchChanged || this._changes.valueChanged;
  71775. return this._changes;
  71776. };
  71777. /**
  71778. * Disposes of th webVRCOntroller
  71779. */
  71780. WebVRController.prototype.dispose = function () {
  71781. _super.prototype.dispose.call(this);
  71782. this.onTriggerStateChangedObservable.clear();
  71783. this.onMainButtonStateChangedObservable.clear();
  71784. this.onSecondaryButtonStateChangedObservable.clear();
  71785. this.onPadStateChangedObservable.clear();
  71786. this.onPadValuesChangedObservable.clear();
  71787. };
  71788. return WebVRController;
  71789. }(BABYLON.PoseEnabledController));
  71790. BABYLON.WebVRController = WebVRController;
  71791. })(BABYLON || (BABYLON = {}));
  71792. //# sourceMappingURL=babylon.webVRController.js.map
  71793. var BABYLON;
  71794. (function (BABYLON) {
  71795. /**
  71796. * Oculus Touch Controller
  71797. */
  71798. var OculusTouchController = /** @class */ (function (_super) {
  71799. __extends(OculusTouchController, _super);
  71800. /**
  71801. * Creates a new OculusTouchController from a gamepad
  71802. * @param vrGamepad the gamepad that the controller should be created from
  71803. */
  71804. function OculusTouchController(vrGamepad) {
  71805. var _this = _super.call(this, vrGamepad) || this;
  71806. /**
  71807. * Fired when the secondary trigger on this controller is modified
  71808. */
  71809. _this.onSecondaryTriggerStateChangedObservable = new BABYLON.Observable();
  71810. /**
  71811. * Fired when the thumb rest on this controller is modified
  71812. */
  71813. _this.onThumbRestChangedObservable = new BABYLON.Observable();
  71814. _this.controllerType = BABYLON.PoseEnabledControllerType.OCULUS;
  71815. return _this;
  71816. }
  71817. /**
  71818. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  71819. * @param scene scene in which to add meshes
  71820. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  71821. */
  71822. OculusTouchController.prototype.initControllerMesh = function (scene, meshLoaded) {
  71823. var _this = this;
  71824. var meshName;
  71825. // Hand
  71826. if (this.hand === 'left') {
  71827. meshName = OculusTouchController.MODEL_LEFT_FILENAME;
  71828. }
  71829. else { // Right is the default if no hand is specified
  71830. meshName = OculusTouchController.MODEL_RIGHT_FILENAME;
  71831. }
  71832. BABYLON.SceneLoader.ImportMesh("", OculusTouchController.MODEL_BASE_URL, meshName, scene, function (newMeshes) {
  71833. /*
  71834. Parent Mesh name: oculus_touch_left
  71835. - body
  71836. - trigger
  71837. - thumbstick
  71838. - grip
  71839. - button_y
  71840. - button_x
  71841. - button_enter
  71842. */
  71843. _this._defaultModel = newMeshes[1];
  71844. _this.attachToMesh(_this._defaultModel);
  71845. if (meshLoaded) {
  71846. meshLoaded(_this._defaultModel);
  71847. }
  71848. });
  71849. };
  71850. Object.defineProperty(OculusTouchController.prototype, "onAButtonStateChangedObservable", {
  71851. /**
  71852. * Fired when the A button on this controller is modified
  71853. */
  71854. get: function () {
  71855. if (this.hand === 'right') {
  71856. return this.onMainButtonStateChangedObservable;
  71857. }
  71858. else {
  71859. throw new Error('No A button on left hand');
  71860. }
  71861. },
  71862. enumerable: true,
  71863. configurable: true
  71864. });
  71865. Object.defineProperty(OculusTouchController.prototype, "onBButtonStateChangedObservable", {
  71866. /**
  71867. * Fired when the B button on this controller is modified
  71868. */
  71869. get: function () {
  71870. if (this.hand === 'right') {
  71871. return this.onSecondaryButtonStateChangedObservable;
  71872. }
  71873. else {
  71874. throw new Error('No B button on left hand');
  71875. }
  71876. },
  71877. enumerable: true,
  71878. configurable: true
  71879. });
  71880. Object.defineProperty(OculusTouchController.prototype, "onXButtonStateChangedObservable", {
  71881. /**
  71882. * Fired when the X button on this controller is modified
  71883. */
  71884. get: function () {
  71885. if (this.hand === 'left') {
  71886. return this.onMainButtonStateChangedObservable;
  71887. }
  71888. else {
  71889. throw new Error('No X button on right hand');
  71890. }
  71891. },
  71892. enumerable: true,
  71893. configurable: true
  71894. });
  71895. Object.defineProperty(OculusTouchController.prototype, "onYButtonStateChangedObservable", {
  71896. /**
  71897. * Fired when the Y button on this controller is modified
  71898. */
  71899. get: function () {
  71900. if (this.hand === 'left') {
  71901. return this.onSecondaryButtonStateChangedObservable;
  71902. }
  71903. else {
  71904. throw new Error('No Y button on right hand');
  71905. }
  71906. },
  71907. enumerable: true,
  71908. configurable: true
  71909. });
  71910. /**
  71911. * Called once for each button that changed state since the last frame
  71912. * 0) thumb stick (touch, press, value = pressed (0,1)). value is in this.leftStick
  71913. * 1) index trigger (touch (?), press (only when value > 0.1), value 0 to 1)
  71914. * 2) secondary trigger (same)
  71915. * 3) A (right) X (left), touch, pressed = value
  71916. * 4) B / Y
  71917. * 5) thumb rest
  71918. * @param buttonIdx Which button index changed
  71919. * @param state New state of the button
  71920. * @param changes Which properties on the state changed since last frame
  71921. */
  71922. OculusTouchController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  71923. var notifyObject = state; //{ state: state, changes: changes };
  71924. var triggerDirection = this.hand === 'right' ? -1 : 1;
  71925. switch (buttonIdx) {
  71926. case 0:
  71927. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  71928. return;
  71929. case 1: // index trigger
  71930. if (this._defaultModel) {
  71931. (this._defaultModel.getChildren()[3]).rotation.x = -notifyObject.value * 0.20;
  71932. (this._defaultModel.getChildren()[3]).position.y = -notifyObject.value * 0.005;
  71933. (this._defaultModel.getChildren()[3]).position.z = -notifyObject.value * 0.005;
  71934. }
  71935. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  71936. return;
  71937. case 2: // secondary trigger
  71938. if (this._defaultModel) {
  71939. (this._defaultModel.getChildren()[4]).position.x = triggerDirection * notifyObject.value * 0.0035;
  71940. }
  71941. this.onSecondaryTriggerStateChangedObservable.notifyObservers(notifyObject);
  71942. return;
  71943. case 3:
  71944. if (this._defaultModel) {
  71945. if (notifyObject.pressed) {
  71946. (this._defaultModel.getChildren()[1]).position.y = -0.001;
  71947. }
  71948. else {
  71949. (this._defaultModel.getChildren()[1]).position.y = 0;
  71950. }
  71951. }
  71952. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  71953. return;
  71954. case 4:
  71955. if (this._defaultModel) {
  71956. if (notifyObject.pressed) {
  71957. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  71958. }
  71959. else {
  71960. (this._defaultModel.getChildren()[2]).position.y = 0;
  71961. }
  71962. }
  71963. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  71964. return;
  71965. case 5:
  71966. this.onThumbRestChangedObservable.notifyObservers(notifyObject);
  71967. return;
  71968. }
  71969. };
  71970. /**
  71971. * Base Url for the controller model.
  71972. */
  71973. OculusTouchController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/oculus/';
  71974. /**
  71975. * File name for the left controller model.
  71976. */
  71977. OculusTouchController.MODEL_LEFT_FILENAME = 'left.babylon';
  71978. /**
  71979. * File name for the right controller model.
  71980. */
  71981. OculusTouchController.MODEL_RIGHT_FILENAME = 'right.babylon';
  71982. return OculusTouchController;
  71983. }(BABYLON.WebVRController));
  71984. BABYLON.OculusTouchController = OculusTouchController;
  71985. })(BABYLON || (BABYLON = {}));
  71986. //# sourceMappingURL=babylon.oculusTouchController.js.map
  71987. var BABYLON;
  71988. (function (BABYLON) {
  71989. /**
  71990. * Vive Controller
  71991. */
  71992. var ViveController = /** @class */ (function (_super) {
  71993. __extends(ViveController, _super);
  71994. /**
  71995. * Creates a new ViveController from a gamepad
  71996. * @param vrGamepad the gamepad that the controller should be created from
  71997. */
  71998. function ViveController(vrGamepad) {
  71999. var _this = _super.call(this, vrGamepad) || this;
  72000. _this.controllerType = BABYLON.PoseEnabledControllerType.VIVE;
  72001. _this._invertLeftStickY = true;
  72002. return _this;
  72003. }
  72004. /**
  72005. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  72006. * @param scene scene in which to add meshes
  72007. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  72008. */
  72009. ViveController.prototype.initControllerMesh = function (scene, meshLoaded) {
  72010. var _this = this;
  72011. BABYLON.SceneLoader.ImportMesh("", ViveController.MODEL_BASE_URL, ViveController.MODEL_FILENAME, scene, function (newMeshes) {
  72012. /*
  72013. Parent Mesh name: ViveWand
  72014. - body
  72015. - r_gripper
  72016. - l_gripper
  72017. - menu_button
  72018. - system_button
  72019. - trackpad
  72020. - trigger
  72021. - LED
  72022. */
  72023. _this._defaultModel = newMeshes[1];
  72024. _this.attachToMesh(_this._defaultModel);
  72025. if (meshLoaded) {
  72026. meshLoaded(_this._defaultModel);
  72027. }
  72028. });
  72029. };
  72030. Object.defineProperty(ViveController.prototype, "onLeftButtonStateChangedObservable", {
  72031. /**
  72032. * Fired when the left button on this controller is modified
  72033. */
  72034. get: function () {
  72035. return this.onMainButtonStateChangedObservable;
  72036. },
  72037. enumerable: true,
  72038. configurable: true
  72039. });
  72040. Object.defineProperty(ViveController.prototype, "onRightButtonStateChangedObservable", {
  72041. /**
  72042. * Fired when the right button on this controller is modified
  72043. */
  72044. get: function () {
  72045. return this.onMainButtonStateChangedObservable;
  72046. },
  72047. enumerable: true,
  72048. configurable: true
  72049. });
  72050. Object.defineProperty(ViveController.prototype, "onMenuButtonStateChangedObservable", {
  72051. /**
  72052. * Fired when the menu button on this controller is modified
  72053. */
  72054. get: function () {
  72055. return this.onSecondaryButtonStateChangedObservable;
  72056. },
  72057. enumerable: true,
  72058. configurable: true
  72059. });
  72060. /**
  72061. * Called once for each button that changed state since the last frame
  72062. * Vive mapping:
  72063. * 0: touchpad
  72064. * 1: trigger
  72065. * 2: left AND right buttons
  72066. * 3: menu button
  72067. * @param buttonIdx Which button index changed
  72068. * @param state New state of the button
  72069. * @param changes Which properties on the state changed since last frame
  72070. */
  72071. ViveController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  72072. var notifyObject = state; //{ state: state, changes: changes };
  72073. switch (buttonIdx) {
  72074. case 0:
  72075. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  72076. return;
  72077. case 1: // index trigger
  72078. if (this._defaultModel) {
  72079. (this._defaultModel.getChildren()[6]).rotation.x = -notifyObject.value * 0.15;
  72080. }
  72081. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  72082. return;
  72083. case 2: // left AND right button
  72084. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  72085. return;
  72086. case 3:
  72087. if (this._defaultModel) {
  72088. if (notifyObject.pressed) {
  72089. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  72090. }
  72091. else {
  72092. (this._defaultModel.getChildren()[2]).position.y = 0;
  72093. }
  72094. }
  72095. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  72096. return;
  72097. }
  72098. };
  72099. /**
  72100. * Base Url for the controller model.
  72101. */
  72102. ViveController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/vive/';
  72103. /**
  72104. * File name for the controller model.
  72105. */
  72106. ViveController.MODEL_FILENAME = 'wand.babylon';
  72107. return ViveController;
  72108. }(BABYLON.WebVRController));
  72109. BABYLON.ViveController = ViveController;
  72110. })(BABYLON || (BABYLON = {}));
  72111. //# sourceMappingURL=babylon.viveController.js.map
  72112. var BABYLON;
  72113. (function (BABYLON) {
  72114. /**
  72115. * Generic Controller
  72116. */
  72117. var GenericController = /** @class */ (function (_super) {
  72118. __extends(GenericController, _super);
  72119. /**
  72120. * Creates a new GenericController from a gamepad
  72121. * @param vrGamepad the gamepad that the controller should be created from
  72122. */
  72123. function GenericController(vrGamepad) {
  72124. return _super.call(this, vrGamepad) || this;
  72125. }
  72126. /**
  72127. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  72128. * @param scene scene in which to add meshes
  72129. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  72130. */
  72131. GenericController.prototype.initControllerMesh = function (scene, meshLoaded) {
  72132. var _this = this;
  72133. BABYLON.SceneLoader.ImportMesh("", GenericController.MODEL_BASE_URL, GenericController.MODEL_FILENAME, scene, function (newMeshes) {
  72134. _this._defaultModel = newMeshes[1];
  72135. _this.attachToMesh(_this._defaultModel);
  72136. if (meshLoaded) {
  72137. meshLoaded(_this._defaultModel);
  72138. }
  72139. });
  72140. };
  72141. /**
  72142. * Called once for each button that changed state since the last frame
  72143. * @param buttonIdx Which button index changed
  72144. * @param state New state of the button
  72145. * @param changes Which properties on the state changed since last frame
  72146. */
  72147. GenericController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  72148. console.log("Button id: " + buttonIdx + "state: ");
  72149. console.dir(state);
  72150. };
  72151. /**
  72152. * Base Url for the controller model.
  72153. */
  72154. GenericController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  72155. /**
  72156. * File name for the controller model.
  72157. */
  72158. GenericController.MODEL_FILENAME = 'generic.babylon';
  72159. return GenericController;
  72160. }(BABYLON.WebVRController));
  72161. BABYLON.GenericController = GenericController;
  72162. })(BABYLON || (BABYLON = {}));
  72163. //# sourceMappingURL=babylon.genericController.js.map
  72164. var BABYLON;
  72165. (function (BABYLON) {
  72166. /**
  72167. * Defines the LoadedMeshInfo object that describes information about the loaded webVR controller mesh
  72168. */
  72169. var LoadedMeshInfo = /** @class */ (function () {
  72170. function LoadedMeshInfo() {
  72171. /**
  72172. * Map of the button meshes contained in the controller
  72173. */
  72174. this.buttonMeshes = {};
  72175. /**
  72176. * Map of the axis meshes contained in the controller
  72177. */
  72178. this.axisMeshes = {};
  72179. }
  72180. return LoadedMeshInfo;
  72181. }());
  72182. /**
  72183. * Defines the WindowsMotionController object that the state of the windows motion controller
  72184. */
  72185. var WindowsMotionController = /** @class */ (function (_super) {
  72186. __extends(WindowsMotionController, _super);
  72187. /**
  72188. * Creates a new WindowsMotionController from a gamepad
  72189. * @param vrGamepad the gamepad that the controller should be created from
  72190. */
  72191. function WindowsMotionController(vrGamepad) {
  72192. var _this = _super.call(this, vrGamepad) || this;
  72193. _this._mapping = {
  72194. // Semantic button names
  72195. buttons: ['thumbstick', 'trigger', 'grip', 'menu', 'trackpad'],
  72196. // A mapping of the button name to glTF model node name
  72197. // that should be transformed by button value.
  72198. buttonMeshNames: {
  72199. 'trigger': 'SELECT',
  72200. 'menu': 'MENU',
  72201. 'grip': 'GRASP',
  72202. 'thumbstick': 'THUMBSTICK_PRESS',
  72203. 'trackpad': 'TOUCHPAD_PRESS'
  72204. },
  72205. // This mapping is used to translate from the Motion Controller to Babylon semantics
  72206. buttonObservableNames: {
  72207. 'trigger': 'onTriggerStateChangedObservable',
  72208. 'menu': 'onSecondaryButtonStateChangedObservable',
  72209. 'grip': 'onMainButtonStateChangedObservable',
  72210. 'thumbstick': 'onPadStateChangedObservable',
  72211. 'trackpad': 'onTrackpadChangedObservable'
  72212. },
  72213. // A mapping of the axis name to glTF model node name
  72214. // that should be transformed by axis value.
  72215. // This array mirrors the browserGamepad.axes array, such that
  72216. // the mesh corresponding to axis 0 is in this array index 0.
  72217. axisMeshNames: [
  72218. 'THUMBSTICK_X',
  72219. 'THUMBSTICK_Y',
  72220. 'TOUCHPAD_TOUCH_X',
  72221. 'TOUCHPAD_TOUCH_Y'
  72222. ],
  72223. pointingPoseMeshName: BABYLON.PoseEnabledController.POINTING_POSE
  72224. };
  72225. /**
  72226. * Fired when the trackpad on this controller is clicked
  72227. */
  72228. _this.onTrackpadChangedObservable = new BABYLON.Observable();
  72229. /**
  72230. * Fired when the trackpad on this controller is modified
  72231. */
  72232. _this.onTrackpadValuesChangedObservable = new BABYLON.Observable();
  72233. /**
  72234. * The current x and y values of this controller's trackpad
  72235. */
  72236. _this.trackpad = { x: 0, y: 0 };
  72237. _this.controllerType = BABYLON.PoseEnabledControllerType.WINDOWS;
  72238. _this._loadedMeshInfo = null;
  72239. return _this;
  72240. }
  72241. Object.defineProperty(WindowsMotionController.prototype, "onTriggerButtonStateChangedObservable", {
  72242. /**
  72243. * Fired when the trigger on this controller is modified
  72244. */
  72245. get: function () {
  72246. return this.onTriggerStateChangedObservable;
  72247. },
  72248. enumerable: true,
  72249. configurable: true
  72250. });
  72251. Object.defineProperty(WindowsMotionController.prototype, "onMenuButtonStateChangedObservable", {
  72252. /**
  72253. * Fired when the menu button on this controller is modified
  72254. */
  72255. get: function () {
  72256. return this.onSecondaryButtonStateChangedObservable;
  72257. },
  72258. enumerable: true,
  72259. configurable: true
  72260. });
  72261. Object.defineProperty(WindowsMotionController.prototype, "onGripButtonStateChangedObservable", {
  72262. /**
  72263. * Fired when the grip button on this controller is modified
  72264. */
  72265. get: function () {
  72266. return this.onMainButtonStateChangedObservable;
  72267. },
  72268. enumerable: true,
  72269. configurable: true
  72270. });
  72271. Object.defineProperty(WindowsMotionController.prototype, "onThumbstickButtonStateChangedObservable", {
  72272. /**
  72273. * Fired when the thumbstick button on this controller is modified
  72274. */
  72275. get: function () {
  72276. return this.onPadStateChangedObservable;
  72277. },
  72278. enumerable: true,
  72279. configurable: true
  72280. });
  72281. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadButtonStateChangedObservable", {
  72282. /**
  72283. * Fired when the touchpad button on this controller is modified
  72284. */
  72285. get: function () {
  72286. return this.onTrackpadChangedObservable;
  72287. },
  72288. enumerable: true,
  72289. configurable: true
  72290. });
  72291. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadValuesChangedObservable", {
  72292. /**
  72293. * Fired when the touchpad values on this controller are modified
  72294. */
  72295. get: function () {
  72296. return this.onTrackpadValuesChangedObservable;
  72297. },
  72298. enumerable: true,
  72299. configurable: true
  72300. });
  72301. /**
  72302. * Called once per frame by the engine.
  72303. */
  72304. WindowsMotionController.prototype.update = function () {
  72305. _super.prototype.update.call(this);
  72306. if (this.browserGamepad.axes) {
  72307. if (this.browserGamepad.axes[2] != this.trackpad.x || this.browserGamepad.axes[3] != this.trackpad.y) {
  72308. this.trackpad.x = this.browserGamepad["axes"][2];
  72309. this.trackpad.y = this.browserGamepad["axes"][3];
  72310. this.onTrackpadValuesChangedObservable.notifyObservers(this.trackpad);
  72311. }
  72312. // Only need to animate axes if there is a loaded mesh
  72313. if (this._loadedMeshInfo) {
  72314. for (var axis = 0; axis < this._mapping.axisMeshNames.length; axis++) {
  72315. this._lerpAxisTransform(axis, this.browserGamepad.axes[axis]);
  72316. }
  72317. }
  72318. }
  72319. };
  72320. /**
  72321. * Called once for each button that changed state since the last frame
  72322. * @param buttonIdx Which button index changed
  72323. * @param state New state of the button
  72324. * @param changes Which properties on the state changed since last frame
  72325. */
  72326. WindowsMotionController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  72327. var buttonName = this._mapping.buttons[buttonIdx];
  72328. if (!buttonName) {
  72329. return;
  72330. }
  72331. // Only emit events for buttons that we know how to map from index to name
  72332. var observable = this[(this._mapping.buttonObservableNames)[buttonName]];
  72333. if (observable) {
  72334. observable.notifyObservers(state);
  72335. }
  72336. this._lerpButtonTransform(buttonName, state.value);
  72337. };
  72338. /**
  72339. * Moves the buttons on the controller mesh based on their current state
  72340. * @param buttonName the name of the button to move
  72341. * @param buttonValue the value of the button which determines the buttons new position
  72342. */
  72343. WindowsMotionController.prototype._lerpButtonTransform = function (buttonName, buttonValue) {
  72344. // If there is no loaded mesh, there is nothing to transform.
  72345. if (!this._loadedMeshInfo) {
  72346. return;
  72347. }
  72348. var meshInfo = this._loadedMeshInfo.buttonMeshes[buttonName];
  72349. if (!meshInfo.unpressed.rotationQuaternion || !meshInfo.pressed.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  72350. return;
  72351. }
  72352. BABYLON.Quaternion.SlerpToRef(meshInfo.unpressed.rotationQuaternion, meshInfo.pressed.rotationQuaternion, buttonValue, meshInfo.value.rotationQuaternion);
  72353. BABYLON.Vector3.LerpToRef(meshInfo.unpressed.position, meshInfo.pressed.position, buttonValue, meshInfo.value.position);
  72354. };
  72355. /**
  72356. * Moves the axis on the controller mesh based on its current state
  72357. * @param axis the index of the axis
  72358. * @param axisValue the value of the axis which determines the meshes new position
  72359. * @hidden
  72360. */
  72361. WindowsMotionController.prototype._lerpAxisTransform = function (axis, axisValue) {
  72362. if (!this._loadedMeshInfo) {
  72363. return;
  72364. }
  72365. var meshInfo = this._loadedMeshInfo.axisMeshes[axis];
  72366. if (!meshInfo) {
  72367. return;
  72368. }
  72369. if (!meshInfo.min.rotationQuaternion || !meshInfo.max.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  72370. return;
  72371. }
  72372. // Convert from gamepad value range (-1 to +1) to lerp range (0 to 1)
  72373. var lerpValue = axisValue * 0.5 + 0.5;
  72374. BABYLON.Quaternion.SlerpToRef(meshInfo.min.rotationQuaternion, meshInfo.max.rotationQuaternion, lerpValue, meshInfo.value.rotationQuaternion);
  72375. BABYLON.Vector3.LerpToRef(meshInfo.min.position, meshInfo.max.position, lerpValue, meshInfo.value.position);
  72376. };
  72377. /**
  72378. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  72379. * @param scene scene in which to add meshes
  72380. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  72381. */
  72382. WindowsMotionController.prototype.initControllerMesh = function (scene, meshLoaded, forceDefault) {
  72383. var _this = this;
  72384. if (forceDefault === void 0) { forceDefault = false; }
  72385. var path;
  72386. var filename;
  72387. // Checking if GLB loader is present
  72388. if (BABYLON.SceneLoader.IsPluginForExtensionAvailable(".glb")) {
  72389. // Determine the device specific folder based on the ID suffix
  72390. var device = 'default';
  72391. if (this.id && !forceDefault) {
  72392. var match = this.id.match(WindowsMotionController.GAMEPAD_ID_PATTERN);
  72393. device = ((match && match[0]) || device);
  72394. }
  72395. // Hand
  72396. if (this.hand === 'left') {
  72397. filename = WindowsMotionController.MODEL_LEFT_FILENAME;
  72398. }
  72399. else { // Right is the default if no hand is specified
  72400. filename = WindowsMotionController.MODEL_RIGHT_FILENAME;
  72401. }
  72402. path = WindowsMotionController.MODEL_BASE_URL + device + '/';
  72403. }
  72404. else {
  72405. BABYLON.Tools.Warn("You need to reference GLTF loader to load Windows Motion Controllers model. Falling back to generic models");
  72406. path = BABYLON.GenericController.MODEL_BASE_URL;
  72407. filename = BABYLON.GenericController.MODEL_FILENAME;
  72408. }
  72409. BABYLON.SceneLoader.ImportMesh("", path, filename, scene, function (meshes) {
  72410. // glTF files successfully loaded from the remote server, now process them to ensure they are in the right format.
  72411. _this._loadedMeshInfo = _this.processModel(scene, meshes);
  72412. if (!_this._loadedMeshInfo) {
  72413. return;
  72414. }
  72415. _this._defaultModel = _this._loadedMeshInfo.rootNode;
  72416. _this.attachToMesh(_this._defaultModel);
  72417. if (meshLoaded) {
  72418. meshLoaded(_this._defaultModel);
  72419. }
  72420. }, null, function (scene, message) {
  72421. BABYLON.Tools.Log(message);
  72422. BABYLON.Tools.Warn('Failed to retrieve controller model from the remote server: ' + path + filename);
  72423. if (!forceDefault) {
  72424. _this.initControllerMesh(scene, meshLoaded, true);
  72425. }
  72426. });
  72427. };
  72428. /**
  72429. * Takes a list of meshes (as loaded from the glTF file) and finds the root node, as well as nodes that
  72430. * can be transformed by button presses and axes values, based on this._mapping.
  72431. *
  72432. * @param scene scene in which the meshes exist
  72433. * @param meshes list of meshes that make up the controller model to process
  72434. * @return structured view of the given meshes, with mapping of buttons and axes to meshes that can be transformed.
  72435. */
  72436. WindowsMotionController.prototype.processModel = function (scene, meshes) {
  72437. var loadedMeshInfo = null;
  72438. // Create a new mesh to contain the glTF hierarchy
  72439. var parentMesh = new BABYLON.Mesh(this.id + " " + this.hand, scene);
  72440. // Find the root node in the loaded glTF scene, and attach it as a child of 'parentMesh'
  72441. var childMesh = null;
  72442. for (var i = 0; i < meshes.length; i++) {
  72443. var mesh = meshes[i];
  72444. if (!mesh.parent) {
  72445. // Exclude controller meshes from picking results
  72446. mesh.isPickable = false;
  72447. // Handle root node, attach to the new parentMesh
  72448. childMesh = mesh;
  72449. break;
  72450. }
  72451. }
  72452. if (childMesh) {
  72453. childMesh.setParent(parentMesh);
  72454. // Create our mesh info. Note that this method will always return non-null.
  72455. loadedMeshInfo = this.createMeshInfo(parentMesh);
  72456. }
  72457. else {
  72458. BABYLON.Tools.Warn('Could not find root node in model file.');
  72459. }
  72460. return loadedMeshInfo;
  72461. };
  72462. WindowsMotionController.prototype.createMeshInfo = function (rootNode) {
  72463. var loadedMeshInfo = new LoadedMeshInfo();
  72464. var i;
  72465. loadedMeshInfo.rootNode = rootNode;
  72466. // Reset the caches
  72467. loadedMeshInfo.buttonMeshes = {};
  72468. loadedMeshInfo.axisMeshes = {};
  72469. // Button Meshes
  72470. for (i = 0; i < this._mapping.buttons.length; i++) {
  72471. var buttonMeshName = this._mapping.buttonMeshNames[this._mapping.buttons[i]];
  72472. if (!buttonMeshName) {
  72473. BABYLON.Tools.Log('Skipping unknown button at index: ' + i + ' with mapped name: ' + this._mapping.buttons[i]);
  72474. continue;
  72475. }
  72476. var buttonMesh = getChildByName(rootNode, buttonMeshName);
  72477. if (!buttonMesh) {
  72478. BABYLON.Tools.Warn('Missing button mesh with name: ' + buttonMeshName);
  72479. continue;
  72480. }
  72481. var buttonMeshInfo = {
  72482. index: i,
  72483. value: getImmediateChildByName(buttonMesh, 'VALUE'),
  72484. pressed: getImmediateChildByName(buttonMesh, 'PRESSED'),
  72485. unpressed: getImmediateChildByName(buttonMesh, 'UNPRESSED')
  72486. };
  72487. if (buttonMeshInfo.value && buttonMeshInfo.pressed && buttonMeshInfo.unpressed) {
  72488. loadedMeshInfo.buttonMeshes[this._mapping.buttons[i]] = buttonMeshInfo;
  72489. }
  72490. else {
  72491. // If we didn't find the mesh, it simply means this button won't have transforms applied as mapped button value changes.
  72492. BABYLON.Tools.Warn('Missing button submesh under mesh with name: ' + buttonMeshName +
  72493. '(VALUE: ' + !!buttonMeshInfo.value +
  72494. ', PRESSED: ' + !!buttonMeshInfo.pressed +
  72495. ', UNPRESSED:' + !!buttonMeshInfo.unpressed +
  72496. ')');
  72497. }
  72498. }
  72499. // Axis Meshes
  72500. for (i = 0; i < this._mapping.axisMeshNames.length; i++) {
  72501. var axisMeshName = this._mapping.axisMeshNames[i];
  72502. if (!axisMeshName) {
  72503. BABYLON.Tools.Log('Skipping unknown axis at index: ' + i);
  72504. continue;
  72505. }
  72506. var axisMesh = getChildByName(rootNode, axisMeshName);
  72507. if (!axisMesh) {
  72508. BABYLON.Tools.Warn('Missing axis mesh with name: ' + axisMeshName);
  72509. continue;
  72510. }
  72511. var axisMeshInfo = {
  72512. index: i,
  72513. value: getImmediateChildByName(axisMesh, 'VALUE'),
  72514. min: getImmediateChildByName(axisMesh, 'MIN'),
  72515. max: getImmediateChildByName(axisMesh, 'MAX')
  72516. };
  72517. if (axisMeshInfo.value && axisMeshInfo.min && axisMeshInfo.max) {
  72518. loadedMeshInfo.axisMeshes[i] = axisMeshInfo;
  72519. }
  72520. else {
  72521. // If we didn't find the mesh, it simply means thit axis won't have transforms applied as mapped axis values change.
  72522. BABYLON.Tools.Warn('Missing axis submesh under mesh with name: ' + axisMeshName +
  72523. '(VALUE: ' + !!axisMeshInfo.value +
  72524. ', MIN: ' + !!axisMeshInfo.min +
  72525. ', MAX:' + !!axisMeshInfo.max +
  72526. ')');
  72527. }
  72528. }
  72529. // Pointing Ray
  72530. loadedMeshInfo.pointingPoseNode = getChildByName(rootNode, this._mapping.pointingPoseMeshName);
  72531. if (!loadedMeshInfo.pointingPoseNode) {
  72532. BABYLON.Tools.Warn('Missing pointing pose mesh with name: ' + this._mapping.pointingPoseMeshName);
  72533. }
  72534. return loadedMeshInfo;
  72535. // Look through all children recursively. This will return null if no mesh exists with the given name.
  72536. function getChildByName(node, name) {
  72537. return node.getChildMeshes(false, function (n) { return n.name === name; })[0];
  72538. }
  72539. // Look through only immediate children. This will return null if no mesh exists with the given name.
  72540. function getImmediateChildByName(node, name) {
  72541. return node.getChildMeshes(true, function (n) { return n.name == name; })[0];
  72542. }
  72543. };
  72544. /**
  72545. * Gets the ray of the controller in the direction the controller is pointing
  72546. * @param length the length the resulting ray should be
  72547. * @returns a ray in the direction the controller is pointing
  72548. */
  72549. WindowsMotionController.prototype.getForwardRay = function (length) {
  72550. if (length === void 0) { length = 100; }
  72551. if (!(this._loadedMeshInfo && this._loadedMeshInfo.pointingPoseNode)) {
  72552. return _super.prototype.getForwardRay.call(this, length);
  72553. }
  72554. var m = this._loadedMeshInfo.pointingPoseNode.getWorldMatrix();
  72555. var origin = m.getTranslation();
  72556. var forward = new BABYLON.Vector3(0, 0, -1);
  72557. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  72558. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  72559. return new BABYLON.Ray(origin, direction, length);
  72560. };
  72561. /**
  72562. * Disposes of the controller
  72563. */
  72564. WindowsMotionController.prototype.dispose = function () {
  72565. _super.prototype.dispose.call(this);
  72566. this.onTrackpadChangedObservable.clear();
  72567. };
  72568. /**
  72569. * The base url used to load the left and right controller models
  72570. */
  72571. WindowsMotionController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/microsoft/';
  72572. /**
  72573. * The name of the left controller model file
  72574. */
  72575. WindowsMotionController.MODEL_LEFT_FILENAME = 'left.glb';
  72576. /**
  72577. * The name of the right controller model file
  72578. */
  72579. WindowsMotionController.MODEL_RIGHT_FILENAME = 'right.glb';
  72580. /**
  72581. * The controller name prefix for this controller type
  72582. */
  72583. WindowsMotionController.GAMEPAD_ID_PREFIX = 'Spatial Controller (Spatial Interaction Source) ';
  72584. /**
  72585. * The controller id pattern for this controller type
  72586. */
  72587. WindowsMotionController.GAMEPAD_ID_PATTERN = /([0-9a-zA-Z]+-[0-9a-zA-Z]+)$/;
  72588. return WindowsMotionController;
  72589. }(BABYLON.WebVRController));
  72590. BABYLON.WindowsMotionController = WindowsMotionController;
  72591. })(BABYLON || (BABYLON = {}));
  72592. //# sourceMappingURL=babylon.windowsMotionController.js.map
  72593. var BABYLON;
  72594. (function (BABYLON) {
  72595. /**
  72596. * Gear VR Controller
  72597. */
  72598. var GearVRController = /** @class */ (function (_super) {
  72599. __extends(GearVRController, _super);
  72600. /**
  72601. * Creates a new GearVRController from a gamepad
  72602. * @param vrGamepad the gamepad that the controller should be created from
  72603. */
  72604. function GearVRController(vrGamepad) {
  72605. var _this = _super.call(this, vrGamepad) || this;
  72606. _this._buttonIndexToObservableNameMap = [
  72607. 'onTrackpadChangedObservable',
  72608. 'onTriggerStateChangedObservable' // Trigger
  72609. ];
  72610. _this.controllerType = BABYLON.PoseEnabledControllerType.GEAR_VR;
  72611. // Initial starting position defaults to where hand would be (incase of only 3dof controller)
  72612. _this._calculatedPosition = new BABYLON.Vector3(_this.hand == "left" ? -0.15 : 0.15, -0.5, 0.4);
  72613. return _this;
  72614. }
  72615. /**
  72616. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  72617. * @param scene scene in which to add meshes
  72618. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  72619. */
  72620. GearVRController.prototype.initControllerMesh = function (scene, meshLoaded) {
  72621. var _this = this;
  72622. BABYLON.SceneLoader.ImportMesh("", GearVRController.MODEL_BASE_URL, GearVRController.MODEL_FILENAME, scene, function (newMeshes) {
  72623. _this._defaultModel = newMeshes[1];
  72624. _this.attachToMesh(_this._defaultModel);
  72625. if (meshLoaded) {
  72626. meshLoaded(_this._defaultModel);
  72627. }
  72628. });
  72629. };
  72630. /**
  72631. * Called once for each button that changed state since the last frame
  72632. * @param buttonIdx Which button index changed
  72633. * @param state New state of the button
  72634. * @param changes Which properties on the state changed since last frame
  72635. */
  72636. GearVRController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  72637. if (buttonIdx < this._buttonIndexToObservableNameMap.length) {
  72638. var observableName = this._buttonIndexToObservableNameMap[buttonIdx];
  72639. // Only emit events for buttons that we know how to map from index to observable
  72640. var observable = this[observableName];
  72641. if (observable) {
  72642. observable.notifyObservers(state);
  72643. }
  72644. }
  72645. };
  72646. /**
  72647. * Base Url for the controller model.
  72648. */
  72649. GearVRController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  72650. /**
  72651. * File name for the controller model.
  72652. */
  72653. GearVRController.MODEL_FILENAME = 'generic.babylon';
  72654. /**
  72655. * Gamepad Id prefix used to identify this controller.
  72656. */
  72657. GearVRController.GAMEPAD_ID_PREFIX = 'Gear VR'; // id is 'Gear VR Controller'
  72658. return GearVRController;
  72659. }(BABYLON.WebVRController));
  72660. BABYLON.GearVRController = GearVRController;
  72661. })(BABYLON || (BABYLON = {}));
  72662. //# sourceMappingURL=babylon.gearVRController.js.map
  72663. var BABYLON;
  72664. (function (BABYLON) {
  72665. /**
  72666. * Google Daydream controller
  72667. */
  72668. var DaydreamController = /** @class */ (function (_super) {
  72669. __extends(DaydreamController, _super);
  72670. /**
  72671. * Creates a new DaydreamController from a gamepad
  72672. * @param vrGamepad the gamepad that the controller should be created from
  72673. */
  72674. function DaydreamController(vrGamepad) {
  72675. var _this = _super.call(this, vrGamepad) || this;
  72676. _this.controllerType = BABYLON.PoseEnabledControllerType.DAYDREAM;
  72677. return _this;
  72678. }
  72679. /**
  72680. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  72681. * @param scene scene in which to add meshes
  72682. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  72683. */
  72684. DaydreamController.prototype.initControllerMesh = function (scene, meshLoaded) {
  72685. var _this = this;
  72686. BABYLON.SceneLoader.ImportMesh("", DaydreamController.MODEL_BASE_URL, DaydreamController.MODEL_FILENAME, scene, function (newMeshes) {
  72687. _this._defaultModel = newMeshes[1];
  72688. _this.attachToMesh(_this._defaultModel);
  72689. if (meshLoaded) {
  72690. meshLoaded(_this._defaultModel);
  72691. }
  72692. });
  72693. };
  72694. /**
  72695. * Called once for each button that changed state since the last frame
  72696. * @param buttonIdx Which button index changed
  72697. * @param state New state of the button
  72698. * @param changes Which properties on the state changed since last frame
  72699. */
  72700. DaydreamController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  72701. // Daydream controller only has 1 GamepadButton (on the trackpad).
  72702. if (buttonIdx === 0) {
  72703. var observable = this.onTriggerStateChangedObservable;
  72704. if (observable) {
  72705. observable.notifyObservers(state);
  72706. }
  72707. }
  72708. else {
  72709. // If the app or home buttons are ever made available
  72710. BABYLON.Tools.Warn("Unrecognized Daydream button index: " + buttonIdx);
  72711. }
  72712. };
  72713. /**
  72714. * Base Url for the controller model.
  72715. */
  72716. DaydreamController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  72717. /**
  72718. * File name for the controller model.
  72719. */
  72720. DaydreamController.MODEL_FILENAME = 'generic.babylon';
  72721. /**
  72722. * Gamepad Id prefix used to identify Daydream Controller.
  72723. */
  72724. DaydreamController.GAMEPAD_ID_PREFIX = 'Daydream'; // id is 'Daydream Controller'
  72725. return DaydreamController;
  72726. }(BABYLON.WebVRController));
  72727. BABYLON.DaydreamController = DaydreamController;
  72728. })(BABYLON || (BABYLON = {}));
  72729. //# sourceMappingURL=babylon.daydreamController.js.map
  72730. var BABYLON;
  72731. (function (BABYLON) {
  72732. var FollowCamera = /** @class */ (function (_super) {
  72733. __extends(FollowCamera, _super);
  72734. function FollowCamera(name, position, scene, lockedTarget) {
  72735. if (lockedTarget === void 0) { lockedTarget = null; }
  72736. var _this = _super.call(this, name, position, scene) || this;
  72737. _this.radius = 12;
  72738. _this.rotationOffset = 0;
  72739. _this.heightOffset = 4;
  72740. _this.cameraAcceleration = 0.05;
  72741. _this.maxCameraSpeed = 20;
  72742. _this.lockedTarget = lockedTarget;
  72743. return _this;
  72744. }
  72745. FollowCamera.prototype.getRadians = function (degrees) {
  72746. return degrees * Math.PI / 180;
  72747. };
  72748. FollowCamera.prototype.follow = function (cameraTarget) {
  72749. if (!cameraTarget)
  72750. return;
  72751. var yRotation;
  72752. if (cameraTarget.rotationQuaternion) {
  72753. var rotMatrix = new BABYLON.Matrix();
  72754. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  72755. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  72756. }
  72757. else {
  72758. yRotation = cameraTarget.rotation.y;
  72759. }
  72760. var radians = this.getRadians(this.rotationOffset) + yRotation;
  72761. var targetPosition = cameraTarget.getAbsolutePosition();
  72762. var targetX = targetPosition.x + Math.sin(radians) * this.radius;
  72763. var targetZ = targetPosition.z + Math.cos(radians) * this.radius;
  72764. var dx = targetX - this.position.x;
  72765. var dy = (targetPosition.y + this.heightOffset) - this.position.y;
  72766. var dz = (targetZ) - this.position.z;
  72767. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  72768. var vy = dy * this.cameraAcceleration;
  72769. var vz = dz * this.cameraAcceleration * 2;
  72770. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  72771. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  72772. }
  72773. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  72774. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  72775. }
  72776. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  72777. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  72778. }
  72779. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  72780. this.setTarget(targetPosition);
  72781. };
  72782. FollowCamera.prototype._checkInputs = function () {
  72783. _super.prototype._checkInputs.call(this);
  72784. if (this.lockedTarget) {
  72785. this.follow(this.lockedTarget);
  72786. }
  72787. };
  72788. FollowCamera.prototype.getClassName = function () {
  72789. return "FollowCamera";
  72790. };
  72791. __decorate([
  72792. BABYLON.serialize()
  72793. ], FollowCamera.prototype, "radius", void 0);
  72794. __decorate([
  72795. BABYLON.serialize()
  72796. ], FollowCamera.prototype, "rotationOffset", void 0);
  72797. __decorate([
  72798. BABYLON.serialize()
  72799. ], FollowCamera.prototype, "heightOffset", void 0);
  72800. __decorate([
  72801. BABYLON.serialize()
  72802. ], FollowCamera.prototype, "cameraAcceleration", void 0);
  72803. __decorate([
  72804. BABYLON.serialize()
  72805. ], FollowCamera.prototype, "maxCameraSpeed", void 0);
  72806. __decorate([
  72807. BABYLON.serializeAsMeshReference("lockedTargetId")
  72808. ], FollowCamera.prototype, "lockedTarget", void 0);
  72809. return FollowCamera;
  72810. }(BABYLON.TargetCamera));
  72811. BABYLON.FollowCamera = FollowCamera;
  72812. var ArcFollowCamera = /** @class */ (function (_super) {
  72813. __extends(ArcFollowCamera, _super);
  72814. function ArcFollowCamera(name, alpha, beta, radius, target, scene) {
  72815. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  72816. _this.alpha = alpha;
  72817. _this.beta = beta;
  72818. _this.radius = radius;
  72819. _this.target = target;
  72820. _this._cartesianCoordinates = BABYLON.Vector3.Zero();
  72821. _this.follow();
  72822. return _this;
  72823. }
  72824. ArcFollowCamera.prototype.follow = function () {
  72825. if (!this.target) {
  72826. return;
  72827. }
  72828. this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);
  72829. this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);
  72830. this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);
  72831. var targetPosition = this.target.getAbsolutePosition();
  72832. this.position = targetPosition.add(this._cartesianCoordinates);
  72833. this.setTarget(targetPosition);
  72834. };
  72835. ArcFollowCamera.prototype._checkInputs = function () {
  72836. _super.prototype._checkInputs.call(this);
  72837. this.follow();
  72838. };
  72839. ArcFollowCamera.prototype.getClassName = function () {
  72840. return "ArcFollowCamera";
  72841. };
  72842. return ArcFollowCamera;
  72843. }(BABYLON.TargetCamera));
  72844. BABYLON.ArcFollowCamera = ArcFollowCamera;
  72845. })(BABYLON || (BABYLON = {}));
  72846. //# sourceMappingURL=babylon.followCamera.js.map
  72847. var BABYLON;
  72848. (function (BABYLON) {
  72849. // We're mainly based on the logic defined into the FreeCamera code
  72850. var UniversalCamera = /** @class */ (function (_super) {
  72851. __extends(UniversalCamera, _super);
  72852. //-- end properties for backward compatibility for inputs
  72853. function UniversalCamera(name, position, scene) {
  72854. var _this = _super.call(this, name, position, scene) || this;
  72855. _this.inputs.addGamepad();
  72856. return _this;
  72857. }
  72858. Object.defineProperty(UniversalCamera.prototype, "gamepadAngularSensibility", {
  72859. //-- Begin properties for backward compatibility for inputs
  72860. get: function () {
  72861. var gamepad = this.inputs.attached["gamepad"];
  72862. if (gamepad)
  72863. return gamepad.gamepadAngularSensibility;
  72864. return 0;
  72865. },
  72866. set: function (value) {
  72867. var gamepad = this.inputs.attached["gamepad"];
  72868. if (gamepad)
  72869. gamepad.gamepadAngularSensibility = value;
  72870. },
  72871. enumerable: true,
  72872. configurable: true
  72873. });
  72874. Object.defineProperty(UniversalCamera.prototype, "gamepadMoveSensibility", {
  72875. get: function () {
  72876. var gamepad = this.inputs.attached["gamepad"];
  72877. if (gamepad)
  72878. return gamepad.gamepadMoveSensibility;
  72879. return 0;
  72880. },
  72881. set: function (value) {
  72882. var gamepad = this.inputs.attached["gamepad"];
  72883. if (gamepad)
  72884. gamepad.gamepadMoveSensibility = value;
  72885. },
  72886. enumerable: true,
  72887. configurable: true
  72888. });
  72889. UniversalCamera.prototype.getClassName = function () {
  72890. return "UniversalCamera";
  72891. };
  72892. return UniversalCamera;
  72893. }(BABYLON.TouchCamera));
  72894. BABYLON.UniversalCamera = UniversalCamera;
  72895. })(BABYLON || (BABYLON = {}));
  72896. //# sourceMappingURL=babylon.universalCamera.js.map
  72897. var BABYLON;
  72898. (function (BABYLON) {
  72899. // We're mainly based on the logic defined into the FreeCamera code
  72900. var GamepadCamera = /** @class */ (function (_super) {
  72901. __extends(GamepadCamera, _super);
  72902. //-- end properties for backward compatibility for inputs
  72903. function GamepadCamera(name, position, scene) {
  72904. return _super.call(this, name, position, scene) || this;
  72905. }
  72906. Object.defineProperty(GamepadCamera.prototype, "gamepadAngularSensibility", {
  72907. //-- Begin properties for backward compatibility for inputs
  72908. get: function () {
  72909. var gamepad = this.inputs.attached["gamepad"];
  72910. if (gamepad)
  72911. return gamepad.gamepadAngularSensibility;
  72912. return 0;
  72913. },
  72914. set: function (value) {
  72915. var gamepad = this.inputs.attached["gamepad"];
  72916. if (gamepad)
  72917. gamepad.gamepadAngularSensibility = value;
  72918. },
  72919. enumerable: true,
  72920. configurable: true
  72921. });
  72922. Object.defineProperty(GamepadCamera.prototype, "gamepadMoveSensibility", {
  72923. get: function () {
  72924. var gamepad = this.inputs.attached["gamepad"];
  72925. if (gamepad)
  72926. return gamepad.gamepadMoveSensibility;
  72927. return 0;
  72928. },
  72929. set: function (value) {
  72930. var gamepad = this.inputs.attached["gamepad"];
  72931. if (gamepad)
  72932. gamepad.gamepadMoveSensibility = value;
  72933. },
  72934. enumerable: true,
  72935. configurable: true
  72936. });
  72937. GamepadCamera.prototype.getClassName = function () {
  72938. return "GamepadCamera";
  72939. };
  72940. return GamepadCamera;
  72941. }(BABYLON.UniversalCamera));
  72942. BABYLON.GamepadCamera = GamepadCamera;
  72943. })(BABYLON || (BABYLON = {}));
  72944. //# sourceMappingURL=babylon.gamepadCamera.js.map
  72945. var BABYLON;
  72946. (function (BABYLON) {
  72947. var PostProcessRenderPipelineManager = /** @class */ (function () {
  72948. function PostProcessRenderPipelineManager() {
  72949. this._renderPipelines = {};
  72950. }
  72951. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  72952. this._renderPipelines[renderPipeline._name] = renderPipeline;
  72953. };
  72954. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  72955. if (unique === void 0) { unique = false; }
  72956. var renderPipeline = this._renderPipelines[renderPipelineName];
  72957. if (!renderPipeline) {
  72958. return;
  72959. }
  72960. renderPipeline._attachCameras(cameras, unique);
  72961. };
  72962. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  72963. var renderPipeline = this._renderPipelines[renderPipelineName];
  72964. if (!renderPipeline) {
  72965. return;
  72966. }
  72967. renderPipeline._detachCameras(cameras);
  72968. };
  72969. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  72970. var renderPipeline = this._renderPipelines[renderPipelineName];
  72971. if (!renderPipeline) {
  72972. return;
  72973. }
  72974. renderPipeline._enableEffect(renderEffectName, cameras);
  72975. };
  72976. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  72977. var renderPipeline = this._renderPipelines[renderPipelineName];
  72978. if (!renderPipeline) {
  72979. return;
  72980. }
  72981. renderPipeline._disableEffect(renderEffectName, cameras);
  72982. };
  72983. PostProcessRenderPipelineManager.prototype.update = function () {
  72984. for (var renderPipelineName in this._renderPipelines) {
  72985. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  72986. var pipeline = this._renderPipelines[renderPipelineName];
  72987. if (!pipeline.isSupported) {
  72988. pipeline.dispose();
  72989. delete this._renderPipelines[renderPipelineName];
  72990. }
  72991. else {
  72992. pipeline._update();
  72993. }
  72994. }
  72995. }
  72996. };
  72997. PostProcessRenderPipelineManager.prototype._rebuild = function () {
  72998. for (var renderPipelineName in this._renderPipelines) {
  72999. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  73000. var pipeline = this._renderPipelines[renderPipelineName];
  73001. pipeline._rebuild();
  73002. }
  73003. }
  73004. };
  73005. PostProcessRenderPipelineManager.prototype.dispose = function () {
  73006. for (var renderPipelineName in this._renderPipelines) {
  73007. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  73008. var pipeline = this._renderPipelines[renderPipelineName];
  73009. pipeline.dispose();
  73010. }
  73011. }
  73012. };
  73013. return PostProcessRenderPipelineManager;
  73014. }());
  73015. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  73016. })(BABYLON || (BABYLON = {}));
  73017. //# sourceMappingURL=babylon.postProcessRenderPipelineManager.js.map
  73018. var BABYLON;
  73019. (function (BABYLON) {
  73020. /**
  73021. * This represents a set of one or more post processes in Babylon.
  73022. * A post process can be used to apply a shader to a texture after it is rendered.
  73023. * @example https://doc.babylonjs.com/how_to/how_to_use_postprocessrenderpipeline
  73024. */
  73025. var PostProcessRenderEffect = /** @class */ (function () {
  73026. /**
  73027. * Instantiates a post process render effect.
  73028. * A post process can be used to apply a shader to a texture after it is rendered.
  73029. * @param engine The engine the effect is tied to
  73030. * @param name The name of the effect
  73031. * @param getPostProcesses A function that returns a set of post processes which the effect will run in order to be run.
  73032. * @param singleInstance False if this post process can be run on multiple cameras. (default: true)
  73033. */
  73034. function PostProcessRenderEffect(engine, name, getPostProcesses, singleInstance) {
  73035. this._name = name;
  73036. this._singleInstance = singleInstance || true;
  73037. this._getPostProcesses = getPostProcesses;
  73038. this._cameras = {};
  73039. this._indicesForCamera = {};
  73040. this._postProcesses = {};
  73041. }
  73042. Object.defineProperty(PostProcessRenderEffect.prototype, "isSupported", {
  73043. /**
  73044. * Checks if all the post processes in the effect are supported.
  73045. */
  73046. get: function () {
  73047. for (var index in this._postProcesses) {
  73048. if (this._postProcesses.hasOwnProperty(index)) {
  73049. var pps = this._postProcesses[index];
  73050. for (var ppIndex = 0; ppIndex < pps.length; ppIndex++) {
  73051. if (!pps[ppIndex].isSupported) {
  73052. return false;
  73053. }
  73054. }
  73055. }
  73056. }
  73057. return true;
  73058. },
  73059. enumerable: true,
  73060. configurable: true
  73061. });
  73062. /**
  73063. * Updates the current state of the effect
  73064. */
  73065. PostProcessRenderEffect.prototype._update = function () {
  73066. };
  73067. /**
  73068. * Attaches the effect on cameras
  73069. * @param cameras The camera to attach to.
  73070. */
  73071. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  73072. var _this = this;
  73073. var cameraKey;
  73074. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  73075. if (!cams) {
  73076. return;
  73077. }
  73078. for (var i = 0; i < cams.length; i++) {
  73079. var camera = cams[i];
  73080. var cameraName = camera.name;
  73081. if (this._singleInstance) {
  73082. cameraKey = 0;
  73083. }
  73084. else {
  73085. cameraKey = cameraName;
  73086. }
  73087. if (!this._postProcesses[cameraKey]) {
  73088. var postProcess = this._getPostProcesses();
  73089. if (postProcess) {
  73090. this._postProcesses[cameraKey] = Array.isArray(postProcess) ? postProcess : [postProcess];
  73091. }
  73092. }
  73093. if (!this._indicesForCamera[cameraName]) {
  73094. this._indicesForCamera[cameraName] = [];
  73095. }
  73096. this._postProcesses[cameraKey].forEach(function (postProcess) {
  73097. var index = camera.attachPostProcess(postProcess);
  73098. _this._indicesForCamera[cameraName].push(index);
  73099. });
  73100. if (!this._cameras[cameraName]) {
  73101. this._cameras[cameraName] = camera;
  73102. }
  73103. }
  73104. };
  73105. /**
  73106. * Detatches the effect on cameras
  73107. * @param cameras The camera to detatch from.
  73108. */
  73109. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  73110. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  73111. if (!cams) {
  73112. return;
  73113. }
  73114. for (var i = 0; i < cams.length; i++) {
  73115. var camera = cams[i];
  73116. var cameraName = camera.name;
  73117. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  73118. camera.detachPostProcess(postProcess);
  73119. });
  73120. if (this._cameras[cameraName]) {
  73121. //this._indicesForCamera.splice(index, 1);
  73122. this._cameras[cameraName] = null;
  73123. }
  73124. }
  73125. };
  73126. /**
  73127. * Enables the effect on given cameras
  73128. * @param cameras The camera to enable.
  73129. */
  73130. PostProcessRenderEffect.prototype._enable = function (cameras) {
  73131. var _this = this;
  73132. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  73133. if (!cams) {
  73134. return;
  73135. }
  73136. for (var i = 0; i < cams.length; i++) {
  73137. var camera = cams[i];
  73138. var cameraName = camera.name;
  73139. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  73140. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined || camera._postProcesses[this._indicesForCamera[cameraName][j]] === null) {
  73141. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  73142. cams[i].attachPostProcess(postProcess, _this._indicesForCamera[cameraName][j]);
  73143. });
  73144. }
  73145. }
  73146. }
  73147. };
  73148. /**
  73149. * Disables the effect on the given cameras
  73150. * @param cameras The camera to disable.
  73151. */
  73152. PostProcessRenderEffect.prototype._disable = function (cameras) {
  73153. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  73154. if (!cams) {
  73155. return;
  73156. }
  73157. for (var i = 0; i < cams.length; i++) {
  73158. var camera = cams[i];
  73159. var cameraName = camera.name;
  73160. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  73161. camera.detachPostProcess(postProcess);
  73162. });
  73163. }
  73164. };
  73165. /**
  73166. * Gets a list of the post processes contained in the effect.
  73167. * @param camera The camera to get the post processes on.
  73168. * @returns The list of the post processes in the effect.
  73169. */
  73170. PostProcessRenderEffect.prototype.getPostProcesses = function (camera) {
  73171. if (this._singleInstance) {
  73172. return this._postProcesses[0];
  73173. }
  73174. else {
  73175. if (!camera) {
  73176. return null;
  73177. }
  73178. return this._postProcesses[camera.name];
  73179. }
  73180. };
  73181. return PostProcessRenderEffect;
  73182. }());
  73183. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  73184. })(BABYLON || (BABYLON = {}));
  73185. //# sourceMappingURL=babylon.postProcessRenderEffect.js.map
  73186. var BABYLON;
  73187. (function (BABYLON) {
  73188. var PostProcessRenderPipeline = /** @class */ (function () {
  73189. function PostProcessRenderPipeline(engine, name) {
  73190. this.engine = engine;
  73191. this._name = name;
  73192. this._renderEffects = {};
  73193. this._renderEffectsForIsolatedPass = new Array();
  73194. this._cameras = [];
  73195. }
  73196. PostProcessRenderPipeline.prototype.getClassName = function () {
  73197. return "PostProcessRenderPipeline";
  73198. };
  73199. Object.defineProperty(PostProcessRenderPipeline.prototype, "isSupported", {
  73200. get: function () {
  73201. for (var renderEffectName in this._renderEffects) {
  73202. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  73203. if (!this._renderEffects[renderEffectName].isSupported) {
  73204. return false;
  73205. }
  73206. }
  73207. }
  73208. return true;
  73209. },
  73210. enumerable: true,
  73211. configurable: true
  73212. });
  73213. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  73214. this._renderEffects[renderEffect._name] = renderEffect;
  73215. };
  73216. // private
  73217. PostProcessRenderPipeline.prototype._rebuild = function () {
  73218. };
  73219. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  73220. var renderEffects = this._renderEffects[renderEffectName];
  73221. if (!renderEffects) {
  73222. return;
  73223. }
  73224. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  73225. };
  73226. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  73227. var renderEffects = this._renderEffects[renderEffectName];
  73228. if (!renderEffects) {
  73229. return;
  73230. }
  73231. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  73232. };
  73233. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  73234. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  73235. if (!cams) {
  73236. return;
  73237. }
  73238. var indicesToDelete = [];
  73239. var i;
  73240. for (i = 0; i < cams.length; i++) {
  73241. var camera = cams[i];
  73242. var cameraName = camera.name;
  73243. if (this._cameras.indexOf(camera) === -1) {
  73244. this._cameras[cameraName] = camera;
  73245. }
  73246. else if (unique) {
  73247. indicesToDelete.push(i);
  73248. }
  73249. }
  73250. for (i = 0; i < indicesToDelete.length; i++) {
  73251. cameras.splice(indicesToDelete[i], 1);
  73252. }
  73253. for (var renderEffectName in this._renderEffects) {
  73254. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  73255. this._renderEffects[renderEffectName]._attachCameras(cams);
  73256. }
  73257. }
  73258. };
  73259. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  73260. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  73261. if (!cams) {
  73262. return;
  73263. }
  73264. for (var renderEffectName in this._renderEffects) {
  73265. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  73266. this._renderEffects[renderEffectName]._detachCameras(cams);
  73267. }
  73268. }
  73269. for (var i = 0; i < cams.length; i++) {
  73270. this._cameras.splice(this._cameras.indexOf(cams[i]), 1);
  73271. }
  73272. };
  73273. PostProcessRenderPipeline.prototype._update = function () {
  73274. for (var renderEffectName in this._renderEffects) {
  73275. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  73276. this._renderEffects[renderEffectName]._update();
  73277. }
  73278. }
  73279. for (var i = 0; i < this._cameras.length; i++) {
  73280. var cameraName = this._cameras[i].name;
  73281. if (this._renderEffectsForIsolatedPass[cameraName]) {
  73282. this._renderEffectsForIsolatedPass[cameraName]._update();
  73283. }
  73284. }
  73285. };
  73286. PostProcessRenderPipeline.prototype._reset = function () {
  73287. this._renderEffects = {};
  73288. this._renderEffectsForIsolatedPass = new Array();
  73289. };
  73290. PostProcessRenderPipeline.prototype._enableMSAAOnFirstPostProcess = function (sampleCount) {
  73291. // 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)
  73292. var effectKeys = Object.keys(this._renderEffects);
  73293. if (this.engine.webGLVersion >= 2 && effectKeys.length > 0) {
  73294. var postProcesses = this._renderEffects[effectKeys[0]].getPostProcesses();
  73295. if (postProcesses) {
  73296. postProcesses[0].samples = sampleCount;
  73297. return true;
  73298. }
  73299. }
  73300. return false;
  73301. };
  73302. PostProcessRenderPipeline.prototype.dispose = function () {
  73303. // Must be implemented by children
  73304. };
  73305. __decorate([
  73306. BABYLON.serialize()
  73307. ], PostProcessRenderPipeline.prototype, "_name", void 0);
  73308. return PostProcessRenderPipeline;
  73309. }());
  73310. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  73311. })(BABYLON || (BABYLON = {}));
  73312. //# sourceMappingURL=babylon.postProcessRenderPipeline.js.map
  73313. var BABYLON;
  73314. (function (BABYLON) {
  73315. /**
  73316. * This represents a depth renderer in Babylon.
  73317. * A depth renderer will render to it's depth map every frame which can be displayed or used in post processing
  73318. */
  73319. var DepthRenderer = /** @class */ (function () {
  73320. /**
  73321. * Instantiates a depth renderer
  73322. * @param scene The scene the renderer belongs to
  73323. * @param type The texture type of the depth map (default: Engine.TEXTURETYPE_FLOAT)
  73324. * @param camera The camera to be used to render the depth map (default: scene's active camera)
  73325. */
  73326. function DepthRenderer(scene, type, camera) {
  73327. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  73328. if (camera === void 0) { camera = null; }
  73329. var _this = this;
  73330. this._scene = scene;
  73331. this._camera = camera;
  73332. var engine = scene.getEngine();
  73333. // Render target
  73334. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  73335. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  73336. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  73337. this._depthMap.refreshRate = 1;
  73338. this._depthMap.renderParticles = false;
  73339. this._depthMap.renderList = null;
  73340. // Camera to get depth map from to support multiple concurrent cameras
  73341. this._depthMap.activeCamera = this._camera;
  73342. this._depthMap.ignoreCameraViewport = true;
  73343. this._depthMap.useCameraPostProcesses = false;
  73344. // set default depth value to 1.0 (far away)
  73345. this._depthMap.onClearObservable.add(function (engine) {
  73346. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  73347. });
  73348. // Custom render function
  73349. var renderSubMesh = function (subMesh) {
  73350. var mesh = subMesh.getRenderingMesh();
  73351. var scene = _this._scene;
  73352. var engine = scene.getEngine();
  73353. var material = subMesh.getMaterial();
  73354. if (!material) {
  73355. return;
  73356. }
  73357. // Culling and reverse (right handed system)
  73358. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  73359. // Managing instances
  73360. var batch = mesh._getInstancesRenderList(subMesh._id);
  73361. if (batch.mustReturn) {
  73362. return;
  73363. }
  73364. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  73365. var camera = _this._camera || scene.activeCamera;
  73366. if (_this.isReady(subMesh, hardwareInstancedRendering) && camera) {
  73367. engine.enableEffect(_this._effect);
  73368. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  73369. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  73370. _this._effect.setFloat2("depthValues", camera.minZ, camera.minZ + camera.maxZ);
  73371. // Alpha test
  73372. if (material && material.needAlphaTesting()) {
  73373. var alphaTexture = material.getAlphaTestTexture();
  73374. if (alphaTexture) {
  73375. _this._effect.setTexture("diffuseSampler", alphaTexture);
  73376. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  73377. }
  73378. }
  73379. // Bones
  73380. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  73381. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  73382. }
  73383. // Draw
  73384. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  73385. }
  73386. };
  73387. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  73388. var index;
  73389. if (depthOnlySubMeshes.length) {
  73390. engine.setColorWrite(false);
  73391. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  73392. renderSubMesh(depthOnlySubMeshes.data[index]);
  73393. }
  73394. engine.setColorWrite(true);
  73395. }
  73396. for (index = 0; index < opaqueSubMeshes.length; index++) {
  73397. renderSubMesh(opaqueSubMeshes.data[index]);
  73398. }
  73399. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  73400. renderSubMesh(alphaTestSubMeshes.data[index]);
  73401. }
  73402. };
  73403. }
  73404. /**
  73405. * Creates the depth rendering effect and checks if the effect is ready.
  73406. * @param subMesh The submesh to be used to render the depth map of
  73407. * @param useInstances If multiple world instances should be used
  73408. * @returns if the depth renderer is ready to render the depth map
  73409. */
  73410. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  73411. var material = subMesh.getMaterial();
  73412. if (material.disableDepthWrite) {
  73413. return false;
  73414. }
  73415. var defines = [];
  73416. var attribs = [BABYLON.VertexBuffer.PositionKind];
  73417. var mesh = subMesh.getMesh();
  73418. // Alpha test
  73419. if (material && material.needAlphaTesting() && material.getAlphaTestTexture()) {
  73420. defines.push("#define ALPHATEST");
  73421. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  73422. attribs.push(BABYLON.VertexBuffer.UVKind);
  73423. defines.push("#define UV1");
  73424. }
  73425. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  73426. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  73427. defines.push("#define UV2");
  73428. }
  73429. }
  73430. // Bones
  73431. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  73432. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  73433. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  73434. if (mesh.numBoneInfluencers > 4) {
  73435. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  73436. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  73437. }
  73438. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  73439. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  73440. }
  73441. else {
  73442. defines.push("#define NUM_BONE_INFLUENCERS 0");
  73443. }
  73444. // Instances
  73445. if (useInstances) {
  73446. defines.push("#define INSTANCES");
  73447. attribs.push("world0");
  73448. attribs.push("world1");
  73449. attribs.push("world2");
  73450. attribs.push("world3");
  73451. }
  73452. // Get correct effect
  73453. var join = defines.join("\n");
  73454. if (this._cachedDefines !== join) {
  73455. this._cachedDefines = join;
  73456. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "depthValues"], ["diffuseSampler"], join);
  73457. }
  73458. return this._effect.isReady();
  73459. };
  73460. /**
  73461. * Gets the texture which the depth map will be written to.
  73462. * @returns The depth map texture
  73463. */
  73464. DepthRenderer.prototype.getDepthMap = function () {
  73465. return this._depthMap;
  73466. };
  73467. /**
  73468. * Disposes of the depth renderer.
  73469. */
  73470. DepthRenderer.prototype.dispose = function () {
  73471. this._depthMap.dispose();
  73472. };
  73473. return DepthRenderer;
  73474. }());
  73475. BABYLON.DepthRenderer = DepthRenderer;
  73476. })(BABYLON || (BABYLON = {}));
  73477. //# sourceMappingURL=babylon.depthRenderer.js.map
  73478. var BABYLON;
  73479. (function (BABYLON) {
  73480. var SSAORenderingPipeline = /** @class */ (function (_super) {
  73481. __extends(SSAORenderingPipeline, _super);
  73482. /**
  73483. * @constructor
  73484. * @param {string} name - The rendering pipeline name
  73485. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  73486. * @param {any} ratio - The size of the postprocesses. Can be a number shared between passes or an object for more precision: { ssaoRatio: 0.5, combineRatio: 1.0 }
  73487. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  73488. */
  73489. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  73490. var _this = _super.call(this, scene.getEngine(), name) || this;
  73491. // Members
  73492. /**
  73493. * The PassPostProcess id in the pipeline that contains the original scene color
  73494. */
  73495. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  73496. /**
  73497. * The SSAO PostProcess id in the pipeline
  73498. */
  73499. _this.SSAORenderEffect = "SSAORenderEffect";
  73500. /**
  73501. * The horizontal blur PostProcess id in the pipeline
  73502. */
  73503. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  73504. /**
  73505. * The vertical blur PostProcess id in the pipeline
  73506. */
  73507. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  73508. /**
  73509. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  73510. */
  73511. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  73512. /**
  73513. * The output strength of the SSAO post-process. Default value is 1.0.
  73514. */
  73515. _this.totalStrength = 1.0;
  73516. /**
  73517. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0006
  73518. */
  73519. _this.radius = 0.0001;
  73520. /**
  73521. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  73522. * Must not be equal to fallOff and superior to fallOff.
  73523. * Default value is 0.975
  73524. */
  73525. _this.area = 0.0075;
  73526. /**
  73527. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  73528. * Must not be equal to area and inferior to area.
  73529. * Default value is 0.0
  73530. */
  73531. _this.fallOff = 0.000001;
  73532. /**
  73533. * The base color of the SSAO post-process
  73534. * The final result is "base + ssao" between [0, 1]
  73535. */
  73536. _this.base = 0.5;
  73537. _this._firstUpdate = true;
  73538. _this._scene = scene;
  73539. // Set up assets
  73540. _this._createRandomTexture();
  73541. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  73542. var ssaoRatio = ratio.ssaoRatio || ratio;
  73543. var combineRatio = ratio.combineRatio || ratio;
  73544. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  73545. _this._createSSAOPostProcess(ssaoRatio);
  73546. _this._createBlurPostProcess(ssaoRatio);
  73547. _this._createSSAOCombinePostProcess(combineRatio);
  73548. // Set up pipeline
  73549. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  73550. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  73551. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  73552. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  73553. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  73554. // Finish
  73555. scene.postProcessRenderPipelineManager.addPipeline(_this);
  73556. if (cameras)
  73557. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  73558. return _this;
  73559. }
  73560. // Public Methods
  73561. /**
  73562. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  73563. */
  73564. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  73565. if (disableDepthRender === void 0) { disableDepthRender = false; }
  73566. for (var i = 0; i < this._scene.cameras.length; i++) {
  73567. var camera = this._scene.cameras[i];
  73568. this._originalColorPostProcess.dispose(camera);
  73569. this._ssaoPostProcess.dispose(camera);
  73570. this._blurHPostProcess.dispose(camera);
  73571. this._blurVPostProcess.dispose(camera);
  73572. this._ssaoCombinePostProcess.dispose(camera);
  73573. }
  73574. this._randomTexture.dispose();
  73575. if (disableDepthRender)
  73576. this._scene.disableDepthRenderer();
  73577. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  73578. _super.prototype.dispose.call(this);
  73579. };
  73580. // Private Methods
  73581. SSAORenderingPipeline.prototype._createBlurPostProcess = function (ratio) {
  73582. var _this = this;
  73583. var size = 16;
  73584. 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);
  73585. 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);
  73586. this._blurHPostProcess.onActivateObservable.add(function () {
  73587. var dw = _this._blurHPostProcess.width / _this._scene.getEngine().getRenderWidth();
  73588. _this._blurHPostProcess.kernel = size * dw;
  73589. });
  73590. this._blurVPostProcess.onActivateObservable.add(function () {
  73591. var dw = _this._blurVPostProcess.height / _this._scene.getEngine().getRenderHeight();
  73592. _this._blurVPostProcess.kernel = size * dw;
  73593. });
  73594. };
  73595. SSAORenderingPipeline.prototype._rebuild = function () {
  73596. this._firstUpdate = true;
  73597. _super.prototype._rebuild.call(this);
  73598. };
  73599. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  73600. var _this = this;
  73601. var numSamples = 16;
  73602. var sampleSphere = [
  73603. 0.5381, 0.1856, -0.4319,
  73604. 0.1379, 0.2486, 0.4430,
  73605. 0.3371, 0.5679, -0.0057,
  73606. -0.6999, -0.0451, -0.0019,
  73607. 0.0689, -0.1598, -0.8547,
  73608. 0.0560, 0.0069, -0.1843,
  73609. -0.0146, 0.1402, 0.0762,
  73610. 0.0100, -0.1924, -0.0344,
  73611. -0.3577, -0.5301, -0.4358,
  73612. -0.3169, 0.1063, 0.0158,
  73613. 0.0103, -0.5869, 0.0046,
  73614. -0.0897, -0.4940, 0.3287,
  73615. 0.7119, -0.0154, -0.0918,
  73616. -0.0533, 0.0596, -0.5411,
  73617. 0.0352, -0.0631, 0.5460,
  73618. -0.4776, 0.2847, -0.0271
  73619. ];
  73620. var samplesFactor = 1.0 / numSamples;
  73621. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", [
  73622. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  73623. "area", "fallOff", "base", "range", "viewport"
  73624. ], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  73625. this._ssaoPostProcess.onApply = function (effect) {
  73626. if (_this._firstUpdate) {
  73627. effect.setArray3("sampleSphere", sampleSphere);
  73628. effect.setFloat("samplesFactor", samplesFactor);
  73629. effect.setFloat("randTextureTiles", 4.0);
  73630. }
  73631. effect.setFloat("totalStrength", _this.totalStrength);
  73632. effect.setFloat("radius", _this.radius);
  73633. effect.setFloat("area", _this.area);
  73634. effect.setFloat("fallOff", _this.fallOff);
  73635. effect.setFloat("base", _this.base);
  73636. effect.setTexture("textureSampler", _this._depthTexture);
  73637. effect.setTexture("randomSampler", _this._randomTexture);
  73638. };
  73639. };
  73640. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  73641. var _this = this;
  73642. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor", "viewport"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  73643. this._ssaoCombinePostProcess.onApply = function (effect) {
  73644. effect.setVector4("viewport", BABYLON.Tmp.Vector4[0].copyFromFloats(0, 0, 1.0, 1.0));
  73645. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  73646. };
  73647. };
  73648. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  73649. var size = 512;
  73650. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  73651. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  73652. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  73653. var context = this._randomTexture.getContext();
  73654. var rand = function (min, max) {
  73655. return Math.random() * (max - min) + min;
  73656. };
  73657. var randVector = BABYLON.Vector3.Zero();
  73658. for (var x = 0; x < size; x++) {
  73659. for (var y = 0; y < size; y++) {
  73660. randVector.x = Math.floor(rand(-1.0, 1.0) * 255);
  73661. randVector.y = Math.floor(rand(-1.0, 1.0) * 255);
  73662. randVector.z = Math.floor(rand(-1.0, 1.0) * 255);
  73663. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  73664. context.fillRect(x, y, 1, 1);
  73665. }
  73666. }
  73667. this._randomTexture.update(false);
  73668. };
  73669. __decorate([
  73670. BABYLON.serialize()
  73671. ], SSAORenderingPipeline.prototype, "totalStrength", void 0);
  73672. __decorate([
  73673. BABYLON.serialize()
  73674. ], SSAORenderingPipeline.prototype, "radius", void 0);
  73675. __decorate([
  73676. BABYLON.serialize()
  73677. ], SSAORenderingPipeline.prototype, "area", void 0);
  73678. __decorate([
  73679. BABYLON.serialize()
  73680. ], SSAORenderingPipeline.prototype, "fallOff", void 0);
  73681. __decorate([
  73682. BABYLON.serialize()
  73683. ], SSAORenderingPipeline.prototype, "base", void 0);
  73684. return SSAORenderingPipeline;
  73685. }(BABYLON.PostProcessRenderPipeline));
  73686. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  73687. })(BABYLON || (BABYLON = {}));
  73688. //# sourceMappingURL=babylon.ssaoRenderingPipeline.js.map
  73689. var BABYLON;
  73690. (function (BABYLON) {
  73691. var SSAO2RenderingPipeline = /** @class */ (function (_super) {
  73692. __extends(SSAO2RenderingPipeline, _super);
  73693. /**
  73694. * @constructor
  73695. * @param {string} name - The rendering pipeline name
  73696. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  73697. * @param {any} ratio - The size of the postprocesses. Can be a number shared between passes or an object for more precision: { ssaoRatio: 0.5, blurRatio: 1.0 }
  73698. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  73699. */
  73700. function SSAO2RenderingPipeline(name, scene, ratio, cameras) {
  73701. var _this = _super.call(this, scene.getEngine(), name) || this;
  73702. // Members
  73703. /**
  73704. * The PassPostProcess id in the pipeline that contains the original scene color
  73705. */
  73706. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  73707. /**
  73708. * The SSAO PostProcess id in the pipeline
  73709. */
  73710. _this.SSAORenderEffect = "SSAORenderEffect";
  73711. /**
  73712. * The horizontal blur PostProcess id in the pipeline
  73713. */
  73714. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  73715. /**
  73716. * The vertical blur PostProcess id in the pipeline
  73717. */
  73718. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  73719. /**
  73720. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  73721. */
  73722. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  73723. /**
  73724. * The output strength of the SSAO post-process. Default value is 1.0.
  73725. */
  73726. _this.totalStrength = 1.0;
  73727. /**
  73728. * Maximum depth value to still render AO. A smooth falloff makes the dimming more natural, so there will be no abrupt shading change.
  73729. */
  73730. _this.maxZ = 100.0;
  73731. /**
  73732. * In order to save performances, SSAO radius is clamped on close geometry. This ratio changes by how much
  73733. */
  73734. _this.minZAspect = 0.2;
  73735. /**
  73736. * Number of samples used for the SSAO calculations. Default value is 8
  73737. */
  73738. _this._samples = 8;
  73739. /**
  73740. * Are we using bilateral blur ?
  73741. */
  73742. _this._expensiveBlur = true;
  73743. /**
  73744. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 2.0
  73745. */
  73746. _this.radius = 2.0;
  73747. /**
  73748. * The base color of the SSAO post-process
  73749. * The final result is "base + ssao" between [0, 1]
  73750. */
  73751. _this.base = 0.1;
  73752. _this._firstUpdate = true;
  73753. _this._scene = scene;
  73754. _this._ratio = ratio;
  73755. if (!_this.isSupported) {
  73756. BABYLON.Tools.Error("SSAO 2 needs WebGL 2 support.");
  73757. return _this;
  73758. }
  73759. var ssaoRatio = _this._ratio.ssaoRatio || ratio;
  73760. var blurRatio = _this._ratio.blurRatio || ratio;
  73761. // Set up assets
  73762. var geometryBufferRenderer = scene.enableGeometryBufferRenderer();
  73763. _this._createRandomTexture();
  73764. _this._depthTexture = geometryBufferRenderer.getGBuffer().textures[0];
  73765. _this._normalTexture = geometryBufferRenderer.getGBuffer().textures[1];
  73766. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  73767. _this._createSSAOPostProcess(1.0);
  73768. _this._createBlurPostProcess(ssaoRatio, blurRatio);
  73769. _this._createSSAOCombinePostProcess(blurRatio);
  73770. // Set up pipeline
  73771. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  73772. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  73773. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  73774. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  73775. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  73776. // Finish
  73777. scene.postProcessRenderPipelineManager.addPipeline(_this);
  73778. if (cameras)
  73779. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  73780. return _this;
  73781. }
  73782. Object.defineProperty(SSAO2RenderingPipeline.prototype, "samples", {
  73783. get: function () {
  73784. return this._samples;
  73785. },
  73786. set: function (n) {
  73787. this._ssaoPostProcess.updateEffect("#define SAMPLES " + n + "\n#define SSAO");
  73788. this._samples = n;
  73789. this._sampleSphere = this._generateHemisphere();
  73790. this._firstUpdate = true;
  73791. },
  73792. enumerable: true,
  73793. configurable: true
  73794. });
  73795. Object.defineProperty(SSAO2RenderingPipeline.prototype, "expensiveBlur", {
  73796. get: function () {
  73797. return this._expensiveBlur;
  73798. },
  73799. set: function (b) {
  73800. 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"]);
  73801. this._blurVPostProcess.updateEffect("#define BILATERAL_BLUR\n#define SAMPLES 16\n#define EXPENSIVE " + (b ? "1" : "0") + "\n", null, ["textureSampler", "depthSampler"]);
  73802. this._expensiveBlur = b;
  73803. this._firstUpdate = true;
  73804. },
  73805. enumerable: true,
  73806. configurable: true
  73807. });
  73808. Object.defineProperty(SSAO2RenderingPipeline, "IsSupported", {
  73809. /**
  73810. * Support test.
  73811. */
  73812. get: function () {
  73813. var engine = BABYLON.Engine.LastCreatedEngine;
  73814. if (!engine) {
  73815. return false;
  73816. }
  73817. return engine.getCaps().drawBuffersExtension;
  73818. },
  73819. enumerable: true,
  73820. configurable: true
  73821. });
  73822. // Public Methods
  73823. /**
  73824. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  73825. */
  73826. SSAO2RenderingPipeline.prototype.dispose = function (disableGeometryBufferRenderer) {
  73827. if (disableGeometryBufferRenderer === void 0) { disableGeometryBufferRenderer = false; }
  73828. for (var i = 0; i < this._scene.cameras.length; i++) {
  73829. var camera = this._scene.cameras[i];
  73830. this._originalColorPostProcess.dispose(camera);
  73831. this._ssaoPostProcess.dispose(camera);
  73832. this._blurHPostProcess.dispose(camera);
  73833. this._blurVPostProcess.dispose(camera);
  73834. this._ssaoCombinePostProcess.dispose(camera);
  73835. }
  73836. this._randomTexture.dispose();
  73837. if (disableGeometryBufferRenderer)
  73838. this._scene.disableGeometryBufferRenderer();
  73839. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  73840. _super.prototype.dispose.call(this);
  73841. };
  73842. // Private Methods
  73843. SSAO2RenderingPipeline.prototype._createBlurPostProcess = function (ssaoRatio, blurRatio) {
  73844. var _this = this;
  73845. this._samplerOffsets = [];
  73846. var expensive = this.expensiveBlur;
  73847. for (var i = -8; i < 8; i++) {
  73848. this._samplerOffsets.push(i * 2 + 0.5);
  73849. }
  73850. 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");
  73851. this._blurHPostProcess.onApply = function (effect) {
  73852. if (!_this._scene.activeCamera) {
  73853. return;
  73854. }
  73855. effect.setFloat("outSize", _this._ssaoCombinePostProcess.width > 0 ? _this._ssaoCombinePostProcess.width : _this._originalColorPostProcess.width);
  73856. effect.setFloat("near", _this._scene.activeCamera.minZ);
  73857. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  73858. effect.setFloat("radius", _this.radius);
  73859. effect.setTexture("depthSampler", _this._depthTexture);
  73860. if (_this._firstUpdate) {
  73861. effect.setArray("samplerOffsets", _this._samplerOffsets);
  73862. }
  73863. };
  73864. 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");
  73865. this._blurVPostProcess.onApply = function (effect) {
  73866. if (!_this._scene.activeCamera) {
  73867. return;
  73868. }
  73869. effect.setFloat("outSize", _this._ssaoCombinePostProcess.height > 0 ? _this._ssaoCombinePostProcess.height : _this._originalColorPostProcess.height);
  73870. effect.setFloat("near", _this._scene.activeCamera.minZ);
  73871. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  73872. effect.setFloat("radius", _this.radius);
  73873. effect.setTexture("depthSampler", _this._depthTexture);
  73874. if (_this._firstUpdate) {
  73875. effect.setArray("samplerOffsets", _this._samplerOffsets);
  73876. _this._firstUpdate = false;
  73877. }
  73878. };
  73879. };
  73880. SSAO2RenderingPipeline.prototype._rebuild = function () {
  73881. this._firstUpdate = true;
  73882. _super.prototype._rebuild.call(this);
  73883. };
  73884. SSAO2RenderingPipeline.prototype._generateHemisphere = function () {
  73885. var numSamples = this.samples;
  73886. var result = [];
  73887. var vector, scale;
  73888. var rand = function (min, max) {
  73889. return Math.random() * (max - min) + min;
  73890. };
  73891. var i = 0;
  73892. while (i < numSamples) {
  73893. vector = new BABYLON.Vector3(rand(-1.0, 1.0), rand(-1.0, 1.0), rand(0.30, 1.0));
  73894. vector.normalize();
  73895. scale = i / numSamples;
  73896. scale = BABYLON.Scalar.Lerp(0.1, 1.0, scale * scale);
  73897. vector.scaleInPlace(scale);
  73898. result.push(vector.x, vector.y, vector.z);
  73899. i++;
  73900. }
  73901. return result;
  73902. };
  73903. SSAO2RenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  73904. var _this = this;
  73905. var numSamples = this.samples;
  73906. this._sampleSphere = this._generateHemisphere();
  73907. this._ssaoPostProcess = new BABYLON.PostProcess("ssao2", "ssao2", [
  73908. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  73909. "base", "range", "projection", "near", "far", "texelSize",
  73910. "xViewport", "yViewport", "maxZ", "minZAspect"
  73911. ], ["randomSampler", "normalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  73912. this._ssaoPostProcess.onApply = function (effect) {
  73913. if (_this._firstUpdate) {
  73914. effect.setArray3("sampleSphere", _this._sampleSphere);
  73915. effect.setFloat("randTextureTiles", 4.0);
  73916. }
  73917. if (!_this._scene.activeCamera) {
  73918. return;
  73919. }
  73920. effect.setFloat("samplesFactor", 1 / _this.samples);
  73921. effect.setFloat("totalStrength", _this.totalStrength);
  73922. effect.setFloat2("texelSize", 1 / _this._ssaoPostProcess.width, 1 / _this._ssaoPostProcess.height);
  73923. effect.setFloat("radius", _this.radius);
  73924. effect.setFloat("maxZ", _this.maxZ);
  73925. effect.setFloat("minZAspect", _this.minZAspect);
  73926. effect.setFloat("base", _this.base);
  73927. effect.setFloat("near", _this._scene.activeCamera.minZ);
  73928. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  73929. effect.setFloat("xViewport", Math.tan(_this._scene.activeCamera.fov / 2) * _this._scene.getEngine().getAspectRatio(_this._scene.activeCamera, true));
  73930. effect.setFloat("yViewport", Math.tan(_this._scene.activeCamera.fov / 2));
  73931. effect.setMatrix("projection", _this._scene.getProjectionMatrix());
  73932. effect.setTexture("textureSampler", _this._depthTexture);
  73933. effect.setTexture("normalSampler", _this._normalTexture);
  73934. effect.setTexture("randomSampler", _this._randomTexture);
  73935. };
  73936. };
  73937. SSAO2RenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  73938. var _this = this;
  73939. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor", "viewport"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  73940. this._ssaoCombinePostProcess.onApply = function (effect) {
  73941. var viewport = _this._scene.activeCamera.viewport;
  73942. effect.setVector4("viewport", BABYLON.Tmp.Vector4[0].copyFromFloats(viewport.x, viewport.y, viewport.width, viewport.height));
  73943. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  73944. };
  73945. };
  73946. SSAO2RenderingPipeline.prototype._createRandomTexture = function () {
  73947. var size = 512;
  73948. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  73949. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  73950. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  73951. var context = this._randomTexture.getContext();
  73952. var rand = function (min, max) {
  73953. return Math.random() * (max - min) + min;
  73954. };
  73955. var randVector = BABYLON.Vector3.Zero();
  73956. for (var x = 0; x < size; x++) {
  73957. for (var y = 0; y < size; y++) {
  73958. randVector.x = rand(0.0, 1.0);
  73959. randVector.y = rand(0.0, 1.0);
  73960. randVector.z = 0.0;
  73961. randVector.normalize();
  73962. randVector.scaleInPlace(255);
  73963. randVector.x = Math.floor(randVector.x);
  73964. randVector.y = Math.floor(randVector.y);
  73965. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  73966. context.fillRect(x, y, 1, 1);
  73967. }
  73968. }
  73969. this._randomTexture.update(false);
  73970. };
  73971. /**
  73972. * Serialize the rendering pipeline (Used when exporting)
  73973. * @returns the serialized object
  73974. */
  73975. SSAO2RenderingPipeline.prototype.serialize = function () {
  73976. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  73977. serializationObject.customType = "SSAO2RenderingPipeline";
  73978. return serializationObject;
  73979. };
  73980. /**
  73981. * Parse the serialized pipeline
  73982. * @param source Source pipeline.
  73983. * @param scene The scene to load the pipeline to.
  73984. * @param rootUrl The URL of the serialized pipeline.
  73985. * @returns An instantiated pipeline from the serialized object.
  73986. */
  73987. SSAO2RenderingPipeline.Parse = function (source, scene, rootUrl) {
  73988. return BABYLON.SerializationHelper.Parse(function () { return new SSAO2RenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
  73989. };
  73990. __decorate([
  73991. BABYLON.serialize()
  73992. ], SSAO2RenderingPipeline.prototype, "totalStrength", void 0);
  73993. __decorate([
  73994. BABYLON.serialize()
  73995. ], SSAO2RenderingPipeline.prototype, "maxZ", void 0);
  73996. __decorate([
  73997. BABYLON.serialize()
  73998. ], SSAO2RenderingPipeline.prototype, "minZAspect", void 0);
  73999. __decorate([
  74000. BABYLON.serialize("samples")
  74001. ], SSAO2RenderingPipeline.prototype, "_samples", void 0);
  74002. __decorate([
  74003. BABYLON.serialize()
  74004. ], SSAO2RenderingPipeline.prototype, "_ratio", void 0);
  74005. __decorate([
  74006. BABYLON.serialize("expensiveBlur")
  74007. ], SSAO2RenderingPipeline.prototype, "_expensiveBlur", void 0);
  74008. __decorate([
  74009. BABYLON.serialize()
  74010. ], SSAO2RenderingPipeline.prototype, "radius", void 0);
  74011. __decorate([
  74012. BABYLON.serialize()
  74013. ], SSAO2RenderingPipeline.prototype, "base", void 0);
  74014. return SSAO2RenderingPipeline;
  74015. }(BABYLON.PostProcessRenderPipeline));
  74016. BABYLON.SSAO2RenderingPipeline = SSAO2RenderingPipeline;
  74017. })(BABYLON || (BABYLON = {}));
  74018. //# sourceMappingURL=babylon.ssao2RenderingPipeline.js.map
  74019. // BABYLON.JS Chromatic Aberration GLSL Shader
  74020. // Author: Olivier Guyot
  74021. // Separates very slightly R, G and B colors on the edges of the screen
  74022. // Inspired by Francois Tarlier & Martins Upitis
  74023. var BABYLON;
  74024. (function (BABYLON) {
  74025. var LensRenderingPipeline = /** @class */ (function (_super) {
  74026. __extends(LensRenderingPipeline, _super);
  74027. /**
  74028. * @constructor
  74029. *
  74030. * Effect parameters are as follow:
  74031. * {
  74032. * chromatic_aberration: number; // from 0 to x (1 for realism)
  74033. * edge_blur: number; // from 0 to x (1 for realism)
  74034. * distortion: number; // from 0 to x (1 for realism)
  74035. * grain_amount: number; // from 0 to 1
  74036. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  74037. * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default)
  74038. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  74039. * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)
  74040. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  74041. * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default)
  74042. * dof_threshold: number; // depth-of-field: highlights threshold (default: 1)
  74043. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  74044. * }
  74045. * Note: if an effect parameter is unset, effect is disabled
  74046. *
  74047. * @param {string} name - The rendering pipeline name
  74048. * @param {object} parameters - An object containing all parameters (see above)
  74049. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  74050. * @param {number} ratio - The size of the postprocesses (0.5 means that your postprocess will have a width = canvas.width 0.5 and a height = canvas.height 0.5)
  74051. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  74052. */
  74053. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  74054. if (ratio === void 0) { ratio = 1.0; }
  74055. var _this = _super.call(this, scene.getEngine(), name) || this;
  74056. // Lens effects can be of the following:
  74057. // - chromatic aberration (slight shift of RGB colors)
  74058. // - blur on the edge of the lens
  74059. // - lens distortion
  74060. // - depth-of-field blur & highlights enhancing
  74061. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  74062. // - grain effect (noise or custom texture)
  74063. // Two additional texture samplers are needed:
  74064. // - depth map (for depth-of-field)
  74065. // - grain texture
  74066. /**
  74067. * The chromatic aberration PostProcess id in the pipeline
  74068. */
  74069. _this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  74070. /**
  74071. * The highlights enhancing PostProcess id in the pipeline
  74072. */
  74073. _this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  74074. /**
  74075. * The depth-of-field PostProcess id in the pipeline
  74076. */
  74077. _this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  74078. _this._scene = scene;
  74079. // Fetch texture samplers
  74080. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  74081. if (parameters.grain_texture) {
  74082. _this._grainTexture = parameters.grain_texture;
  74083. }
  74084. else {
  74085. _this._createGrainTexture();
  74086. }
  74087. // save parameters
  74088. _this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  74089. _this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  74090. _this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  74091. _this._distortion = parameters.distortion ? parameters.distortion : 0;
  74092. _this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  74093. _this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  74094. _this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;
  74095. _this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  74096. _this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;
  74097. _this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  74098. _this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  74099. // Create effects
  74100. _this._createChromaticAberrationPostProcess(ratio);
  74101. _this._createHighlightsPostProcess(ratio);
  74102. _this._createDepthOfFieldPostProcess(ratio / 4);
  74103. // Set up pipeline
  74104. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
  74105. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
  74106. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
  74107. if (_this._highlightsGain === -1) {
  74108. _this._disableEffect(_this.HighlightsEnhancingEffect, null);
  74109. }
  74110. // Finish
  74111. scene.postProcessRenderPipelineManager.addPipeline(_this);
  74112. if (cameras) {
  74113. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  74114. }
  74115. return _this;
  74116. }
  74117. // public methods (self explanatory)
  74118. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
  74119. LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
  74120. LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
  74121. LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
  74122. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
  74123. LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
  74124. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
  74125. LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
  74126. LensRenderingPipeline.prototype.setFocusDistance = function (amount) { this._dofDistance = amount; };
  74127. LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDistance = -1; };
  74128. LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
  74129. LensRenderingPipeline.prototype.setDarkenOutOfFocus = function (amount) { this._dofDarken = amount; };
  74130. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  74131. this._highlightsPostProcess.updateEffect("#define PENTAGON\n");
  74132. };
  74133. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  74134. this._highlightsPostProcess.updateEffect();
  74135. };
  74136. LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
  74137. LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
  74138. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  74139. this._highlightsGain = amount;
  74140. };
  74141. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  74142. if (this._highlightsGain === -1) {
  74143. this._highlightsGain = 1.0;
  74144. }
  74145. this._highlightsThreshold = amount;
  74146. };
  74147. LensRenderingPipeline.prototype.disableHighlights = function () {
  74148. this._highlightsGain = -1;
  74149. };
  74150. /**
  74151. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  74152. */
  74153. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  74154. if (disableDepthRender === void 0) { disableDepthRender = false; }
  74155. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  74156. this._chromaticAberrationPostProcess = null;
  74157. this._highlightsPostProcess = null;
  74158. this._depthOfFieldPostProcess = null;
  74159. this._grainTexture.dispose();
  74160. if (disableDepthRender)
  74161. this._scene.disableDepthRenderer();
  74162. };
  74163. // colors shifting and distortion
  74164. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  74165. var _this = this;
  74166. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height", "direction", "radialIntensity", "centerPosition"], // uniforms
  74167. [], // samplers
  74168. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  74169. this._chromaticAberrationPostProcess.onApply = function (effect) {
  74170. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  74171. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  74172. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  74173. effect.setFloat('radialIntensity', 1);
  74174. effect.setFloat2('direction', 17, 17);
  74175. effect.setFloat2('centerPosition', 0.5, 0.5);
  74176. };
  74177. };
  74178. // highlights enhancing
  74179. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  74180. var _this = this;
  74181. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["gain", "threshold", "screen_width", "screen_height"], // uniforms
  74182. [], // samplers
  74183. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, this._dofPentagon ? "#define PENTAGON\n" : "");
  74184. this._highlightsPostProcess.onApply = function (effect) {
  74185. effect.setFloat('gain', _this._highlightsGain);
  74186. effect.setFloat('threshold', _this._highlightsThreshold);
  74187. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  74188. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  74189. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  74190. };
  74191. };
  74192. // colors shifting and distortion
  74193. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  74194. var _this = this;
  74195. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  74196. "grain_amount", "blur_noise", "screen_width", "screen_height", "distortion", "dof_enabled",
  74197. "screen_distance", "aperture", "darken", "edge_blur", "highlights", "near", "far"
  74198. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  74199. this._depthOfFieldPostProcess.onApply = function (effect) {
  74200. effect.setTexture("depthSampler", _this._depthTexture);
  74201. effect.setTexture("grainSampler", _this._grainTexture);
  74202. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  74203. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  74204. effect.setFloat('grain_amount', _this._grainAmount);
  74205. effect.setBool('blur_noise', _this._blurNoise);
  74206. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  74207. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  74208. effect.setFloat('distortion', _this._distortion);
  74209. effect.setBool('dof_enabled', (_this._dofDistance !== -1));
  74210. effect.setFloat('screen_distance', 1.0 / (0.1 - 1.0 / _this._dofDistance));
  74211. effect.setFloat('aperture', _this._dofAperture);
  74212. effect.setFloat('darken', _this._dofDarken);
  74213. effect.setFloat('edge_blur', _this._edgeBlur);
  74214. effect.setBool('highlights', (_this._highlightsGain !== -1));
  74215. if (_this._scene.activeCamera) {
  74216. effect.setFloat('near', _this._scene.activeCamera.minZ);
  74217. effect.setFloat('far', _this._scene.activeCamera.maxZ);
  74218. }
  74219. };
  74220. };
  74221. // creates a black and white random noise texture, 512x512
  74222. LensRenderingPipeline.prototype._createGrainTexture = function () {
  74223. var size = 512;
  74224. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  74225. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  74226. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  74227. var context = this._grainTexture.getContext();
  74228. var rand = function (min, max) {
  74229. return Math.random() * (max - min) + min;
  74230. };
  74231. var value;
  74232. for (var x = 0; x < size; x++) {
  74233. for (var y = 0; y < size; y++) {
  74234. value = Math.floor(rand(0.42, 0.58) * 255);
  74235. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  74236. context.fillRect(x, y, 1, 1);
  74237. }
  74238. }
  74239. this._grainTexture.update(false);
  74240. };
  74241. return LensRenderingPipeline;
  74242. }(BABYLON.PostProcessRenderPipeline));
  74243. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  74244. })(BABYLON || (BABYLON = {}));
  74245. //# sourceMappingURL=babylon.lensRenderingPipeline.js.map
  74246. var BABYLON;
  74247. (function (BABYLON) {
  74248. var StandardRenderingPipeline = /** @class */ (function (_super) {
  74249. __extends(StandardRenderingPipeline, _super);
  74250. /**
  74251. * @constructor
  74252. * @param {string} name - The rendering pipeline name
  74253. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  74254. * @param {any} ratio - The size of the postprocesses (0.5 means that your postprocess will have a width = canvas.width 0.5 and a height = canvas.height 0.5)
  74255. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  74256. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  74257. */
  74258. function StandardRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  74259. if (originalPostProcess === void 0) { originalPostProcess = null; }
  74260. var _this = _super.call(this, scene.getEngine(), name) || this;
  74261. _this.downSampleX4PostProcess = null;
  74262. _this.brightPassPostProcess = null;
  74263. _this.blurHPostProcesses = [];
  74264. _this.blurVPostProcesses = [];
  74265. _this.textureAdderPostProcess = null;
  74266. _this.volumetricLightPostProcess = null;
  74267. _this.volumetricLightSmoothXPostProcess = null;
  74268. _this.volumetricLightSmoothYPostProcess = null;
  74269. _this.volumetricLightMergePostProces = null;
  74270. _this.volumetricLightFinalPostProcess = null;
  74271. _this.luminancePostProcess = null;
  74272. _this.luminanceDownSamplePostProcesses = [];
  74273. _this.hdrPostProcess = null;
  74274. _this.textureAdderFinalPostProcess = null;
  74275. _this.lensFlareFinalPostProcess = null;
  74276. _this.hdrFinalPostProcess = null;
  74277. _this.lensFlarePostProcess = null;
  74278. _this.lensFlareComposePostProcess = null;
  74279. _this.motionBlurPostProcess = null;
  74280. _this.depthOfFieldPostProcess = null;
  74281. // Values
  74282. _this.brightThreshold = 1.0;
  74283. _this.blurWidth = 512.0;
  74284. _this.horizontalBlur = false;
  74285. _this.exposure = 1.0;
  74286. _this.lensTexture = null;
  74287. _this.volumetricLightCoefficient = 0.2;
  74288. _this.volumetricLightPower = 4.0;
  74289. _this.volumetricLightBlurScale = 64.0;
  74290. _this.sourceLight = null;
  74291. _this.hdrMinimumLuminance = 1.0;
  74292. _this.hdrDecreaseRate = 0.5;
  74293. _this.hdrIncreaseRate = 0.5;
  74294. _this.lensColorTexture = null;
  74295. _this.lensFlareStrength = 20.0;
  74296. _this.lensFlareGhostDispersal = 1.4;
  74297. _this.lensFlareHaloWidth = 0.7;
  74298. _this.lensFlareDistortionStrength = 16.0;
  74299. _this.lensStarTexture = null;
  74300. _this.lensFlareDirtTexture = null;
  74301. _this.depthOfFieldDistance = 10.0;
  74302. _this.depthOfFieldBlurWidth = 64.0;
  74303. _this.motionStrength = 1.0;
  74304. // IAnimatable
  74305. _this.animations = [];
  74306. _this._currentDepthOfFieldSource = null;
  74307. _this._hdrCurrentLuminance = 1.0;
  74308. // Getters and setters
  74309. _this._bloomEnabled = true;
  74310. _this._depthOfFieldEnabled = false;
  74311. _this._vlsEnabled = false;
  74312. _this._lensFlareEnabled = false;
  74313. _this._hdrEnabled = false;
  74314. _this._motionBlurEnabled = false;
  74315. _this._motionBlurSamples = 64.0;
  74316. _this._volumetricLightStepsCount = 50.0;
  74317. _this._cameras = cameras || [];
  74318. // Initialize
  74319. _this._scene = scene;
  74320. _this._basePostProcess = originalPostProcess;
  74321. _this._ratio = ratio;
  74322. // Misc
  74323. _this._floatTextureType = scene.getEngine().getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  74324. // Finish
  74325. scene.postProcessRenderPipelineManager.addPipeline(_this);
  74326. _this._buildPipeline();
  74327. return _this;
  74328. }
  74329. Object.defineProperty(StandardRenderingPipeline.prototype, "BloomEnabled", {
  74330. get: function () {
  74331. return this._bloomEnabled;
  74332. },
  74333. set: function (enabled) {
  74334. if (this._bloomEnabled === enabled) {
  74335. return;
  74336. }
  74337. this._bloomEnabled = enabled;
  74338. this._buildPipeline();
  74339. },
  74340. enumerable: true,
  74341. configurable: true
  74342. });
  74343. Object.defineProperty(StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", {
  74344. get: function () {
  74345. return this._depthOfFieldEnabled;
  74346. },
  74347. set: function (enabled) {
  74348. if (this._depthOfFieldEnabled === enabled) {
  74349. return;
  74350. }
  74351. this._depthOfFieldEnabled = enabled;
  74352. this._buildPipeline();
  74353. },
  74354. enumerable: true,
  74355. configurable: true
  74356. });
  74357. Object.defineProperty(StandardRenderingPipeline.prototype, "LensFlareEnabled", {
  74358. get: function () {
  74359. return this._lensFlareEnabled;
  74360. },
  74361. set: function (enabled) {
  74362. if (this._lensFlareEnabled === enabled) {
  74363. return;
  74364. }
  74365. this._lensFlareEnabled = enabled;
  74366. this._buildPipeline();
  74367. },
  74368. enumerable: true,
  74369. configurable: true
  74370. });
  74371. Object.defineProperty(StandardRenderingPipeline.prototype, "HDREnabled", {
  74372. get: function () {
  74373. return this._hdrEnabled;
  74374. },
  74375. set: function (enabled) {
  74376. if (this._hdrEnabled === enabled) {
  74377. return;
  74378. }
  74379. this._hdrEnabled = enabled;
  74380. this._buildPipeline();
  74381. },
  74382. enumerable: true,
  74383. configurable: true
  74384. });
  74385. Object.defineProperty(StandardRenderingPipeline.prototype, "VLSEnabled", {
  74386. get: function () {
  74387. return this._vlsEnabled;
  74388. },
  74389. set: function (enabled) {
  74390. if (this._vlsEnabled === enabled) {
  74391. return;
  74392. }
  74393. if (enabled) {
  74394. var geometry = this._scene.enableGeometryBufferRenderer();
  74395. if (!geometry) {
  74396. BABYLON.Tools.Warn("Geometry renderer is not supported, cannot create volumetric lights in Standard Rendering Pipeline");
  74397. return;
  74398. }
  74399. }
  74400. this._vlsEnabled = enabled;
  74401. this._buildPipeline();
  74402. },
  74403. enumerable: true,
  74404. configurable: true
  74405. });
  74406. Object.defineProperty(StandardRenderingPipeline.prototype, "MotionBlurEnabled", {
  74407. get: function () {
  74408. return this._motionBlurEnabled;
  74409. },
  74410. set: function (enabled) {
  74411. if (this._motionBlurEnabled === enabled) {
  74412. return;
  74413. }
  74414. this._motionBlurEnabled = enabled;
  74415. this._buildPipeline();
  74416. },
  74417. enumerable: true,
  74418. configurable: true
  74419. });
  74420. Object.defineProperty(StandardRenderingPipeline.prototype, "volumetricLightStepsCount", {
  74421. get: function () {
  74422. return this._volumetricLightStepsCount;
  74423. },
  74424. set: function (count) {
  74425. if (this.volumetricLightPostProcess) {
  74426. this.volumetricLightPostProcess.updateEffect("#define VLS\n#define NB_STEPS " + count.toFixed(1));
  74427. }
  74428. this._volumetricLightStepsCount = count;
  74429. },
  74430. enumerable: true,
  74431. configurable: true
  74432. });
  74433. Object.defineProperty(StandardRenderingPipeline.prototype, "motionBlurSamples", {
  74434. get: function () {
  74435. return this._motionBlurSamples;
  74436. },
  74437. set: function (samples) {
  74438. if (this.motionBlurPostProcess) {
  74439. this.motionBlurPostProcess.updateEffect("#define MOTION_BLUR\n#define MAX_MOTION_SAMPLES " + samples.toFixed(1));
  74440. }
  74441. this._motionBlurSamples = samples;
  74442. },
  74443. enumerable: true,
  74444. configurable: true
  74445. });
  74446. StandardRenderingPipeline.prototype._buildPipeline = function () {
  74447. var _this = this;
  74448. var ratio = this._ratio;
  74449. var scene = this._scene;
  74450. this._disposePostProcesses();
  74451. this._reset();
  74452. // Create pass post-process
  74453. if (!this._basePostProcess) {
  74454. this.originalPostProcess = new BABYLON.PostProcess("HDRPass", "standard", [], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define PASS_POST_PROCESS", this._floatTextureType);
  74455. this.originalPostProcess.onApply = function (effect) {
  74456. _this._currentDepthOfFieldSource = _this.originalPostProcess;
  74457. };
  74458. }
  74459. else {
  74460. this.originalPostProcess = this._basePostProcess;
  74461. }
  74462. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this.originalPostProcess; }, true));
  74463. this._currentDepthOfFieldSource = this.originalPostProcess;
  74464. if (this._bloomEnabled) {
  74465. // Create down sample X4 post-process
  74466. this._createDownSampleX4PostProcess(scene, ratio / 2);
  74467. // Create bright pass post-process
  74468. this._createBrightPassPostProcess(scene, ratio / 2);
  74469. // Create gaussian blur post-processes (down sampling blurs)
  74470. this._createBlurPostProcesses(scene, ratio / 4, 1);
  74471. // Create texture adder post-process
  74472. this._createTextureAdderPostProcess(scene, ratio);
  74473. // Create depth-of-field source post-process
  74474. 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);
  74475. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBaseDepthOfFieldSource", function () { return _this.textureAdderFinalPostProcess; }, true));
  74476. }
  74477. if (this._vlsEnabled) {
  74478. // Create volumetric light
  74479. this._createVolumetricLightPostProcess(scene, ratio);
  74480. // Create volumetric light final post-process
  74481. 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);
  74482. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSFinal", function () { return _this.volumetricLightFinalPostProcess; }, true));
  74483. }
  74484. if (this._lensFlareEnabled) {
  74485. // Create lens flare post-process
  74486. this._createLensFlarePostProcess(scene, ratio);
  74487. // Create depth-of-field source post-process post lens-flare and disable it now
  74488. 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);
  74489. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostLensFlareDepthOfFieldSource", function () { return _this.lensFlareFinalPostProcess; }, true));
  74490. }
  74491. if (this._hdrEnabled) {
  74492. // Create luminance
  74493. this._createLuminancePostProcesses(scene, this._floatTextureType);
  74494. // Create HDR
  74495. this._createHdrPostProcess(scene, ratio);
  74496. // Create depth-of-field source post-process post hdr and disable it now
  74497. 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);
  74498. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostHDReDepthOfFieldSource", function () { return _this.hdrFinalPostProcess; }, true));
  74499. }
  74500. if (this._depthOfFieldEnabled) {
  74501. // Create gaussian blur used by depth-of-field
  74502. this._createBlurPostProcesses(scene, ratio / 2, 3, "depthOfFieldBlurWidth");
  74503. // Create depth-of-field post-process
  74504. this._createDepthOfFieldPostProcess(scene, ratio);
  74505. }
  74506. if (this._motionBlurEnabled) {
  74507. // Create motion blur post-process
  74508. this._createMotionBlurPostProcess(scene, ratio);
  74509. }
  74510. if (this._cameras !== null) {
  74511. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  74512. }
  74513. };
  74514. // Down Sample X4 Post-Processs
  74515. StandardRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  74516. var _this = this;
  74517. var downSampleX4Offsets = new Array(32);
  74518. 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);
  74519. this.downSampleX4PostProcess.onApply = function (effect) {
  74520. var id = 0;
  74521. var width = _this.downSampleX4PostProcess.width;
  74522. var height = _this.downSampleX4PostProcess.height;
  74523. for (var i = -2; i < 2; i++) {
  74524. for (var j = -2; j < 2; j++) {
  74525. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / width);
  74526. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / height);
  74527. id += 2;
  74528. }
  74529. }
  74530. effect.setArray2("dsOffsets", downSampleX4Offsets);
  74531. };
  74532. // Add to pipeline
  74533. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this.downSampleX4PostProcess; }, true));
  74534. };
  74535. // Brightpass Post-Process
  74536. StandardRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  74537. var _this = this;
  74538. var brightOffsets = new Array(8);
  74539. 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);
  74540. this.brightPassPostProcess.onApply = function (effect) {
  74541. var sU = (1.0 / _this.brightPassPostProcess.width);
  74542. var sV = (1.0 / _this.brightPassPostProcess.height);
  74543. brightOffsets[0] = -0.5 * sU;
  74544. brightOffsets[1] = 0.5 * sV;
  74545. brightOffsets[2] = 0.5 * sU;
  74546. brightOffsets[3] = 0.5 * sV;
  74547. brightOffsets[4] = -0.5 * sU;
  74548. brightOffsets[5] = -0.5 * sV;
  74549. brightOffsets[6] = 0.5 * sU;
  74550. brightOffsets[7] = -0.5 * sV;
  74551. effect.setArray2("dsOffsets", brightOffsets);
  74552. effect.setFloat("brightThreshold", _this.brightThreshold);
  74553. };
  74554. // Add to pipeline
  74555. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this.brightPassPostProcess; }, true));
  74556. };
  74557. // Create blur H&V post-processes
  74558. StandardRenderingPipeline.prototype._createBlurPostProcesses = function (scene, ratio, indice, blurWidthKey) {
  74559. var _this = this;
  74560. if (blurWidthKey === void 0) { blurWidthKey = "blurWidth"; }
  74561. var engine = scene.getEngine();
  74562. 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);
  74563. 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);
  74564. blurX.onActivateObservable.add(function () {
  74565. var dw = blurX.width / engine.getRenderWidth();
  74566. blurX.kernel = _this[blurWidthKey] * dw;
  74567. });
  74568. blurY.onActivateObservable.add(function () {
  74569. var dw = blurY.height / engine.getRenderHeight();
  74570. blurY.kernel = _this.horizontalBlur ? 64 * dw : _this[blurWidthKey] * dw;
  74571. });
  74572. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurH" + indice, function () { return blurX; }, true));
  74573. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurV" + indice, function () { return blurY; }, true));
  74574. this.blurHPostProcesses.push(blurX);
  74575. this.blurVPostProcesses.push(blurY);
  74576. };
  74577. // Create texture adder post-process
  74578. StandardRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  74579. var _this = this;
  74580. 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);
  74581. this.textureAdderPostProcess.onApply = function (effect) {
  74582. effect.setTextureFromPostProcess("otherSampler", _this._vlsEnabled ? _this._currentDepthOfFieldSource : _this.originalPostProcess);
  74583. effect.setTexture("lensSampler", _this.lensTexture);
  74584. effect.setFloat("exposure", _this.exposure);
  74585. _this._currentDepthOfFieldSource = _this.textureAdderFinalPostProcess;
  74586. };
  74587. // Add to pipeline
  74588. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this.textureAdderPostProcess; }, true));
  74589. };
  74590. StandardRenderingPipeline.prototype._createVolumetricLightPostProcess = function (scene, ratio) {
  74591. var _this = this;
  74592. var geometryRenderer = scene.enableGeometryBufferRenderer();
  74593. geometryRenderer.enablePosition = true;
  74594. var geometry = geometryRenderer.getGBuffer();
  74595. // Base post-process
  74596. 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));
  74597. var depthValues = BABYLON.Vector2.Zero();
  74598. this.volumetricLightPostProcess.onApply = function (effect) {
  74599. if (_this.sourceLight && _this.sourceLight.getShadowGenerator() && _this._scene.activeCamera) {
  74600. var generator = _this.sourceLight.getShadowGenerator();
  74601. effect.setTexture("shadowMapSampler", generator.getShadowMap());
  74602. effect.setTexture("positionSampler", geometry.textures[2]);
  74603. effect.setColor3("sunColor", _this.sourceLight.diffuse);
  74604. effect.setVector3("sunDirection", _this.sourceLight.getShadowDirection());
  74605. effect.setVector3("cameraPosition", _this._scene.activeCamera.globalPosition);
  74606. effect.setMatrix("shadowViewProjection", generator.getTransformMatrix());
  74607. effect.setFloat("scatteringCoefficient", _this.volumetricLightCoefficient);
  74608. effect.setFloat("scatteringPower", _this.volumetricLightPower);
  74609. depthValues.x = generator.getLight().getDepthMinZ(_this._scene.activeCamera);
  74610. depthValues.y = generator.getLight().getDepthMaxZ(_this._scene.activeCamera);
  74611. effect.setVector2("depthValues", depthValues);
  74612. }
  74613. };
  74614. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLS", function () { return _this.volumetricLightPostProcess; }, true));
  74615. // Smooth
  74616. this._createBlurPostProcesses(scene, ratio / 4, 0, "volumetricLightBlurScale");
  74617. // Merge
  74618. this.volumetricLightMergePostProces = new BABYLON.PostProcess("HDRVLSMerge", "standard", [], ["originalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define VLSMERGE");
  74619. this.volumetricLightMergePostProces.onApply = function (effect) {
  74620. effect.setTextureFromPostProcess("originalSampler", _this._bloomEnabled ? _this.textureAdderFinalPostProcess : _this.originalPostProcess);
  74621. _this._currentDepthOfFieldSource = _this.volumetricLightFinalPostProcess;
  74622. };
  74623. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSMerge", function () { return _this.volumetricLightMergePostProces; }, true));
  74624. };
  74625. // Create luminance
  74626. StandardRenderingPipeline.prototype._createLuminancePostProcesses = function (scene, textureType) {
  74627. var _this = this;
  74628. // Create luminance
  74629. var size = Math.pow(3, StandardRenderingPipeline.LuminanceSteps);
  74630. this.luminancePostProcess = new BABYLON.PostProcess("HDRLuminance", "standard", ["lumOffsets"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define LUMINANCE", textureType);
  74631. var offsets = [];
  74632. this.luminancePostProcess.onApply = function (effect) {
  74633. var sU = (1.0 / _this.luminancePostProcess.width);
  74634. var sV = (1.0 / _this.luminancePostProcess.height);
  74635. offsets[0] = -0.5 * sU;
  74636. offsets[1] = 0.5 * sV;
  74637. offsets[2] = 0.5 * sU;
  74638. offsets[3] = 0.5 * sV;
  74639. offsets[4] = -0.5 * sU;
  74640. offsets[5] = -0.5 * sV;
  74641. offsets[6] = 0.5 * sU;
  74642. offsets[7] = -0.5 * sV;
  74643. effect.setArray2("lumOffsets", offsets);
  74644. };
  74645. // Add to pipeline
  74646. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminance", function () { return _this.luminancePostProcess; }, true));
  74647. // Create down sample luminance
  74648. for (var i = StandardRenderingPipeline.LuminanceSteps - 1; i >= 0; i--) {
  74649. var size = Math.pow(3, i);
  74650. var defines = "#define LUMINANCE_DOWN_SAMPLE\n";
  74651. if (i === 0) {
  74652. defines += "#define FINAL_DOWN_SAMPLER";
  74653. }
  74654. var postProcess = new BABYLON.PostProcess("HDRLuminanceDownSample" + i, "standard", ["dsOffsets", "halfDestPixelSize"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, defines, textureType);
  74655. this.luminanceDownSamplePostProcesses.push(postProcess);
  74656. }
  74657. // Create callbacks and add effects
  74658. var lastLuminance = this.luminancePostProcess;
  74659. this.luminanceDownSamplePostProcesses.forEach(function (pp, index) {
  74660. var downSampleOffsets = new Array(18);
  74661. pp.onApply = function (effect) {
  74662. if (!lastLuminance) {
  74663. return;
  74664. }
  74665. var id = 0;
  74666. for (var x = -1; x < 2; x++) {
  74667. for (var y = -1; y < 2; y++) {
  74668. downSampleOffsets[id] = x / lastLuminance.width;
  74669. downSampleOffsets[id + 1] = y / lastLuminance.height;
  74670. id += 2;
  74671. }
  74672. }
  74673. effect.setArray2("dsOffsets", downSampleOffsets);
  74674. effect.setFloat("halfDestPixelSize", 0.5 / lastLuminance.width);
  74675. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  74676. lastLuminance = _this.luminancePostProcess;
  74677. }
  74678. else {
  74679. lastLuminance = pp;
  74680. }
  74681. };
  74682. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  74683. pp.onAfterRender = function (effect) {
  74684. var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
  74685. 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);
  74686. _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;
  74687. };
  74688. }
  74689. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminanceDownSample" + index, function () { return pp; }, true));
  74690. });
  74691. };
  74692. // Create HDR post-process
  74693. StandardRenderingPipeline.prototype._createHdrPostProcess = function (scene, ratio) {
  74694. var _this = this;
  74695. 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);
  74696. var outputLiminance = 1;
  74697. var time = 0;
  74698. var lastTime = 0;
  74699. this.hdrPostProcess.onApply = function (effect) {
  74700. effect.setTextureFromPostProcess("textureAdderSampler", _this._currentDepthOfFieldSource);
  74701. time += scene.getEngine().getDeltaTime();
  74702. if (outputLiminance < 0) {
  74703. outputLiminance = _this._hdrCurrentLuminance;
  74704. }
  74705. else {
  74706. var dt = (lastTime - time) / 1000.0;
  74707. if (_this._hdrCurrentLuminance < outputLiminance + _this.hdrDecreaseRate * dt) {
  74708. outputLiminance += _this.hdrDecreaseRate * dt;
  74709. }
  74710. else if (_this._hdrCurrentLuminance > outputLiminance - _this.hdrIncreaseRate * dt) {
  74711. outputLiminance -= _this.hdrIncreaseRate * dt;
  74712. }
  74713. else {
  74714. outputLiminance = _this._hdrCurrentLuminance;
  74715. }
  74716. }
  74717. outputLiminance = BABYLON.Scalar.Clamp(outputLiminance, _this.hdrMinimumLuminance, 1e20);
  74718. effect.setFloat("averageLuminance", outputLiminance);
  74719. lastTime = time;
  74720. _this._currentDepthOfFieldSource = _this.hdrFinalPostProcess;
  74721. };
  74722. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDR", function () { return _this.hdrPostProcess; }, true));
  74723. };
  74724. // Create lens flare post-process
  74725. StandardRenderingPipeline.prototype._createLensFlarePostProcess = function (scene, ratio) {
  74726. var _this = this;
  74727. 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);
  74728. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlare", function () { return _this.lensFlarePostProcess; }, true));
  74729. this._createBlurPostProcesses(scene, ratio / 4, 2);
  74730. 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);
  74731. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlareCompose", function () { return _this.lensFlareComposePostProcess; }, true));
  74732. var resolution = new BABYLON.Vector2(0, 0);
  74733. // Lens flare
  74734. this.lensFlarePostProcess.onApply = function (effect) {
  74735. effect.setTextureFromPostProcess("textureSampler", _this._bloomEnabled ? _this.blurHPostProcesses[0] : _this.originalPostProcess);
  74736. effect.setTexture("lensColorSampler", _this.lensColorTexture);
  74737. effect.setFloat("strength", _this.lensFlareStrength);
  74738. effect.setFloat("ghostDispersal", _this.lensFlareGhostDispersal);
  74739. effect.setFloat("haloWidth", _this.lensFlareHaloWidth);
  74740. // Shift
  74741. resolution.x = _this.lensFlarePostProcess.width;
  74742. resolution.y = _this.lensFlarePostProcess.height;
  74743. effect.setVector2("resolution", resolution);
  74744. effect.setFloat("distortionStrength", _this.lensFlareDistortionStrength);
  74745. };
  74746. // Compose
  74747. 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);
  74748. 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);
  74749. this.lensFlareComposePostProcess.onApply = function (effect) {
  74750. if (!_this._scene.activeCamera) {
  74751. return;
  74752. }
  74753. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  74754. effect.setTexture("lensDirtSampler", _this.lensFlareDirtTexture);
  74755. effect.setTexture("lensStarSampler", _this.lensStarTexture);
  74756. // Lens start rotation matrix
  74757. var camerax = _this._scene.activeCamera.getViewMatrix().getRow(0);
  74758. var cameraz = _this._scene.activeCamera.getViewMatrix().getRow(2);
  74759. 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));
  74760. camRot *= 4.0;
  74761. 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);
  74762. var lensStarMatrix = scaleBias2.multiply(starRotation).multiply(scaleBias1);
  74763. effect.setMatrix("lensStarMatrix", lensStarMatrix);
  74764. _this._currentDepthOfFieldSource = _this.lensFlareFinalPostProcess;
  74765. };
  74766. };
  74767. // Create depth-of-field post-process
  74768. StandardRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (scene, ratio) {
  74769. var _this = this;
  74770. 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);
  74771. this.depthOfFieldPostProcess.onApply = function (effect) {
  74772. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  74773. effect.setTexture("depthSampler", _this._getDepthTexture());
  74774. effect.setFloat("distance", _this.depthOfFieldDistance);
  74775. };
  74776. // Add to pipeline
  74777. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDepthOfField", function () { return _this.depthOfFieldPostProcess; }, true));
  74778. };
  74779. // Create motion blur post-process
  74780. StandardRenderingPipeline.prototype._createMotionBlurPostProcess = function (scene, ratio) {
  74781. var _this = this;
  74782. 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);
  74783. var motionScale = 0;
  74784. var prevViewProjection = BABYLON.Matrix.Identity();
  74785. var invViewProjection = BABYLON.Matrix.Identity();
  74786. var viewProjection = BABYLON.Matrix.Identity();
  74787. var screenSize = BABYLON.Vector2.Zero();
  74788. this.motionBlurPostProcess.onApply = function (effect) {
  74789. viewProjection = scene.getProjectionMatrix().multiply(scene.getViewMatrix());
  74790. viewProjection.invertToRef(invViewProjection);
  74791. effect.setMatrix("inverseViewProjection", invViewProjection);
  74792. effect.setMatrix("prevViewProjection", prevViewProjection);
  74793. prevViewProjection = viewProjection;
  74794. screenSize.x = _this.motionBlurPostProcess.width;
  74795. screenSize.y = _this.motionBlurPostProcess.height;
  74796. effect.setVector2("screenSize", screenSize);
  74797. motionScale = scene.getEngine().getFps() / 60.0;
  74798. effect.setFloat("motionScale", motionScale);
  74799. effect.setFloat("motionStrength", _this.motionStrength);
  74800. effect.setTexture("depthSampler", _this._getDepthTexture());
  74801. };
  74802. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRMotionBlur", function () { return _this.motionBlurPostProcess; }, true));
  74803. };
  74804. StandardRenderingPipeline.prototype._getDepthTexture = function () {
  74805. if (this._scene.getEngine().getCaps().drawBuffersExtension) {
  74806. var renderer = this._scene.enableGeometryBufferRenderer();
  74807. return renderer.getGBuffer().textures[0];
  74808. }
  74809. return this._scene.enableDepthRenderer().getDepthMap();
  74810. };
  74811. StandardRenderingPipeline.prototype._disposePostProcesses = function () {
  74812. for (var i = 0; i < this._cameras.length; i++) {
  74813. var camera = this._cameras[i];
  74814. if (this.originalPostProcess) {
  74815. this.originalPostProcess.dispose(camera);
  74816. }
  74817. if (this.downSampleX4PostProcess) {
  74818. this.downSampleX4PostProcess.dispose(camera);
  74819. }
  74820. if (this.brightPassPostProcess) {
  74821. this.brightPassPostProcess.dispose(camera);
  74822. }
  74823. if (this.textureAdderPostProcess) {
  74824. this.textureAdderPostProcess.dispose(camera);
  74825. }
  74826. if (this.textureAdderFinalPostProcess) {
  74827. this.textureAdderFinalPostProcess.dispose(camera);
  74828. }
  74829. if (this.volumetricLightPostProcess) {
  74830. this.volumetricLightPostProcess.dispose(camera);
  74831. }
  74832. if (this.volumetricLightSmoothXPostProcess) {
  74833. this.volumetricLightSmoothXPostProcess.dispose(camera);
  74834. }
  74835. if (this.volumetricLightSmoothYPostProcess) {
  74836. this.volumetricLightSmoothYPostProcess.dispose(camera);
  74837. }
  74838. if (this.volumetricLightMergePostProces) {
  74839. this.volumetricLightMergePostProces.dispose(camera);
  74840. }
  74841. if (this.volumetricLightFinalPostProcess) {
  74842. this.volumetricLightFinalPostProcess.dispose(camera);
  74843. }
  74844. if (this.lensFlarePostProcess) {
  74845. this.lensFlarePostProcess.dispose(camera);
  74846. }
  74847. if (this.lensFlareComposePostProcess) {
  74848. this.lensFlareComposePostProcess.dispose(camera);
  74849. }
  74850. for (var j = 0; j < this.luminanceDownSamplePostProcesses.length; j++) {
  74851. this.luminanceDownSamplePostProcesses[j].dispose(camera);
  74852. }
  74853. if (this.luminancePostProcess) {
  74854. this.luminancePostProcess.dispose(camera);
  74855. }
  74856. if (this.hdrPostProcess) {
  74857. this.hdrPostProcess.dispose(camera);
  74858. }
  74859. if (this.hdrFinalPostProcess) {
  74860. this.hdrFinalPostProcess.dispose(camera);
  74861. }
  74862. if (this.depthOfFieldPostProcess) {
  74863. this.depthOfFieldPostProcess.dispose(camera);
  74864. }
  74865. if (this.motionBlurPostProcess) {
  74866. this.motionBlurPostProcess.dispose(camera);
  74867. }
  74868. for (var j = 0; j < this.blurHPostProcesses.length; j++) {
  74869. this.blurHPostProcesses[j].dispose(camera);
  74870. }
  74871. for (var j = 0; j < this.blurVPostProcesses.length; j++) {
  74872. this.blurVPostProcesses[j].dispose(camera);
  74873. }
  74874. }
  74875. this.originalPostProcess = null;
  74876. this.downSampleX4PostProcess = null;
  74877. this.brightPassPostProcess = null;
  74878. this.textureAdderPostProcess = null;
  74879. this.textureAdderFinalPostProcess = null;
  74880. this.volumetricLightPostProcess = null;
  74881. this.volumetricLightSmoothXPostProcess = null;
  74882. this.volumetricLightSmoothYPostProcess = null;
  74883. this.volumetricLightMergePostProces = null;
  74884. this.volumetricLightFinalPostProcess = null;
  74885. this.lensFlarePostProcess = null;
  74886. this.lensFlareComposePostProcess = null;
  74887. this.luminancePostProcess = null;
  74888. this.hdrPostProcess = null;
  74889. this.hdrFinalPostProcess = null;
  74890. this.depthOfFieldPostProcess = null;
  74891. this.motionBlurPostProcess = null;
  74892. this.luminanceDownSamplePostProcesses = [];
  74893. this.blurHPostProcesses = [];
  74894. this.blurVPostProcesses = [];
  74895. };
  74896. /**
  74897. * Dispose of the pipeline and stop all post processes
  74898. */
  74899. StandardRenderingPipeline.prototype.dispose = function () {
  74900. this._disposePostProcesses();
  74901. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  74902. _super.prototype.dispose.call(this);
  74903. };
  74904. /**
  74905. * Serialize the rendering pipeline (Used when exporting)
  74906. * @returns the serialized object
  74907. */
  74908. StandardRenderingPipeline.prototype.serialize = function () {
  74909. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  74910. if (this.sourceLight) {
  74911. serializationObject.sourceLightId = this.sourceLight.id;
  74912. }
  74913. serializationObject.customType = "StandardRenderingPipeline";
  74914. return serializationObject;
  74915. };
  74916. /**
  74917. * Parse the serialized pipeline
  74918. * @param source Source pipeline.
  74919. * @param scene The scene to load the pipeline to.
  74920. * @param rootUrl The URL of the serialized pipeline.
  74921. * @returns An instantiated pipeline from the serialized object.
  74922. */
  74923. StandardRenderingPipeline.Parse = function (source, scene, rootUrl) {
  74924. var p = BABYLON.SerializationHelper.Parse(function () { return new StandardRenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
  74925. if (source.sourceLightId) {
  74926. p.sourceLight = scene.getLightByID(source.sourceLightId);
  74927. }
  74928. return p;
  74929. };
  74930. // Luminance steps
  74931. StandardRenderingPipeline.LuminanceSteps = 6;
  74932. __decorate([
  74933. BABYLON.serialize()
  74934. ], StandardRenderingPipeline.prototype, "brightThreshold", void 0);
  74935. __decorate([
  74936. BABYLON.serialize()
  74937. ], StandardRenderingPipeline.prototype, "blurWidth", void 0);
  74938. __decorate([
  74939. BABYLON.serialize()
  74940. ], StandardRenderingPipeline.prototype, "horizontalBlur", void 0);
  74941. __decorate([
  74942. BABYLON.serialize()
  74943. ], StandardRenderingPipeline.prototype, "exposure", void 0);
  74944. __decorate([
  74945. BABYLON.serializeAsTexture("lensTexture")
  74946. ], StandardRenderingPipeline.prototype, "lensTexture", void 0);
  74947. __decorate([
  74948. BABYLON.serialize()
  74949. ], StandardRenderingPipeline.prototype, "volumetricLightCoefficient", void 0);
  74950. __decorate([
  74951. BABYLON.serialize()
  74952. ], StandardRenderingPipeline.prototype, "volumetricLightPower", void 0);
  74953. __decorate([
  74954. BABYLON.serialize()
  74955. ], StandardRenderingPipeline.prototype, "volumetricLightBlurScale", void 0);
  74956. __decorate([
  74957. BABYLON.serialize()
  74958. ], StandardRenderingPipeline.prototype, "hdrMinimumLuminance", void 0);
  74959. __decorate([
  74960. BABYLON.serialize()
  74961. ], StandardRenderingPipeline.prototype, "hdrDecreaseRate", void 0);
  74962. __decorate([
  74963. BABYLON.serialize()
  74964. ], StandardRenderingPipeline.prototype, "hdrIncreaseRate", void 0);
  74965. __decorate([
  74966. BABYLON.serializeAsTexture("lensColorTexture")
  74967. ], StandardRenderingPipeline.prototype, "lensColorTexture", void 0);
  74968. __decorate([
  74969. BABYLON.serialize()
  74970. ], StandardRenderingPipeline.prototype, "lensFlareStrength", void 0);
  74971. __decorate([
  74972. BABYLON.serialize()
  74973. ], StandardRenderingPipeline.prototype, "lensFlareGhostDispersal", void 0);
  74974. __decorate([
  74975. BABYLON.serialize()
  74976. ], StandardRenderingPipeline.prototype, "lensFlareHaloWidth", void 0);
  74977. __decorate([
  74978. BABYLON.serialize()
  74979. ], StandardRenderingPipeline.prototype, "lensFlareDistortionStrength", void 0);
  74980. __decorate([
  74981. BABYLON.serializeAsTexture("lensStarTexture")
  74982. ], StandardRenderingPipeline.prototype, "lensStarTexture", void 0);
  74983. __decorate([
  74984. BABYLON.serializeAsTexture("lensFlareDirtTexture")
  74985. ], StandardRenderingPipeline.prototype, "lensFlareDirtTexture", void 0);
  74986. __decorate([
  74987. BABYLON.serialize()
  74988. ], StandardRenderingPipeline.prototype, "depthOfFieldDistance", void 0);
  74989. __decorate([
  74990. BABYLON.serialize()
  74991. ], StandardRenderingPipeline.prototype, "depthOfFieldBlurWidth", void 0);
  74992. __decorate([
  74993. BABYLON.serialize()
  74994. ], StandardRenderingPipeline.prototype, "motionStrength", void 0);
  74995. __decorate([
  74996. BABYLON.serialize()
  74997. ], StandardRenderingPipeline.prototype, "_ratio", void 0);
  74998. __decorate([
  74999. BABYLON.serialize()
  75000. ], StandardRenderingPipeline.prototype, "BloomEnabled", null);
  75001. __decorate([
  75002. BABYLON.serialize()
  75003. ], StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", null);
  75004. __decorate([
  75005. BABYLON.serialize()
  75006. ], StandardRenderingPipeline.prototype, "LensFlareEnabled", null);
  75007. __decorate([
  75008. BABYLON.serialize()
  75009. ], StandardRenderingPipeline.prototype, "HDREnabled", null);
  75010. __decorate([
  75011. BABYLON.serialize()
  75012. ], StandardRenderingPipeline.prototype, "VLSEnabled", null);
  75013. __decorate([
  75014. BABYLON.serialize()
  75015. ], StandardRenderingPipeline.prototype, "MotionBlurEnabled", null);
  75016. __decorate([
  75017. BABYLON.serialize()
  75018. ], StandardRenderingPipeline.prototype, "volumetricLightStepsCount", null);
  75019. __decorate([
  75020. BABYLON.serialize()
  75021. ], StandardRenderingPipeline.prototype, "motionBlurSamples", null);
  75022. return StandardRenderingPipeline;
  75023. }(BABYLON.PostProcessRenderPipeline));
  75024. BABYLON.StandardRenderingPipeline = StandardRenderingPipeline;
  75025. })(BABYLON || (BABYLON = {}));
  75026. //# sourceMappingURL=babylon.standardRenderingPipeline.js.map
  75027. var BABYLON;
  75028. (function (BABYLON) {
  75029. var FxaaPostProcess = /** @class */ (function (_super) {
  75030. __extends(FxaaPostProcess, _super);
  75031. function FxaaPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  75032. if (camera === void 0) { camera = null; }
  75033. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  75034. var _this = _super.call(this, name, "fxaa", ["texelSize"], null, options, camera, samplingMode || BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, reusable, null, textureType, "fxaa", undefined, true) || this;
  75035. var defines = _this._getDefines();
  75036. _this.updateEffect(defines);
  75037. _this.onApplyObservable.add(function (effect) {
  75038. var texelSize = _this.texelSize;
  75039. effect.setFloat2("texelSize", texelSize.x, texelSize.y);
  75040. });
  75041. return _this;
  75042. }
  75043. FxaaPostProcess.prototype._getDefines = function () {
  75044. var engine = this.getEngine();
  75045. if (!engine) {
  75046. return null;
  75047. }
  75048. var glInfo = engine.getGlInfo();
  75049. if (glInfo && glInfo.renderer && glInfo.renderer.toLowerCase().indexOf("mali") > -1) {
  75050. return "#define MALI 1\n";
  75051. }
  75052. return null;
  75053. };
  75054. return FxaaPostProcess;
  75055. }(BABYLON.PostProcess));
  75056. BABYLON.FxaaPostProcess = FxaaPostProcess;
  75057. })(BABYLON || (BABYLON = {}));
  75058. //# sourceMappingURL=babylon.fxaaPostProcess.js.map
  75059. var BABYLON;
  75060. (function (BABYLON) {
  75061. /**
  75062. * The ChromaticAberrationPostProcess separates the rgb channels in an image to produce chromatic distortion around the edges of the screen
  75063. */
  75064. var ChromaticAberrationPostProcess = /** @class */ (function (_super) {
  75065. __extends(ChromaticAberrationPostProcess, _super);
  75066. /**
  75067. * Creates a new instance ChromaticAberrationPostProcess
  75068. * @param name The name of the effect.
  75069. * @param screenWidth The width of the screen to apply the effect on.
  75070. * @param screenHeight The height of the screen to apply the effect on.
  75071. * @param options The required width/height ratio to downsize to before computing the render pass.
  75072. * @param camera The camera to apply the render pass to.
  75073. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  75074. * @param engine The engine which the post process will be applied. (default: current engine)
  75075. * @param reusable If the post process can be reused on the same frame. (default: false)
  75076. * @param textureType Type of textures used when performing the post process. (default: 0)
  75077. * @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)
  75078. */
  75079. function ChromaticAberrationPostProcess(name, screenWidth, screenHeight, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  75080. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  75081. if (blockCompilation === void 0) { blockCompilation = false; }
  75082. 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;
  75083. /**
  75084. * The amount of seperation of rgb channels (default: 30)
  75085. */
  75086. _this.aberrationAmount = 30;
  75087. /**
  75088. * The amount the effect will increase for pixels closer to the edge of the screen. (default: 0)
  75089. */
  75090. _this.radialIntensity = 0;
  75091. /**
  75092. * 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))
  75093. */
  75094. _this.direction = new BABYLON.Vector2(0.707, 0.707);
  75095. /**
  75096. * 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))
  75097. */
  75098. _this.centerPosition = new BABYLON.Vector2(0.5, 0.5);
  75099. _this.onApplyObservable.add(function (effect) {
  75100. effect.setFloat('chromatic_aberration', _this.aberrationAmount);
  75101. effect.setFloat('screen_width', screenWidth);
  75102. effect.setFloat('screen_height', screenHeight);
  75103. effect.setFloat('radialIntensity', _this.radialIntensity);
  75104. effect.setFloat2('direction', _this.direction.x, _this.direction.y);
  75105. effect.setFloat2('centerPosition', _this.centerPosition.x, _this.centerPosition.y);
  75106. });
  75107. return _this;
  75108. }
  75109. return ChromaticAberrationPostProcess;
  75110. }(BABYLON.PostProcess));
  75111. BABYLON.ChromaticAberrationPostProcess = ChromaticAberrationPostProcess;
  75112. })(BABYLON || (BABYLON = {}));
  75113. //# sourceMappingURL=babylon.chromaticAberrationPostProcess.js.map
  75114. var BABYLON;
  75115. (function (BABYLON) {
  75116. /**
  75117. * The GrainPostProcess adds noise to the image at mid luminance levels
  75118. */
  75119. var GrainPostProcess = /** @class */ (function (_super) {
  75120. __extends(GrainPostProcess, _super);
  75121. /**
  75122. * Creates a new instance of @see GrainPostProcess
  75123. * @param name The name of the effect.
  75124. * @param options The required width/height ratio to downsize to before computing the render pass.
  75125. * @param camera The camera to apply the render pass to.
  75126. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  75127. * @param engine The engine which the post process will be applied. (default: current engine)
  75128. * @param reusable If the post process can be reused on the same frame. (default: false)
  75129. * @param textureType Type of textures used when performing the post process. (default: 0)
  75130. * @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)
  75131. */
  75132. function GrainPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  75133. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  75134. if (blockCompilation === void 0) { blockCompilation = false; }
  75135. var _this = _super.call(this, name, "grain", ["intensity", "animatedSeed"], [], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  75136. /**
  75137. * The intensity of the grain added (default: 30)
  75138. */
  75139. _this.intensity = 30;
  75140. /**
  75141. * If the grain should be randomized on every frame
  75142. */
  75143. _this.animated = false;
  75144. _this.onApplyObservable.add(function (effect) {
  75145. effect.setFloat('intensity', _this.intensity);
  75146. effect.setFloat('animatedSeed', _this.animated ? Math.random() + 1 : 1);
  75147. });
  75148. return _this;
  75149. }
  75150. return GrainPostProcess;
  75151. }(BABYLON.PostProcess));
  75152. BABYLON.GrainPostProcess = GrainPostProcess;
  75153. })(BABYLON || (BABYLON = {}));
  75154. //# sourceMappingURL=babylon.grainPostProcess.js.map
  75155. var BABYLON;
  75156. (function (BABYLON) {
  75157. /**
  75158. * The SharpenPostProcess applies a sharpen kernel to every pixel
  75159. * See http://en.wikipedia.org/wiki/Kernel_(image_processing)
  75160. */
  75161. var SharpenPostProcess = /** @class */ (function (_super) {
  75162. __extends(SharpenPostProcess, _super);
  75163. /**
  75164. * Creates a new instance ConvolutionPostProcess
  75165. * @param name The name of the effect.
  75166. * @param options The required width/height ratio to downsize to before computing the render pass.
  75167. * @param camera The camera to apply the render pass to.
  75168. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  75169. * @param engine The engine which the post process will be applied. (default: current engine)
  75170. * @param reusable If the post process can be reused on the same frame. (default: false)
  75171. * @param textureType Type of textures used when performing the post process. (default: 0)
  75172. * @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)
  75173. */
  75174. function SharpenPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  75175. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  75176. if (blockCompilation === void 0) { blockCompilation = false; }
  75177. var _this = _super.call(this, name, "sharpen", ["sharpnessAmounts", "screenSize"], null, options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  75178. /**
  75179. * How much of the original color should be applied. Setting this to 0 will display edge detection. (default: 1)
  75180. */
  75181. _this.colorAmount = 1.0;
  75182. /**
  75183. * How much sharpness should be applied (default: 0.3)
  75184. */
  75185. _this.edgeAmount = 0.3;
  75186. _this.onApply = function (effect) {
  75187. effect.setFloat2("screenSize", _this.width, _this.height);
  75188. effect.setFloat2("sharpnessAmounts", _this.edgeAmount, _this.colorAmount);
  75189. };
  75190. return _this;
  75191. }
  75192. return SharpenPostProcess;
  75193. }(BABYLON.PostProcess));
  75194. BABYLON.SharpenPostProcess = SharpenPostProcess;
  75195. })(BABYLON || (BABYLON = {}));
  75196. //# sourceMappingURL=babylon.sharpenPostProcess.js.map
  75197. var BABYLON;
  75198. (function (BABYLON) {
  75199. /**
  75200. * The Blur Post Process which blurs an image based on a kernel and direction.
  75201. * Can be used twice in x and y directions to perform a guassian blur in two passes.
  75202. */
  75203. var BlurPostProcess = /** @class */ (function (_super) {
  75204. __extends(BlurPostProcess, _super);
  75205. /**
  75206. * Creates a new instance BlurPostProcess
  75207. * @param name The name of the effect.
  75208. * @param direction The direction in which to blur the image.
  75209. * @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.
  75210. * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
  75211. * @param camera The camera to apply the render pass to.
  75212. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  75213. * @param engine The engine which the post process will be applied. (default: current engine)
  75214. * @param reusable If the post process can be reused on the same frame. (default: false)
  75215. * @param textureType Type of textures used when performing the post process. (default: 0)
  75216. * @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)
  75217. */
  75218. function BlurPostProcess(name, /** The direction in which to blur the image. */ direction, kernel, options, camera, samplingMode, engine, reusable, textureType, defines, blockCompilation) {
  75219. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  75220. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  75221. if (defines === void 0) { defines = ""; }
  75222. if (blockCompilation === void 0) { blockCompilation = false; }
  75223. 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;
  75224. _this.direction = direction;
  75225. _this.blockCompilation = blockCompilation;
  75226. _this._packedFloat = false;
  75227. _this._staticDefines = "";
  75228. _this._staticDefines = defines;
  75229. _this.onApplyObservable.add(function (effect) {
  75230. if (_this._outputTexture) {
  75231. effect.setFloat2('delta', (1 / _this._outputTexture.width) * _this.direction.x, (1 / _this._outputTexture.height) * _this.direction.y);
  75232. }
  75233. else {
  75234. effect.setFloat2('delta', (1 / _this.width) * _this.direction.x, (1 / _this.height) * _this.direction.y);
  75235. }
  75236. });
  75237. _this.kernel = kernel;
  75238. return _this;
  75239. }
  75240. Object.defineProperty(BlurPostProcess.prototype, "kernel", {
  75241. /**
  75242. * Gets the length in pixels of the blur sample region
  75243. */
  75244. get: function () {
  75245. return this._idealKernel;
  75246. },
  75247. /**
  75248. * Sets the length in pixels of the blur sample region
  75249. */
  75250. set: function (v) {
  75251. if (this._idealKernel === v) {
  75252. return;
  75253. }
  75254. v = Math.max(v, 1);
  75255. this._idealKernel = v;
  75256. this._kernel = this._nearestBestKernel(v);
  75257. if (!this.blockCompilation) {
  75258. this._updateParameters();
  75259. }
  75260. },
  75261. enumerable: true,
  75262. configurable: true
  75263. });
  75264. Object.defineProperty(BlurPostProcess.prototype, "packedFloat", {
  75265. /**
  75266. * Gets wether or not the blur is unpacking/repacking floats
  75267. */
  75268. get: function () {
  75269. return this._packedFloat;
  75270. },
  75271. /**
  75272. * Sets wether or not the blur needs to unpack/repack floats
  75273. */
  75274. set: function (v) {
  75275. if (this._packedFloat === v) {
  75276. return;
  75277. }
  75278. this._packedFloat = v;
  75279. if (!this.blockCompilation) {
  75280. this._updateParameters();
  75281. }
  75282. },
  75283. enumerable: true,
  75284. configurable: true
  75285. });
  75286. /**
  75287. * Updates the effect with the current post process compile time values and recompiles the shader.
  75288. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  75289. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  75290. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  75291. * @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
  75292. * @param onCompiled Called when the shader has been compiled.
  75293. * @param onError Called if there is an error when compiling a shader.
  75294. */
  75295. BlurPostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  75296. if (defines === void 0) { defines = null; }
  75297. if (uniforms === void 0) { uniforms = null; }
  75298. if (samplers === void 0) { samplers = null; }
  75299. this._updateParameters(onCompiled, onError);
  75300. };
  75301. BlurPostProcess.prototype._updateParameters = function (onCompiled, onError) {
  75302. // Generate sampling offsets and weights
  75303. var N = this._kernel;
  75304. var centerIndex = (N - 1) / 2;
  75305. // Generate Gaussian sampling weights over kernel
  75306. var offsets = [];
  75307. var weights = [];
  75308. var totalWeight = 0;
  75309. for (var i = 0; i < N; i++) {
  75310. var u = i / (N - 1);
  75311. var w = this._gaussianWeight(u * 2.0 - 1);
  75312. offsets[i] = (i - centerIndex);
  75313. weights[i] = w;
  75314. totalWeight += w;
  75315. }
  75316. // Normalize weights
  75317. for (var i = 0; i < weights.length; i++) {
  75318. weights[i] /= totalWeight;
  75319. }
  75320. // Optimize: combine samples to take advantage of hardware linear sampling
  75321. // Walk from left to center, combining pairs (symmetrically)
  75322. var linearSamplingWeights = [];
  75323. var linearSamplingOffsets = [];
  75324. var linearSamplingMap = [];
  75325. for (var i = 0; i <= centerIndex; i += 2) {
  75326. var j = Math.min(i + 1, Math.floor(centerIndex));
  75327. var singleCenterSample = i === j;
  75328. if (singleCenterSample) {
  75329. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  75330. }
  75331. else {
  75332. var sharedCell = j === centerIndex;
  75333. var weightLinear = (weights[i] + weights[j] * (sharedCell ? .5 : 1.));
  75334. var offsetLinear = offsets[i] + 1 / (1 + weights[i] / weights[j]);
  75335. if (offsetLinear === 0) {
  75336. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  75337. linearSamplingMap.push({ o: offsets[i + 1], w: weights[i + 1] });
  75338. }
  75339. else {
  75340. linearSamplingMap.push({ o: offsetLinear, w: weightLinear });
  75341. linearSamplingMap.push({ o: -offsetLinear, w: weightLinear });
  75342. }
  75343. }
  75344. }
  75345. for (var i = 0; i < linearSamplingMap.length; i++) {
  75346. linearSamplingOffsets[i] = linearSamplingMap[i].o;
  75347. linearSamplingWeights[i] = linearSamplingMap[i].w;
  75348. }
  75349. // Replace with optimized
  75350. offsets = linearSamplingOffsets;
  75351. weights = linearSamplingWeights;
  75352. // Generate shaders
  75353. var maxVaryingRows = this.getEngine().getCaps().maxVaryingVectors;
  75354. var freeVaryingVec2 = Math.max(maxVaryingRows, 0.) - 1; // Because of sampleCenter
  75355. var varyingCount = Math.min(offsets.length, freeVaryingVec2);
  75356. var defines = "";
  75357. defines += this._staticDefines;
  75358. // The DOF fragment should ignore the center pixel when looping as it is handled manualy in the fragment shader.
  75359. if (this._staticDefines.indexOf("DOF") != -1) {
  75360. defines += "#define CENTER_WEIGHT " + this._glslFloat(weights[varyingCount - 1]) + "\r\n";
  75361. varyingCount--;
  75362. }
  75363. for (var i = 0; i < varyingCount; i++) {
  75364. defines += "#define KERNEL_OFFSET" + i + " " + this._glslFloat(offsets[i]) + "\r\n";
  75365. defines += "#define KERNEL_WEIGHT" + i + " " + this._glslFloat(weights[i]) + "\r\n";
  75366. }
  75367. var depCount = 0;
  75368. for (var i = freeVaryingVec2; i < offsets.length; i++) {
  75369. defines += "#define KERNEL_DEP_OFFSET" + depCount + " " + this._glslFloat(offsets[i]) + "\r\n";
  75370. defines += "#define KERNEL_DEP_WEIGHT" + depCount + " " + this._glslFloat(weights[i]) + "\r\n";
  75371. depCount++;
  75372. }
  75373. if (this.packedFloat) {
  75374. defines += "#define PACKEDFLOAT 1";
  75375. }
  75376. this.blockCompilation = false;
  75377. _super.prototype.updateEffect.call(this, defines, null, null, {
  75378. varyingCount: varyingCount,
  75379. depCount: depCount
  75380. }, onCompiled, onError);
  75381. };
  75382. /**
  75383. * Best kernels are odd numbers that when divided by 2, their integer part is even, so 5, 9 or 13.
  75384. * Other odd kernels optimize correctly but require proportionally more samples, even kernels are
  75385. * possible but will produce minor visual artifacts. Since each new kernel requires a new shader we
  75386. * want to minimize kernel changes, having gaps between physical kernels is helpful in that regard.
  75387. * The gaps between physical kernels are compensated for in the weighting of the samples
  75388. * @param idealKernel Ideal blur kernel.
  75389. * @return Nearest best kernel.
  75390. */
  75391. BlurPostProcess.prototype._nearestBestKernel = function (idealKernel) {
  75392. var v = Math.round(idealKernel);
  75393. for (var _i = 0, _a = [v, v - 1, v + 1, v - 2, v + 2]; _i < _a.length; _i++) {
  75394. var k = _a[_i];
  75395. if (((k % 2) !== 0) && ((Math.floor(k / 2) % 2) === 0) && k > 0) {
  75396. return Math.max(k, 3);
  75397. }
  75398. }
  75399. return Math.max(v, 3);
  75400. };
  75401. /**
  75402. * Calculates the value of a Gaussian distribution with sigma 3 at a given point.
  75403. * @param x The point on the Gaussian distribution to sample.
  75404. * @return the value of the Gaussian function at x.
  75405. */
  75406. BlurPostProcess.prototype._gaussianWeight = function (x) {
  75407. //reference: Engine/ImageProcessingBlur.cpp #dcc760
  75408. // We are evaluating the Gaussian (normal) distribution over a kernel parameter space of [-1,1],
  75409. // so we truncate at three standard deviations by setting stddev (sigma) to 1/3.
  75410. // The choice of 3-sigma truncation is common but arbitrary, and means that the signal is
  75411. // truncated at around 1.3% of peak strength.
  75412. //the distribution is scaled to account for the difference between the actual kernel size and the requested kernel size
  75413. var sigma = (1 / 3);
  75414. var denominator = Math.sqrt(2.0 * Math.PI) * sigma;
  75415. var exponent = -((x * x) / (2.0 * sigma * sigma));
  75416. var weight = (1.0 / denominator) * Math.exp(exponent);
  75417. return weight;
  75418. };
  75419. /**
  75420. * Generates a string that can be used as a floating point number in GLSL.
  75421. * @param x Value to print.
  75422. * @param decimalFigures Number of decimal places to print the number to (excluding trailing 0s).
  75423. * @return GLSL float string.
  75424. */
  75425. BlurPostProcess.prototype._glslFloat = function (x, decimalFigures) {
  75426. if (decimalFigures === void 0) { decimalFigures = 8; }
  75427. return x.toFixed(decimalFigures).replace(/0+$/, '');
  75428. };
  75429. return BlurPostProcess;
  75430. }(BABYLON.PostProcess));
  75431. BABYLON.BlurPostProcess = BlurPostProcess;
  75432. })(BABYLON || (BABYLON = {}));
  75433. //# sourceMappingURL=babylon.blurPostProcess.js.map
  75434. var BABYLON;
  75435. (function (BABYLON) {
  75436. /**
  75437. * The DepthOfFieldBlurPostProcess applied a blur in a give direction.
  75438. * This blur differs from the standard BlurPostProcess as it attempts to avoid blurring pixels
  75439. * based on samples that have a large difference in distance than the center pixel.
  75440. * See section 2.6.2 http://fileadmin.cs.lth.se/cs/education/edan35/lectures/12dof.pdf
  75441. */
  75442. var DepthOfFieldBlurPostProcess = /** @class */ (function (_super) {
  75443. __extends(DepthOfFieldBlurPostProcess, _super);
  75444. /**
  75445. * Creates a new instance CircleOfConfusionPostProcess
  75446. * @param name The name of the effect.
  75447. * @param scene The scene the effect belongs to.
  75448. * @param direction The direction the blur should be applied.
  75449. * @param kernel The size of the kernel used to blur.
  75450. * @param options The required width/height ratio to downsize to before computing the render pass.
  75451. * @param camera The camera to apply the render pass to.
  75452. * @param circleOfConfusion The circle of confusion + depth map to be used to avoid blurring accross edges
  75453. * @param imageToBlur The image to apply the blur to (default: Current rendered frame)
  75454. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  75455. * @param engine The engine which the post process will be applied. (default: current engine)
  75456. * @param reusable If the post process can be reused on the same frame. (default: false)
  75457. * @param textureType Type of textures used when performing the post process. (default: 0)
  75458. * @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)
  75459. */
  75460. function DepthOfFieldBlurPostProcess(name, scene, direction, kernel, options, camera, circleOfConfusion, imageToBlur, samplingMode, engine, reusable, textureType, blockCompilation) {
  75461. if (imageToBlur === void 0) { imageToBlur = null; }
  75462. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  75463. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  75464. if (blockCompilation === void 0) { blockCompilation = false; }
  75465. 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;
  75466. _this.direction = direction;
  75467. _this.onApplyObservable.add(function (effect) {
  75468. if (imageToBlur != null) {
  75469. effect.setTextureFromPostProcess("textureSampler", imageToBlur);
  75470. }
  75471. effect.setTextureFromPostProcessOutput("circleOfConfusionSampler", circleOfConfusion);
  75472. if (scene.activeCamera) {
  75473. effect.setFloat2('cameraMinMaxZ', scene.activeCamera.minZ, scene.activeCamera.maxZ);
  75474. }
  75475. });
  75476. return _this;
  75477. }
  75478. return DepthOfFieldBlurPostProcess;
  75479. }(BABYLON.BlurPostProcess));
  75480. BABYLON.DepthOfFieldBlurPostProcess = DepthOfFieldBlurPostProcess;
  75481. })(BABYLON || (BABYLON = {}));
  75482. //# sourceMappingURL=babylon.depthOfFieldBlurPostProcess.js.map
  75483. var BABYLON;
  75484. (function (BABYLON) {
  75485. /**
  75486. * Options to be set when merging outputs from the default pipeline.
  75487. */
  75488. var DepthOfFieldMergePostProcessOptions = /** @class */ (function () {
  75489. function DepthOfFieldMergePostProcessOptions() {
  75490. }
  75491. return DepthOfFieldMergePostProcessOptions;
  75492. }());
  75493. BABYLON.DepthOfFieldMergePostProcessOptions = DepthOfFieldMergePostProcessOptions;
  75494. /**
  75495. * The DepthOfFieldMergePostProcess merges blurred images with the original based on the values of the circle of confusion.
  75496. */
  75497. var DepthOfFieldMergePostProcess = /** @class */ (function (_super) {
  75498. __extends(DepthOfFieldMergePostProcess, _super);
  75499. /**
  75500. * Creates a new instance of DepthOfFieldMergePostProcess
  75501. * @param name The name of the effect.
  75502. * @param originalFromInput Post process which's input will be used for the merge.
  75503. * @param circleOfConfusion Circle of confusion post process which's output will be used to blur each pixel.
  75504. * @param blurSteps Blur post processes from low to high which will be mixed with the original image.
  75505. * @param options The required width/height ratio to downsize to before computing the render pass.
  75506. * @param camera The camera to apply the render pass to.
  75507. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  75508. * @param engine The engine which the post process will be applied. (default: current engine)
  75509. * @param reusable If the post process can be reused on the same frame. (default: false)
  75510. * @param textureType Type of textures used when performing the post process. (default: 0)
  75511. * @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)
  75512. */
  75513. function DepthOfFieldMergePostProcess(name, originalFromInput, circleOfConfusion, blurSteps, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  75514. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  75515. if (blockCompilation === void 0) { blockCompilation = false; }
  75516. var _this = _super.call(this, name, "depthOfFieldMerge", [], ["circleOfConfusionSampler", "blurStep0", "blurStep1", "blurStep2"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, true) || this;
  75517. _this.blurSteps = blurSteps;
  75518. _this.onApplyObservable.add(function (effect) {
  75519. effect.setTextureFromPostProcess("textureSampler", originalFromInput);
  75520. effect.setTextureFromPostProcessOutput("circleOfConfusionSampler", circleOfConfusion);
  75521. blurSteps.forEach(function (step, index) {
  75522. effect.setTextureFromPostProcessOutput("blurStep" + (blurSteps.length - index - 1), step);
  75523. });
  75524. });
  75525. if (!blockCompilation) {
  75526. _this.updateEffect();
  75527. }
  75528. return _this;
  75529. }
  75530. /**
  75531. * Updates the effect with the current post process compile time values and recompiles the shader.
  75532. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  75533. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  75534. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  75535. * @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
  75536. * @param onCompiled Called when the shader has been compiled.
  75537. * @param onError Called if there is an error when compiling a shader.
  75538. */
  75539. DepthOfFieldMergePostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  75540. if (defines === void 0) { defines = null; }
  75541. if (uniforms === void 0) { uniforms = null; }
  75542. if (samplers === void 0) { samplers = null; }
  75543. if (!defines) {
  75544. defines = "";
  75545. defines += "#define BLUR_LEVEL " + (this.blurSteps.length - 1) + "\n";
  75546. }
  75547. _super.prototype.updateEffect.call(this, defines, uniforms, samplers, indexParameters, onCompiled, onError);
  75548. };
  75549. return DepthOfFieldMergePostProcess;
  75550. }(BABYLON.PostProcess));
  75551. BABYLON.DepthOfFieldMergePostProcess = DepthOfFieldMergePostProcess;
  75552. })(BABYLON || (BABYLON = {}));
  75553. //# sourceMappingURL=babylon.depthOfFieldMergePostProcess.js.map
  75554. var BABYLON;
  75555. (function (BABYLON) {
  75556. /**
  75557. * The CircleOfConfusionPostProcess computes the circle of confusion value for each pixel given required lens parameters. See https://en.wikipedia.org/wiki/Circle_of_confusion
  75558. */
  75559. var CircleOfConfusionPostProcess = /** @class */ (function (_super) {
  75560. __extends(CircleOfConfusionPostProcess, _super);
  75561. /**
  75562. * Creates a new instance CircleOfConfusionPostProcess
  75563. * @param name The name of the effect.
  75564. * @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.
  75565. * @param options The required width/height ratio to downsize to before computing the render pass.
  75566. * @param camera The camera to apply the render pass to.
  75567. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  75568. * @param engine The engine which the post process will be applied. (default: current engine)
  75569. * @param reusable If the post process can be reused on the same frame. (default: false)
  75570. * @param textureType Type of textures used when performing the post process. (default: 0)
  75571. * @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)
  75572. */
  75573. function CircleOfConfusionPostProcess(name, depthTexture, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  75574. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  75575. if (blockCompilation === void 0) { blockCompilation = false; }
  75576. var _this = _super.call(this, name, "circleOfConfusion", ["cameraMinMaxZ", "focusDistance", "cocPrecalculation"], ["depthSampler"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  75577. /**
  75578. * 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.
  75579. */
  75580. _this.lensSize = 50;
  75581. /**
  75582. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  75583. */
  75584. _this.fStop = 1.4;
  75585. /**
  75586. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  75587. */
  75588. _this.focusDistance = 2000;
  75589. /**
  75590. * Focal length of the effect's camera in scene units/1000 (eg. millimeter). (default: 50)
  75591. */
  75592. _this.focalLength = 50;
  75593. _this._depthTexture = null;
  75594. _this._depthTexture = depthTexture;
  75595. _this.onApplyObservable.add(function (effect) {
  75596. if (!_this._depthTexture) {
  75597. BABYLON.Tools.Warn("No depth texture set on CircleOfConfusionPostProcess");
  75598. return;
  75599. }
  75600. effect.setTexture("depthSampler", _this._depthTexture);
  75601. // Circle of confusion calculation, See https://developer.nvidia.com/gpugems/GPUGems/gpugems_ch23.html
  75602. var aperture = _this.lensSize / _this.fStop;
  75603. var cocPrecalculation = ((aperture * _this.focalLength) / ((_this.focusDistance - _this.focalLength))); // * ((this.focusDistance - pixelDistance)/pixelDistance) [This part is done in shader]
  75604. effect.setFloat('focusDistance', _this.focusDistance);
  75605. effect.setFloat('cocPrecalculation', cocPrecalculation);
  75606. effect.setFloat2('cameraMinMaxZ', _this._depthTexture.activeCamera.minZ, _this._depthTexture.activeCamera.maxZ);
  75607. });
  75608. return _this;
  75609. }
  75610. Object.defineProperty(CircleOfConfusionPostProcess.prototype, "depthTexture", {
  75611. /**
  75612. * 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.
  75613. */
  75614. set: function (value) {
  75615. this._depthTexture = value;
  75616. },
  75617. enumerable: true,
  75618. configurable: true
  75619. });
  75620. return CircleOfConfusionPostProcess;
  75621. }(BABYLON.PostProcess));
  75622. BABYLON.CircleOfConfusionPostProcess = CircleOfConfusionPostProcess;
  75623. })(BABYLON || (BABYLON = {}));
  75624. //# sourceMappingURL=babylon.circleOfConfusionPostProcess.js.map
  75625. var BABYLON;
  75626. (function (BABYLON) {
  75627. /**
  75628. * Specifies the level of max blur that should be applied when using the depth of field effect
  75629. */
  75630. var DepthOfFieldEffectBlurLevel;
  75631. (function (DepthOfFieldEffectBlurLevel) {
  75632. /**
  75633. * Subtle blur
  75634. */
  75635. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["Low"] = 0] = "Low";
  75636. /**
  75637. * Medium blur
  75638. */
  75639. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["Medium"] = 1] = "Medium";
  75640. /**
  75641. * Large blur
  75642. */
  75643. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["High"] = 2] = "High";
  75644. })(DepthOfFieldEffectBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel || (BABYLON.DepthOfFieldEffectBlurLevel = {}));
  75645. ;
  75646. /**
  75647. * The depth of field effect applies a blur to objects that are closer or further from where the camera is focusing.
  75648. */
  75649. var DepthOfFieldEffect = /** @class */ (function (_super) {
  75650. __extends(DepthOfFieldEffect, _super);
  75651. /**
  75652. * Creates a new instance DepthOfFieldEffect
  75653. * @param scene The scene the effect belongs to.
  75654. * @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.
  75655. * @param pipelineTextureType The type of texture to be used when performing the post processing.
  75656. * @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)
  75657. */
  75658. function DepthOfFieldEffect(scene, depthTexture, blurLevel, pipelineTextureType, blockCompilation) {
  75659. if (blurLevel === void 0) { blurLevel = DepthOfFieldEffectBlurLevel.Low; }
  75660. if (pipelineTextureType === void 0) { pipelineTextureType = 0; }
  75661. if (blockCompilation === void 0) { blockCompilation = false; }
  75662. var _this = _super.call(this, scene.getEngine(), "depth of field", function () {
  75663. return _this._effects;
  75664. }, true) || this;
  75665. /**
  75666. * Internal post processes in depth of field effect
  75667. */
  75668. _this._effects = [];
  75669. // Circle of confusion value for each pixel is used to determine how much to blur that pixel
  75670. _this._circleOfConfusion = new BABYLON.CircleOfConfusionPostProcess("circleOfConfusion", depthTexture, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  75671. // 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)
  75672. // Blur the image but do not blur on sharp far to near distance changes to avoid bleeding artifacts
  75673. // See section 2.6.2 http://fileadmin.cs.lth.se/cs/education/edan35/lectures/12dof.pdf
  75674. _this._depthOfFieldBlurY = [];
  75675. _this._depthOfFieldBlurX = [];
  75676. var blurCount = 1;
  75677. var kernelSize = 15;
  75678. switch (blurLevel) {
  75679. case DepthOfFieldEffectBlurLevel.High: {
  75680. blurCount = 3;
  75681. kernelSize = 51;
  75682. break;
  75683. }
  75684. case DepthOfFieldEffectBlurLevel.Medium: {
  75685. blurCount = 2;
  75686. kernelSize = 31;
  75687. break;
  75688. }
  75689. default: {
  75690. kernelSize = 15;
  75691. blurCount = 1;
  75692. break;
  75693. }
  75694. }
  75695. var adjustedKernelSize = kernelSize / Math.pow(2, blurCount - 1);
  75696. var ratio = 1.0;
  75697. for (var i = 0; i < blurCount; i++) {
  75698. 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);
  75699. blurY.autoClear = false;
  75700. ratio = 0.75 / Math.pow(2, i);
  75701. 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);
  75702. blurX.autoClear = false;
  75703. _this._depthOfFieldBlurY.push(blurY);
  75704. _this._depthOfFieldBlurX.push(blurX);
  75705. }
  75706. // Set all post processes on the effect.
  75707. _this._effects = [_this._circleOfConfusion];
  75708. for (var i = 0; i < _this._depthOfFieldBlurX.length; i++) {
  75709. _this._effects.push(_this._depthOfFieldBlurY[i]);
  75710. _this._effects.push(_this._depthOfFieldBlurX[i]);
  75711. }
  75712. // Merge blurred images with original image based on circleOfConfusion
  75713. _this._dofMerge = new BABYLON.DepthOfFieldMergePostProcess("dofMerge", _this._circleOfConfusion, _this._circleOfConfusion, _this._depthOfFieldBlurX, ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  75714. _this._dofMerge.autoClear = false;
  75715. _this._effects.push(_this._dofMerge);
  75716. return _this;
  75717. }
  75718. Object.defineProperty(DepthOfFieldEffect.prototype, "focalLength", {
  75719. get: function () {
  75720. return this._circleOfConfusion.focalLength;
  75721. },
  75722. /**
  75723. * The focal the length of the camera used in the effect in scene units/1000 (eg. millimeter)
  75724. */
  75725. set: function (value) {
  75726. this._circleOfConfusion.focalLength = value;
  75727. },
  75728. enumerable: true,
  75729. configurable: true
  75730. });
  75731. Object.defineProperty(DepthOfFieldEffect.prototype, "fStop", {
  75732. get: function () {
  75733. return this._circleOfConfusion.fStop;
  75734. },
  75735. /**
  75736. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  75737. */
  75738. set: function (value) {
  75739. this._circleOfConfusion.fStop = value;
  75740. },
  75741. enumerable: true,
  75742. configurable: true
  75743. });
  75744. Object.defineProperty(DepthOfFieldEffect.prototype, "focusDistance", {
  75745. get: function () {
  75746. return this._circleOfConfusion.focusDistance;
  75747. },
  75748. /**
  75749. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  75750. */
  75751. set: function (value) {
  75752. this._circleOfConfusion.focusDistance = value;
  75753. },
  75754. enumerable: true,
  75755. configurable: true
  75756. });
  75757. Object.defineProperty(DepthOfFieldEffect.prototype, "lensSize", {
  75758. get: function () {
  75759. return this._circleOfConfusion.lensSize;
  75760. },
  75761. /**
  75762. * 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.
  75763. */
  75764. set: function (value) {
  75765. this._circleOfConfusion.lensSize = value;
  75766. },
  75767. enumerable: true,
  75768. configurable: true
  75769. });
  75770. Object.defineProperty(DepthOfFieldEffect.prototype, "depthTexture", {
  75771. /**
  75772. * 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.
  75773. */
  75774. set: function (value) {
  75775. this._circleOfConfusion.depthTexture = value;
  75776. },
  75777. enumerable: true,
  75778. configurable: true
  75779. });
  75780. /**
  75781. * Disposes each of the internal effects for a given camera.
  75782. * @param camera The camera to dispose the effect on.
  75783. */
  75784. DepthOfFieldEffect.prototype.disposeEffects = function (camera) {
  75785. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  75786. this._effects[effectIndex].dispose(camera);
  75787. }
  75788. };
  75789. /**
  75790. * Internal
  75791. */
  75792. DepthOfFieldEffect.prototype._updateEffects = function () {
  75793. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  75794. this._effects[effectIndex].updateEffect();
  75795. }
  75796. };
  75797. /**
  75798. * Internal
  75799. * @returns if all the contained post processes are ready.
  75800. */
  75801. DepthOfFieldEffect.prototype._isReady = function () {
  75802. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  75803. if (!this._effects[effectIndex].isReady()) {
  75804. return false;
  75805. }
  75806. }
  75807. return true;
  75808. };
  75809. return DepthOfFieldEffect;
  75810. }(BABYLON.PostProcessRenderEffect));
  75811. BABYLON.DepthOfFieldEffect = DepthOfFieldEffect;
  75812. })(BABYLON || (BABYLON = {}));
  75813. //# sourceMappingURL=babylon.depthOfFieldEffect.js.map
  75814. var BABYLON;
  75815. (function (BABYLON) {
  75816. /**
  75817. * The BloomMergePostProcess merges blurred images with the original based on the values of the circle of confusion.
  75818. */
  75819. var BloomMergePostProcess = /** @class */ (function (_super) {
  75820. __extends(BloomMergePostProcess, _super);
  75821. /**
  75822. * Creates a new instance of @see BloomMergePostProcess
  75823. * @param name The name of the effect.
  75824. * @param originalFromInput Post process which's input will be used for the merge.
  75825. * @param blurred Blurred highlights post process which's output will be used.
  75826. * @param weight Weight of the bloom to be added to the original input.
  75827. * @param options The required width/height ratio to downsize to before computing the render pass.
  75828. * @param camera The camera to apply the render pass to.
  75829. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  75830. * @param engine The engine which the post process will be applied. (default: current engine)
  75831. * @param reusable If the post process can be reused on the same frame. (default: false)
  75832. * @param textureType Type of textures used when performing the post process. (default: 0)
  75833. * @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)
  75834. */
  75835. function BloomMergePostProcess(name, originalFromInput, blurred, /** Weight of the bloom to be added to the original input. */ weight, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  75836. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  75837. if (blockCompilation === void 0) { blockCompilation = false; }
  75838. var _this = _super.call(this, name, "bloomMerge", ["bloomWeight"], ["circleOfConfusionSampler", "blurStep0", "blurStep1", "blurStep2", "bloomBlur"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, true) || this;
  75839. _this.weight = weight;
  75840. _this.onApplyObservable.add(function (effect) {
  75841. effect.setTextureFromPostProcess("textureSampler", originalFromInput);
  75842. effect.setTextureFromPostProcessOutput("bloomBlur", blurred);
  75843. effect.setFloat("bloomWeight", _this.weight);
  75844. });
  75845. if (!blockCompilation) {
  75846. _this.updateEffect();
  75847. }
  75848. return _this;
  75849. }
  75850. return BloomMergePostProcess;
  75851. }(BABYLON.PostProcess));
  75852. BABYLON.BloomMergePostProcess = BloomMergePostProcess;
  75853. })(BABYLON || (BABYLON = {}));
  75854. //# sourceMappingURL=babylon.bloomMergePostProcess.js.map
  75855. var BABYLON;
  75856. (function (BABYLON) {
  75857. /**
  75858. * 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.
  75859. */
  75860. var ExtractHighlightsPostProcess = /** @class */ (function (_super) {
  75861. __extends(ExtractHighlightsPostProcess, _super);
  75862. function ExtractHighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  75863. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  75864. if (blockCompilation === void 0) { blockCompilation = false; }
  75865. var _this = _super.call(this, name, "extractHighlights", ["threshold", "exposure"], null, options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  75866. /**
  75867. * The luminance threshold, pixels below this value will be set to black.
  75868. */
  75869. _this.threshold = 0.9;
  75870. /**
  75871. * Internal
  75872. */
  75873. _this._exposure = 1;
  75874. /**
  75875. * Post process which has the input texture to be used when performing highlight extraction
  75876. */
  75877. _this._inputPostProcess = null;
  75878. _this.onApplyObservable.add(function (effect) {
  75879. if (_this._inputPostProcess) {
  75880. effect.setTextureFromPostProcess("textureSampler", _this._inputPostProcess);
  75881. }
  75882. effect.setFloat('threshold', Math.pow(_this.threshold, BABYLON.ToGammaSpace));
  75883. effect.setFloat('exposure', _this._exposure);
  75884. });
  75885. return _this;
  75886. }
  75887. return ExtractHighlightsPostProcess;
  75888. }(BABYLON.PostProcess));
  75889. BABYLON.ExtractHighlightsPostProcess = ExtractHighlightsPostProcess;
  75890. })(BABYLON || (BABYLON = {}));
  75891. //# sourceMappingURL=babylon.extractHighlightsPostProcess.js.map
  75892. var BABYLON;
  75893. (function (BABYLON) {
  75894. /**
  75895. * The bloom effect spreads bright areas of an image to simulate artifacts seen in cameras
  75896. */
  75897. var BloomEffect = /** @class */ (function (_super) {
  75898. __extends(BloomEffect, _super);
  75899. /**
  75900. * Creates a new instance of @see BloomEffect
  75901. * @param scene The scene the effect belongs to.
  75902. * @param bloomScale The ratio of the blur texture to the input texture that should be used to compute the bloom.
  75903. * @param bloomKernel The size of the kernel to be used when applying the blur.
  75904. * @param bloomWeight The the strength of bloom.
  75905. * @param pipelineTextureType The type of texture to be used when performing the post processing.
  75906. * @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)
  75907. */
  75908. function BloomEffect(scene, bloomScale, bloomWeight, bloomKernel, pipelineTextureType, blockCompilation) {
  75909. if (pipelineTextureType === void 0) { pipelineTextureType = 0; }
  75910. if (blockCompilation === void 0) { blockCompilation = false; }
  75911. var _this = _super.call(this, scene.getEngine(), "bloom", function () {
  75912. return _this._effects;
  75913. }, true) || this;
  75914. _this.bloomScale = bloomScale;
  75915. /**
  75916. * Internal
  75917. */
  75918. _this._effects = [];
  75919. _this._downscale = new BABYLON.ExtractHighlightsPostProcess("highlights", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  75920. _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);
  75921. _this._blurX.alwaysForcePOT = true;
  75922. _this._blurX.autoClear = false;
  75923. _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);
  75924. _this._blurY.alwaysForcePOT = true;
  75925. _this._blurY.autoClear = false;
  75926. _this.kernel = bloomKernel;
  75927. _this._effects = [_this._downscale, _this._blurX, _this._blurY];
  75928. _this._merge = new BABYLON.BloomMergePostProcess("bloomMerge", _this._downscale, _this._blurY, bloomWeight, bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  75929. _this._merge.autoClear = false;
  75930. _this._effects.push(_this._merge);
  75931. return _this;
  75932. }
  75933. Object.defineProperty(BloomEffect.prototype, "threshold", {
  75934. /**
  75935. * The luminance threshold to find bright areas of the image to bloom.
  75936. */
  75937. get: function () {
  75938. return this._downscale.threshold;
  75939. },
  75940. set: function (value) {
  75941. this._downscale.threshold = value;
  75942. },
  75943. enumerable: true,
  75944. configurable: true
  75945. });
  75946. Object.defineProperty(BloomEffect.prototype, "weight", {
  75947. /**
  75948. * The strength of the bloom.
  75949. */
  75950. get: function () {
  75951. return this._merge.weight;
  75952. },
  75953. set: function (value) {
  75954. this._merge.weight = value;
  75955. },
  75956. enumerable: true,
  75957. configurable: true
  75958. });
  75959. Object.defineProperty(BloomEffect.prototype, "kernel", {
  75960. /**
  75961. * Specifies the size of the bloom blur kernel, relative to the final output size
  75962. */
  75963. get: function () {
  75964. return this._blurX.kernel / this.bloomScale;
  75965. },
  75966. set: function (value) {
  75967. this._blurX.kernel = value * this.bloomScale;
  75968. this._blurY.kernel = value * this.bloomScale;
  75969. },
  75970. enumerable: true,
  75971. configurable: true
  75972. });
  75973. /**
  75974. * Disposes each of the internal effects for a given camera.
  75975. * @param camera The camera to dispose the effect on.
  75976. */
  75977. BloomEffect.prototype.disposeEffects = function (camera) {
  75978. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  75979. this._effects[effectIndex].dispose(camera);
  75980. }
  75981. };
  75982. /**
  75983. * Internal
  75984. */
  75985. BloomEffect.prototype._updateEffects = function () {
  75986. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  75987. this._effects[effectIndex].updateEffect();
  75988. }
  75989. };
  75990. /**
  75991. * Internal
  75992. * @returns if all the contained post processes are ready.
  75993. */
  75994. BloomEffect.prototype._isReady = function () {
  75995. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  75996. if (!this._effects[effectIndex].isReady()) {
  75997. return false;
  75998. }
  75999. }
  76000. return true;
  76001. };
  76002. return BloomEffect;
  76003. }(BABYLON.PostProcessRenderEffect));
  76004. BABYLON.BloomEffect = BloomEffect;
  76005. })(BABYLON || (BABYLON = {}));
  76006. //# sourceMappingURL=babylon.bloomEffect.js.map
  76007. var BABYLON;
  76008. (function (BABYLON) {
  76009. /**
  76010. * The default rendering pipeline can be added to a scene to apply common post processing effects such as anti-aliasing or depth of field.
  76011. * See https://doc.babylonjs.com/how_to/using_default_rendering_pipeline
  76012. */
  76013. var DefaultRenderingPipeline = /** @class */ (function (_super) {
  76014. __extends(DefaultRenderingPipeline, _super);
  76015. /**
  76016. * @constructor
  76017. * @param {string} name - The rendering pipeline name (default: "")
  76018. * @param {boolean} hdr - If high dynamic range textures should be used (default: true)
  76019. * @param {BABYLON.Scene} scene - The scene linked to this pipeline (default: the last created scene)
  76020. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to (default: scene.cameras)
  76021. * @param {boolean} automaticBuild - if false, you will have to manually call prepare() to update the pipeline (default: true)
  76022. */
  76023. function DefaultRenderingPipeline(name, hdr, scene, cameras, automaticBuild) {
  76024. if (name === void 0) { name = ""; }
  76025. if (hdr === void 0) { hdr = true; }
  76026. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  76027. if (automaticBuild === void 0) { automaticBuild = true; }
  76028. var _this = _super.call(this, scene.getEngine(), name) || this;
  76029. _this._originalCameras = [];
  76030. /**
  76031. * ID of the sharpen post process,
  76032. */
  76033. _this.SharpenPostProcessId = "SharpenPostProcessEffect";
  76034. /**
  76035. * ID of the image processing post process;
  76036. */
  76037. _this.ImageProcessingPostProcessId = "ImageProcessingPostProcessEffect";
  76038. /**
  76039. * ID of the Fast Approximate Anti-Aliasing post process;
  76040. */
  76041. _this.FxaaPostProcessId = "FxaaPostProcessEffect";
  76042. /**
  76043. * ID of the chromatic aberration post process,
  76044. */
  76045. _this.ChromaticAberrationPostProcessId = "ChromaticAberrationPostProcessEffect";
  76046. /**
  76047. * ID of the grain post process
  76048. */
  76049. _this.GrainPostProcessId = "GrainPostProcessEffect";
  76050. /**
  76051. * Glow post process which adds a glow to emmisive areas of the image
  76052. */
  76053. _this._glowLayer = null;
  76054. /**
  76055. * Animations which can be used to tweak settings over a period of time
  76056. */
  76057. _this.animations = [];
  76058. _this._imageProcessingConfigurationObserver = null;
  76059. // Values
  76060. _this._sharpenEnabled = false;
  76061. _this._bloomEnabled = false;
  76062. _this._depthOfFieldEnabled = false;
  76063. _this._depthOfFieldBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel.Low;
  76064. _this._fxaaEnabled = false;
  76065. _this._imageProcessingEnabled = true;
  76066. _this._bloomScale = 0.5;
  76067. _this._chromaticAberrationEnabled = false;
  76068. _this._grainEnabled = false;
  76069. _this._buildAllowed = true;
  76070. _this._resizeObserver = null;
  76071. _this._hardwareScaleLevel = 1.0;
  76072. _this._bloomKernel = 64;
  76073. /**
  76074. * Specifies the weight of the bloom in the final rendering
  76075. */
  76076. _this._bloomWeight = 0.15;
  76077. /**
  76078. * Specifies the luma threshold for the area that will be blurred by the bloom
  76079. */
  76080. _this._bloomThreshold = 0.9;
  76081. _this._samples = 1;
  76082. _this._hasCleared = false;
  76083. _this._prevPostProcess = null;
  76084. _this._prevPrevPostProcess = null;
  76085. _this._cameras = cameras || scene.cameras;
  76086. _this._originalCameras = _this._cameras.slice();
  76087. _this._buildAllowed = automaticBuild;
  76088. // Initialize
  76089. _this._scene = scene;
  76090. var caps = _this._scene.getEngine().getCaps();
  76091. _this._hdr = hdr && (caps.textureHalfFloatRender || caps.textureFloatRender);
  76092. // Misc
  76093. if (_this._hdr) {
  76094. if (caps.textureHalfFloatRender) {
  76095. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  76096. }
  76097. else if (caps.textureFloatRender) {
  76098. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  76099. }
  76100. }
  76101. else {
  76102. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  76103. }
  76104. // Attach
  76105. scene.postProcessRenderPipelineManager.addPipeline(_this);
  76106. var engine = _this._scene.getEngine();
  76107. // Create post processes before hand so they can be modified before enabled.
  76108. // Block compilation flag is set to true to avoid compilation prior to use, these will be updated on first use in build pipeline.
  76109. _this.sharpen = new BABYLON.SharpenPostProcess("sharpen", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  76110. _this._sharpenEffect = new BABYLON.PostProcessRenderEffect(engine, _this.SharpenPostProcessId, function () { return _this.sharpen; }, true);
  76111. _this.depthOfField = new BABYLON.DepthOfFieldEffect(_this._scene, null, _this._depthOfFieldBlurLevel, _this._defaultPipelineTextureType, true);
  76112. _this.bloom = new BABYLON.BloomEffect(_this._scene, _this._bloomScale, _this._bloomWeight, _this.bloomKernel, _this._defaultPipelineTextureType, true);
  76113. _this.chromaticAberration = new BABYLON.ChromaticAberrationPostProcess("ChromaticAberration", engine.getRenderWidth(), engine.getRenderHeight(), 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  76114. _this._chromaticAberrationEffect = new BABYLON.PostProcessRenderEffect(engine, _this.ChromaticAberrationPostProcessId, function () { return _this.chromaticAberration; }, true);
  76115. _this.grain = new BABYLON.GrainPostProcess("Grain", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  76116. _this._grainEffect = new BABYLON.PostProcessRenderEffect(engine, _this.GrainPostProcessId, function () { return _this.grain; }, true);
  76117. _this._resizeObserver = engine.onResizeObservable.add(function () {
  76118. _this._hardwareScaleLevel = engine.getHardwareScalingLevel();
  76119. _this.bloomKernel = _this.bloomKernel;
  76120. });
  76121. _this._imageProcessingConfigurationObserver = _this._scene.imageProcessingConfiguration.onUpdateParameters.add(function () {
  76122. _this.bloom._downscale._exposure = _this._scene.imageProcessingConfiguration.exposure;
  76123. });
  76124. _this._buildPipeline();
  76125. return _this;
  76126. }
  76127. Object.defineProperty(DefaultRenderingPipeline.prototype, "sharpenEnabled", {
  76128. get: function () {
  76129. return this._sharpenEnabled;
  76130. },
  76131. /**
  76132. * Enable or disable the sharpen process from the pipeline
  76133. */
  76134. set: function (enabled) {
  76135. if (this._sharpenEnabled === enabled) {
  76136. return;
  76137. }
  76138. this._sharpenEnabled = enabled;
  76139. this._buildPipeline();
  76140. },
  76141. enumerable: true,
  76142. configurable: true
  76143. });
  76144. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomKernel", {
  76145. /**
  76146. * Specifies the size of the bloom blur kernel, relative to the final output size
  76147. */
  76148. get: function () {
  76149. return this._bloomKernel;
  76150. },
  76151. set: function (value) {
  76152. this._bloomKernel = value;
  76153. this.bloom.kernel = value / this._hardwareScaleLevel;
  76154. },
  76155. enumerable: true,
  76156. configurable: true
  76157. });
  76158. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomWeight", {
  76159. get: function () {
  76160. return this._bloomWeight;
  76161. },
  76162. /**
  76163. * The strength of the bloom.
  76164. */
  76165. set: function (value) {
  76166. if (this._bloomWeight === value) {
  76167. return;
  76168. }
  76169. this.bloom.weight = value;
  76170. this._bloomWeight = value;
  76171. },
  76172. enumerable: true,
  76173. configurable: true
  76174. });
  76175. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomThreshold", {
  76176. get: function () {
  76177. return this._bloomThreshold;
  76178. },
  76179. /**
  76180. * The strength of the bloom.
  76181. */
  76182. set: function (value) {
  76183. if (this._bloomThreshold === value) {
  76184. return;
  76185. }
  76186. this.bloom.threshold = value;
  76187. this._bloomThreshold = value;
  76188. },
  76189. enumerable: true,
  76190. configurable: true
  76191. });
  76192. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomScale", {
  76193. get: function () {
  76194. return this._bloomScale;
  76195. },
  76196. /**
  76197. * The scale of the bloom, lower value will provide better performance.
  76198. */
  76199. set: function (value) {
  76200. if (this._bloomScale === value) {
  76201. return;
  76202. }
  76203. this._bloomScale = value;
  76204. // recreate bloom and dispose old as this setting is not dynamic
  76205. this._rebuildBloom();
  76206. this._buildPipeline();
  76207. },
  76208. enumerable: true,
  76209. configurable: true
  76210. });
  76211. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomEnabled", {
  76212. get: function () {
  76213. return this._bloomEnabled;
  76214. },
  76215. /**
  76216. * Enable or disable the bloom from the pipeline
  76217. */
  76218. set: function (enabled) {
  76219. if (this._bloomEnabled === enabled) {
  76220. return;
  76221. }
  76222. this._bloomEnabled = enabled;
  76223. this._buildPipeline();
  76224. },
  76225. enumerable: true,
  76226. configurable: true
  76227. });
  76228. DefaultRenderingPipeline.prototype._rebuildBloom = function () {
  76229. // recreate bloom and dispose old as this setting is not dynamic
  76230. var oldBloom = this.bloom;
  76231. this.bloom = new BABYLON.BloomEffect(this._scene, this.bloomScale, this._bloomWeight, this.bloomKernel, this._defaultPipelineTextureType, false);
  76232. this.bloom.threshold = oldBloom.threshold;
  76233. for (var i = 0; i < this._cameras.length; i++) {
  76234. oldBloom.disposeEffects(this._cameras[i]);
  76235. }
  76236. };
  76237. Object.defineProperty(DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", {
  76238. /**
  76239. * If the depth of field is enabled.
  76240. */
  76241. get: function () {
  76242. return this._depthOfFieldEnabled;
  76243. },
  76244. set: function (enabled) {
  76245. if (this._depthOfFieldEnabled === enabled) {
  76246. return;
  76247. }
  76248. this._depthOfFieldEnabled = enabled;
  76249. this._buildPipeline();
  76250. },
  76251. enumerable: true,
  76252. configurable: true
  76253. });
  76254. Object.defineProperty(DefaultRenderingPipeline.prototype, "depthOfFieldBlurLevel", {
  76255. /**
  76256. * Blur level of the depth of field effect. (Higher blur will effect performance)
  76257. */
  76258. get: function () {
  76259. return this._depthOfFieldBlurLevel;
  76260. },
  76261. set: function (value) {
  76262. if (this._depthOfFieldBlurLevel === value) {
  76263. return;
  76264. }
  76265. this._depthOfFieldBlurLevel = value;
  76266. // recreate dof and dispose old as this setting is not dynamic
  76267. var oldDof = this.depthOfField;
  76268. this.depthOfField = new BABYLON.DepthOfFieldEffect(this._scene, null, this._depthOfFieldBlurLevel, this._defaultPipelineTextureType, false);
  76269. this.depthOfField.focalLength = oldDof.focalLength;
  76270. this.depthOfField.focusDistance = oldDof.focusDistance;
  76271. this.depthOfField.fStop = oldDof.fStop;
  76272. this.depthOfField.lensSize = oldDof.lensSize;
  76273. for (var i = 0; i < this._cameras.length; i++) {
  76274. oldDof.disposeEffects(this._cameras[i]);
  76275. }
  76276. this._buildPipeline();
  76277. },
  76278. enumerable: true,
  76279. configurable: true
  76280. });
  76281. Object.defineProperty(DefaultRenderingPipeline.prototype, "fxaaEnabled", {
  76282. get: function () {
  76283. return this._fxaaEnabled;
  76284. },
  76285. /**
  76286. * If the anti aliasing is enabled.
  76287. */
  76288. set: function (enabled) {
  76289. if (this._fxaaEnabled === enabled) {
  76290. return;
  76291. }
  76292. this._fxaaEnabled = enabled;
  76293. this._buildPipeline();
  76294. },
  76295. enumerable: true,
  76296. configurable: true
  76297. });
  76298. Object.defineProperty(DefaultRenderingPipeline.prototype, "samples", {
  76299. get: function () {
  76300. return this._samples;
  76301. },
  76302. /**
  76303. * MSAA sample count, setting this to 4 will provide 4x anti aliasing. (default: 1)
  76304. */
  76305. set: function (sampleCount) {
  76306. if (this._samples === sampleCount) {
  76307. return;
  76308. }
  76309. this._samples = sampleCount;
  76310. this._buildPipeline();
  76311. },
  76312. enumerable: true,
  76313. configurable: true
  76314. });
  76315. Object.defineProperty(DefaultRenderingPipeline.prototype, "imageProcessingEnabled", {
  76316. get: function () {
  76317. return this._imageProcessingEnabled;
  76318. },
  76319. /**
  76320. * If image processing is enabled.
  76321. */
  76322. set: function (enabled) {
  76323. if (this._imageProcessingEnabled === enabled) {
  76324. return;
  76325. }
  76326. this._imageProcessingEnabled = enabled;
  76327. this._buildPipeline();
  76328. },
  76329. enumerable: true,
  76330. configurable: true
  76331. });
  76332. Object.defineProperty(DefaultRenderingPipeline.prototype, "glowLayerEnabled", {
  76333. get: function () {
  76334. return this._glowLayer == null;
  76335. },
  76336. /**
  76337. * If glow layer is enabled. (Adds a glow effect to emmissive materials)
  76338. */
  76339. set: function (enabled) {
  76340. if (enabled && !this._glowLayer) {
  76341. this._glowLayer = new BABYLON.GlowLayer("", this._scene);
  76342. }
  76343. else if (!enabled && this._glowLayer) {
  76344. this._glowLayer.dispose();
  76345. this._glowLayer = null;
  76346. }
  76347. },
  76348. enumerable: true,
  76349. configurable: true
  76350. });
  76351. Object.defineProperty(DefaultRenderingPipeline.prototype, "chromaticAberrationEnabled", {
  76352. get: function () {
  76353. return this._chromaticAberrationEnabled;
  76354. },
  76355. /**
  76356. * Enable or disable the chromaticAberration process from the pipeline
  76357. */
  76358. set: function (enabled) {
  76359. if (this._chromaticAberrationEnabled === enabled) {
  76360. return;
  76361. }
  76362. this._chromaticAberrationEnabled = enabled;
  76363. this._buildPipeline();
  76364. },
  76365. enumerable: true,
  76366. configurable: true
  76367. });
  76368. Object.defineProperty(DefaultRenderingPipeline.prototype, "grainEnabled", {
  76369. get: function () {
  76370. return this._grainEnabled;
  76371. },
  76372. /**
  76373. * Enable or disable the grain process from the pipeline
  76374. */
  76375. set: function (enabled) {
  76376. if (this._grainEnabled === enabled) {
  76377. return;
  76378. }
  76379. this._grainEnabled = enabled;
  76380. this._buildPipeline();
  76381. },
  76382. enumerable: true,
  76383. configurable: true
  76384. });
  76385. /**
  76386. * Force the compilation of the entire pipeline.
  76387. */
  76388. DefaultRenderingPipeline.prototype.prepare = function () {
  76389. var previousState = this._buildAllowed;
  76390. this._buildAllowed = true;
  76391. this._buildPipeline();
  76392. this._buildAllowed = previousState;
  76393. };
  76394. DefaultRenderingPipeline.prototype._setAutoClearAndTextureSharing = function (postProcess, skipTextureSharing) {
  76395. if (skipTextureSharing === void 0) { skipTextureSharing = false; }
  76396. if (this._hasCleared) {
  76397. postProcess.autoClear = false;
  76398. }
  76399. else {
  76400. postProcess.autoClear = true;
  76401. this._scene.autoClear = false;
  76402. this._hasCleared = true;
  76403. }
  76404. if (!skipTextureSharing) {
  76405. if (this._prevPrevPostProcess) {
  76406. postProcess.shareOutputWith(this._prevPrevPostProcess);
  76407. }
  76408. else {
  76409. postProcess.useOwnOutput();
  76410. }
  76411. if (this._prevPostProcess) {
  76412. this._prevPrevPostProcess = this._prevPostProcess;
  76413. }
  76414. this._prevPostProcess = postProcess;
  76415. }
  76416. };
  76417. DefaultRenderingPipeline.prototype._buildPipeline = function () {
  76418. var _this = this;
  76419. if (!this._buildAllowed) {
  76420. return;
  76421. }
  76422. this._scene.autoClear = true;
  76423. var engine = this._scene.getEngine();
  76424. this._disposePostProcesses();
  76425. if (this._cameras !== null) {
  76426. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  76427. // get back cameras to be used to reattach pipeline
  76428. this._cameras = this._originalCameras.slice();
  76429. }
  76430. this._reset();
  76431. this._prevPostProcess = null;
  76432. this._prevPrevPostProcess = null;
  76433. this._hasCleared = false;
  76434. if (this.depthOfFieldEnabled) {
  76435. var depthTexture = this._scene.enableDepthRenderer(this._cameras[0]).getDepthMap();
  76436. this.depthOfField.depthTexture = depthTexture;
  76437. if (!this.depthOfField._isReady()) {
  76438. this.depthOfField._updateEffects();
  76439. }
  76440. this.addEffect(this.depthOfField);
  76441. this._setAutoClearAndTextureSharing(this.depthOfField._effects[0], true);
  76442. }
  76443. if (this.bloomEnabled) {
  76444. if (!this.bloom._isReady()) {
  76445. this.bloom._updateEffects();
  76446. }
  76447. this.addEffect(this.bloom);
  76448. this._setAutoClearAndTextureSharing(this.bloom._effects[0], true);
  76449. }
  76450. if (this._imageProcessingEnabled) {
  76451. this.imageProcessing = new BABYLON.ImageProcessingPostProcess("imageProcessing", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  76452. if (this._hdr) {
  76453. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.ImageProcessingPostProcessId, function () { return _this.imageProcessing; }, true));
  76454. this._setAutoClearAndTextureSharing(this.imageProcessing);
  76455. }
  76456. else {
  76457. this._scene.imageProcessingConfiguration.applyByPostProcess = false;
  76458. }
  76459. }
  76460. if (this.sharpenEnabled) {
  76461. if (!this.sharpen.isReady()) {
  76462. this.sharpen.updateEffect();
  76463. }
  76464. this.addEffect(this._sharpenEffect);
  76465. this._setAutoClearAndTextureSharing(this.sharpen);
  76466. }
  76467. if (this.grainEnabled) {
  76468. if (!this.grain.isReady()) {
  76469. this.grain.updateEffect();
  76470. }
  76471. this.addEffect(this._grainEffect);
  76472. this._setAutoClearAndTextureSharing(this.grain);
  76473. }
  76474. if (this.chromaticAberrationEnabled) {
  76475. if (!this.chromaticAberration.isReady()) {
  76476. this.chromaticAberration.updateEffect();
  76477. }
  76478. this.addEffect(this._chromaticAberrationEffect);
  76479. this._setAutoClearAndTextureSharing(this.chromaticAberration);
  76480. }
  76481. if (this.fxaaEnabled) {
  76482. this.fxaa = new BABYLON.FxaaPostProcess("fxaa", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  76483. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FxaaPostProcessId, function () { return _this.fxaa; }, true));
  76484. this._setAutoClearAndTextureSharing(this.fxaa, true);
  76485. }
  76486. if (this._cameras !== null) {
  76487. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  76488. }
  76489. if (!this._enableMSAAOnFirstPostProcess(this.samples) && this.samples > 1) {
  76490. BABYLON.Tools.Warn("MSAA failed to enable, MSAA is only supported in browsers that support webGL >= 2.0");
  76491. }
  76492. };
  76493. DefaultRenderingPipeline.prototype._disposePostProcesses = function (disposeNonRecreated) {
  76494. if (disposeNonRecreated === void 0) { disposeNonRecreated = false; }
  76495. for (var i = 0; i < this._cameras.length; i++) {
  76496. var camera = this._cameras[i];
  76497. if (this.imageProcessing) {
  76498. this.imageProcessing.dispose(camera);
  76499. }
  76500. if (this.fxaa) {
  76501. this.fxaa.dispose(camera);
  76502. }
  76503. // These are created in the constructor and should not be disposed on every pipeline change
  76504. if (disposeNonRecreated) {
  76505. if (this.sharpen) {
  76506. this.sharpen.dispose(camera);
  76507. }
  76508. if (this.depthOfField) {
  76509. this.depthOfField.disposeEffects(camera);
  76510. }
  76511. if (this.bloom) {
  76512. this.bloom.disposeEffects(camera);
  76513. }
  76514. if (this.chromaticAberration) {
  76515. this.chromaticAberration.dispose(camera);
  76516. }
  76517. if (this.grain) {
  76518. this.grain.dispose(camera);
  76519. }
  76520. if (this._glowLayer) {
  76521. this._glowLayer.dispose();
  76522. }
  76523. }
  76524. }
  76525. this.imageProcessing = null;
  76526. this.fxaa = null;
  76527. if (disposeNonRecreated) {
  76528. this.sharpen = null;
  76529. this._sharpenEffect = null;
  76530. this.depthOfField = null;
  76531. this.bloom = null;
  76532. this.chromaticAberration = null;
  76533. this._chromaticAberrationEffect = null;
  76534. this.grain = null;
  76535. this._grainEffect = null;
  76536. this._glowLayer = null;
  76537. }
  76538. };
  76539. /**
  76540. * Dispose of the pipeline and stop all post processes
  76541. */
  76542. DefaultRenderingPipeline.prototype.dispose = function () {
  76543. this._disposePostProcesses(true);
  76544. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  76545. this._scene.autoClear = true;
  76546. if (this._resizeObserver) {
  76547. this._scene.getEngine().onResizeObservable.remove(this._resizeObserver);
  76548. this._resizeObserver = null;
  76549. }
  76550. this._scene.imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingConfigurationObserver);
  76551. _super.prototype.dispose.call(this);
  76552. };
  76553. /**
  76554. * Serialize the rendering pipeline (Used when exporting)
  76555. * @returns the serialized object
  76556. */
  76557. DefaultRenderingPipeline.prototype.serialize = function () {
  76558. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  76559. serializationObject.customType = "DefaultRenderingPipeline";
  76560. return serializationObject;
  76561. };
  76562. /**
  76563. * Parse the serialized pipeline
  76564. * @param source Source pipeline.
  76565. * @param scene The scene to load the pipeline to.
  76566. * @param rootUrl The URL of the serialized pipeline.
  76567. * @returns An instantiated pipeline from the serialized object.
  76568. */
  76569. DefaultRenderingPipeline.Parse = function (source, scene, rootUrl) {
  76570. return BABYLON.SerializationHelper.Parse(function () { return new DefaultRenderingPipeline(source._name, source._name._hdr, scene); }, source, scene, rootUrl);
  76571. };
  76572. __decorate([
  76573. BABYLON.serialize()
  76574. ], DefaultRenderingPipeline.prototype, "sharpenEnabled", null);
  76575. __decorate([
  76576. BABYLON.serialize()
  76577. ], DefaultRenderingPipeline.prototype, "bloomKernel", null);
  76578. __decorate([
  76579. BABYLON.serialize()
  76580. ], DefaultRenderingPipeline.prototype, "_bloomWeight", void 0);
  76581. __decorate([
  76582. BABYLON.serialize()
  76583. ], DefaultRenderingPipeline.prototype, "_bloomThreshold", void 0);
  76584. __decorate([
  76585. BABYLON.serialize()
  76586. ], DefaultRenderingPipeline.prototype, "_hdr", void 0);
  76587. __decorate([
  76588. BABYLON.serialize()
  76589. ], DefaultRenderingPipeline.prototype, "bloomWeight", null);
  76590. __decorate([
  76591. BABYLON.serialize()
  76592. ], DefaultRenderingPipeline.prototype, "bloomThreshold", null);
  76593. __decorate([
  76594. BABYLON.serialize()
  76595. ], DefaultRenderingPipeline.prototype, "bloomScale", null);
  76596. __decorate([
  76597. BABYLON.serialize()
  76598. ], DefaultRenderingPipeline.prototype, "bloomEnabled", null);
  76599. __decorate([
  76600. BABYLON.serialize()
  76601. ], DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", null);
  76602. __decorate([
  76603. BABYLON.serialize()
  76604. ], DefaultRenderingPipeline.prototype, "depthOfFieldBlurLevel", null);
  76605. __decorate([
  76606. BABYLON.serialize()
  76607. ], DefaultRenderingPipeline.prototype, "fxaaEnabled", null);
  76608. __decorate([
  76609. BABYLON.serialize()
  76610. ], DefaultRenderingPipeline.prototype, "samples", null);
  76611. __decorate([
  76612. BABYLON.serialize()
  76613. ], DefaultRenderingPipeline.prototype, "imageProcessingEnabled", null);
  76614. __decorate([
  76615. BABYLON.serialize()
  76616. ], DefaultRenderingPipeline.prototype, "glowLayerEnabled", null);
  76617. __decorate([
  76618. BABYLON.serialize()
  76619. ], DefaultRenderingPipeline.prototype, "chromaticAberrationEnabled", null);
  76620. __decorate([
  76621. BABYLON.serialize()
  76622. ], DefaultRenderingPipeline.prototype, "grainEnabled", null);
  76623. return DefaultRenderingPipeline;
  76624. }(BABYLON.PostProcessRenderPipeline));
  76625. BABYLON.DefaultRenderingPipeline = DefaultRenderingPipeline;
  76626. })(BABYLON || (BABYLON = {}));
  76627. //# sourceMappingURL=babylon.defaultRenderingPipeline.js.map
  76628. var BABYLON;
  76629. (function (BABYLON) {
  76630. /**
  76631. * This renderer is helpfull to fill one of the render target with a geometry buffer.
  76632. */
  76633. var GeometryBufferRenderer = /** @class */ (function () {
  76634. /**
  76635. * Creates a new G Buffer for the scene
  76636. * @param scene The scene the buffer belongs to
  76637. * @param ratio How big is the buffer related to the main canvas.
  76638. */
  76639. function GeometryBufferRenderer(scene, ratio) {
  76640. if (ratio === void 0) { ratio = 1; }
  76641. this._enablePosition = false;
  76642. this._scene = scene;
  76643. this._ratio = ratio;
  76644. // Render target
  76645. this._createRenderTargets();
  76646. }
  76647. Object.defineProperty(GeometryBufferRenderer.prototype, "renderList", {
  76648. /**
  76649. * Set the render list (meshes to be rendered) used in the G buffer.
  76650. */
  76651. set: function (meshes) {
  76652. this._multiRenderTarget.renderList = meshes;
  76653. },
  76654. enumerable: true,
  76655. configurable: true
  76656. });
  76657. Object.defineProperty(GeometryBufferRenderer.prototype, "isSupported", {
  76658. /**
  76659. * Gets wether or not G buffer are supported by the running hardware.
  76660. * This requires draw buffer supports
  76661. */
  76662. get: function () {
  76663. return this._multiRenderTarget.isSupported;
  76664. },
  76665. enumerable: true,
  76666. configurable: true
  76667. });
  76668. Object.defineProperty(GeometryBufferRenderer.prototype, "enablePosition", {
  76669. /**
  76670. * Gets wether or not position are enabled for the G buffer.
  76671. */
  76672. get: function () {
  76673. return this._enablePosition;
  76674. },
  76675. /**
  76676. * Sets wether or not position are enabled for the G buffer.
  76677. */
  76678. set: function (enable) {
  76679. this._enablePosition = enable;
  76680. this.dispose();
  76681. this._createRenderTargets();
  76682. },
  76683. enumerable: true,
  76684. configurable: true
  76685. });
  76686. Object.defineProperty(GeometryBufferRenderer.prototype, "scene", {
  76687. /**
  76688. * Gets the scene associated with the buffer.
  76689. */
  76690. get: function () {
  76691. return this._scene;
  76692. },
  76693. enumerable: true,
  76694. configurable: true
  76695. });
  76696. Object.defineProperty(GeometryBufferRenderer.prototype, "ratio", {
  76697. /**
  76698. * Gets the ratio used by the buffer during its creation.
  76699. * How big is the buffer related to the main canvas.
  76700. */
  76701. get: function () {
  76702. return this._ratio;
  76703. },
  76704. enumerable: true,
  76705. configurable: true
  76706. });
  76707. /**
  76708. * Checks wether everything is ready to render a submesh to the G buffer.
  76709. * @param subMesh the submesh to check readiness for
  76710. * @param useInstances is the mesh drawn using instance or not
  76711. * @returns true if ready otherwise false
  76712. */
  76713. GeometryBufferRenderer.prototype.isReady = function (subMesh, useInstances) {
  76714. var material = subMesh.getMaterial();
  76715. if (material && material.disableDepthWrite) {
  76716. return false;
  76717. }
  76718. var defines = [];
  76719. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  76720. var mesh = subMesh.getMesh();
  76721. // Alpha test
  76722. if (material && material.needAlphaTesting()) {
  76723. defines.push("#define ALPHATEST");
  76724. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  76725. attribs.push(BABYLON.VertexBuffer.UVKind);
  76726. defines.push("#define UV1");
  76727. }
  76728. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  76729. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  76730. defines.push("#define UV2");
  76731. }
  76732. }
  76733. // Buffers
  76734. if (this._enablePosition) {
  76735. defines.push("#define POSITION");
  76736. }
  76737. // Bones
  76738. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  76739. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  76740. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  76741. if (mesh.numBoneInfluencers > 4) {
  76742. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  76743. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  76744. }
  76745. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  76746. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  76747. }
  76748. else {
  76749. defines.push("#define NUM_BONE_INFLUENCERS 0");
  76750. }
  76751. // Instances
  76752. if (useInstances) {
  76753. defines.push("#define INSTANCES");
  76754. attribs.push("world0");
  76755. attribs.push("world1");
  76756. attribs.push("world2");
  76757. attribs.push("world3");
  76758. }
  76759. // Get correct effect
  76760. var join = defines.join("\n");
  76761. if (this._cachedDefines !== join) {
  76762. this._cachedDefines = join;
  76763. this._effect = this._scene.getEngine().createEffect("geometry", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "view"], ["diffuseSampler"], join, undefined, undefined, undefined, { buffersCount: this._enablePosition ? 3 : 2 });
  76764. }
  76765. return this._effect.isReady();
  76766. };
  76767. /**
  76768. * Gets the current underlying G Buffer.
  76769. * @returns the buffer
  76770. */
  76771. GeometryBufferRenderer.prototype.getGBuffer = function () {
  76772. return this._multiRenderTarget;
  76773. };
  76774. Object.defineProperty(GeometryBufferRenderer.prototype, "samples", {
  76775. /**
  76776. * Gets the number of samples used to render the buffer (anti aliasing).
  76777. */
  76778. get: function () {
  76779. return this._multiRenderTarget.samples;
  76780. },
  76781. /**
  76782. * Sets the number of samples used to render the buffer (anti aliasing).
  76783. */
  76784. set: function (value) {
  76785. this._multiRenderTarget.samples = value;
  76786. },
  76787. enumerable: true,
  76788. configurable: true
  76789. });
  76790. /**
  76791. * Disposes the renderer and frees up associated resources.
  76792. */
  76793. GeometryBufferRenderer.prototype.dispose = function () {
  76794. this.getGBuffer().dispose();
  76795. };
  76796. GeometryBufferRenderer.prototype._createRenderTargets = function () {
  76797. var _this = this;
  76798. var engine = this._scene.getEngine();
  76799. var count = this._enablePosition ? 3 : 2;
  76800. 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 });
  76801. if (!this.isSupported) {
  76802. return;
  76803. }
  76804. this._multiRenderTarget.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  76805. this._multiRenderTarget.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  76806. this._multiRenderTarget.refreshRate = 1;
  76807. this._multiRenderTarget.renderParticles = false;
  76808. this._multiRenderTarget.renderList = null;
  76809. // set default depth value to 1.0 (far away)
  76810. this._multiRenderTarget.onClearObservable.add(function (engine) {
  76811. engine.clear(new BABYLON.Color4(0.0, 0.0, 0.0, 1.0), true, true, true);
  76812. });
  76813. // Custom render function
  76814. var renderSubMesh = function (subMesh) {
  76815. var mesh = subMesh.getRenderingMesh();
  76816. var scene = _this._scene;
  76817. var engine = scene.getEngine();
  76818. var material = subMesh.getMaterial();
  76819. if (!material) {
  76820. return;
  76821. }
  76822. // Culling
  76823. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  76824. // Managing instances
  76825. var batch = mesh._getInstancesRenderList(subMesh._id);
  76826. if (batch.mustReturn) {
  76827. return;
  76828. }
  76829. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  76830. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  76831. engine.enableEffect(_this._effect);
  76832. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  76833. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  76834. _this._effect.setMatrix("view", scene.getViewMatrix());
  76835. // Alpha test
  76836. if (material && material.needAlphaTesting()) {
  76837. var alphaTexture = material.getAlphaTestTexture();
  76838. if (alphaTexture) {
  76839. _this._effect.setTexture("diffuseSampler", alphaTexture);
  76840. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  76841. }
  76842. }
  76843. // Bones
  76844. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  76845. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  76846. }
  76847. // Draw
  76848. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  76849. }
  76850. };
  76851. this._multiRenderTarget.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  76852. var index;
  76853. if (depthOnlySubMeshes.length) {
  76854. engine.setColorWrite(false);
  76855. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  76856. renderSubMesh(depthOnlySubMeshes.data[index]);
  76857. }
  76858. engine.setColorWrite(true);
  76859. }
  76860. for (index = 0; index < opaqueSubMeshes.length; index++) {
  76861. renderSubMesh(opaqueSubMeshes.data[index]);
  76862. }
  76863. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  76864. renderSubMesh(alphaTestSubMeshes.data[index]);
  76865. }
  76866. };
  76867. };
  76868. return GeometryBufferRenderer;
  76869. }());
  76870. BABYLON.GeometryBufferRenderer = GeometryBufferRenderer;
  76871. })(BABYLON || (BABYLON = {}));
  76872. //# sourceMappingURL=babylon.geometryBufferRenderer.js.map
  76873. var BABYLON;
  76874. (function (BABYLON) {
  76875. var RefractionPostProcess = /** @class */ (function (_super) {
  76876. __extends(RefractionPostProcess, _super);
  76877. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, options, camera, samplingMode, engine, reusable) {
  76878. var _this = _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], options, camera, samplingMode, engine, reusable) || this;
  76879. _this.color = color;
  76880. _this.depth = depth;
  76881. _this.colorLevel = colorLevel;
  76882. _this._ownRefractionTexture = true;
  76883. _this.onActivateObservable.add(function (cam) {
  76884. _this._refTexture = _this._refTexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  76885. });
  76886. _this.onApplyObservable.add(function (effect) {
  76887. effect.setColor3("baseColor", _this.color);
  76888. effect.setFloat("depth", _this.depth);
  76889. effect.setFloat("colorLevel", _this.colorLevel);
  76890. effect.setTexture("refractionSampler", _this._refTexture);
  76891. });
  76892. return _this;
  76893. }
  76894. Object.defineProperty(RefractionPostProcess.prototype, "refractionTexture", {
  76895. /**
  76896. * Gets or sets the refraction texture
  76897. * Please note that you are responsible for disposing the texture if you set it manually
  76898. */
  76899. get: function () {
  76900. return this._refTexture;
  76901. },
  76902. set: function (value) {
  76903. if (this._refTexture && this._ownRefractionTexture) {
  76904. this._refTexture.dispose();
  76905. }
  76906. this._refTexture = value;
  76907. this._ownRefractionTexture = false;
  76908. },
  76909. enumerable: true,
  76910. configurable: true
  76911. });
  76912. // Methods
  76913. RefractionPostProcess.prototype.dispose = function (camera) {
  76914. if (this._refTexture && this._ownRefractionTexture) {
  76915. this._refTexture.dispose();
  76916. this._refTexture = null;
  76917. }
  76918. _super.prototype.dispose.call(this, camera);
  76919. };
  76920. return RefractionPostProcess;
  76921. }(BABYLON.PostProcess));
  76922. BABYLON.RefractionPostProcess = RefractionPostProcess;
  76923. })(BABYLON || (BABYLON = {}));
  76924. //# sourceMappingURL=babylon.refractionPostProcess.js.map
  76925. var BABYLON;
  76926. (function (BABYLON) {
  76927. var BlackAndWhitePostProcess = /** @class */ (function (_super) {
  76928. __extends(BlackAndWhitePostProcess, _super);
  76929. function BlackAndWhitePostProcess(name, options, camera, samplingMode, engine, reusable) {
  76930. var _this = _super.call(this, name, "blackAndWhite", ["degree"], null, options, camera, samplingMode, engine, reusable) || this;
  76931. _this.degree = 1;
  76932. _this.onApplyObservable.add(function (effect) {
  76933. effect.setFloat("degree", _this.degree);
  76934. });
  76935. return _this;
  76936. }
  76937. return BlackAndWhitePostProcess;
  76938. }(BABYLON.PostProcess));
  76939. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  76940. })(BABYLON || (BABYLON = {}));
  76941. //# sourceMappingURL=babylon.blackAndWhitePostProcess.js.map
  76942. var BABYLON;
  76943. (function (BABYLON) {
  76944. /**
  76945. * The ConvolutionPostProcess applies a 3x3 kernel to every pixel of the
  76946. * input texture to perform effects such as edge detection or sharpening
  76947. * See http://en.wikipedia.org/wiki/Kernel_(image_processing)
  76948. */
  76949. var ConvolutionPostProcess = /** @class */ (function (_super) {
  76950. __extends(ConvolutionPostProcess, _super);
  76951. /**
  76952. * Creates a new instance ConvolutionPostProcess
  76953. * @param name The name of the effect.
  76954. * @param kernel Array of 9 values corrisponding to the 3x3 kernel to be applied
  76955. * @param options The required width/height ratio to downsize to before computing the render pass.
  76956. * @param camera The camera to apply the render pass to.
  76957. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  76958. * @param engine The engine which the post process will be applied. (default: current engine)
  76959. * @param reusable If the post process can be reused on the same frame. (default: false)
  76960. * @param textureType Type of textures used when performing the post process. (default: 0)
  76961. */
  76962. function ConvolutionPostProcess(name, /** Array of 9 values corrisponding to the 3x3 kernel to be applied */ kernel, options, camera, samplingMode, engine, reusable, textureType) {
  76963. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  76964. var _this = _super.call(this, name, "convolution", ["kernel", "screenSize"], null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  76965. _this.kernel = kernel;
  76966. _this.onApply = function (effect) {
  76967. effect.setFloat2("screenSize", _this.width, _this.height);
  76968. effect.setArray("kernel", _this.kernel);
  76969. };
  76970. return _this;
  76971. }
  76972. // Statics
  76973. /**
  76974. * Edge detection 0 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  76975. */
  76976. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  76977. /**
  76978. * Edge detection 1 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  76979. */
  76980. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  76981. /**
  76982. * Edge detection 2 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  76983. */
  76984. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  76985. /**
  76986. * Kernel to sharpen an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  76987. */
  76988. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  76989. /**
  76990. * Kernel to emboss an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  76991. */
  76992. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  76993. /**
  76994. * Kernel to blur an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  76995. */
  76996. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  76997. return ConvolutionPostProcess;
  76998. }(BABYLON.PostProcess));
  76999. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  77000. })(BABYLON || (BABYLON = {}));
  77001. //# sourceMappingURL=babylon.convolutionPostProcess.js.map
  77002. var BABYLON;
  77003. (function (BABYLON) {
  77004. var FilterPostProcess = /** @class */ (function (_super) {
  77005. __extends(FilterPostProcess, _super);
  77006. function FilterPostProcess(name, kernelMatrix, options, camera, samplingMode, engine, reusable) {
  77007. var _this = _super.call(this, name, "filter", ["kernelMatrix"], null, options, camera, samplingMode, engine, reusable) || this;
  77008. _this.kernelMatrix = kernelMatrix;
  77009. _this.onApply = function (effect) {
  77010. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  77011. };
  77012. return _this;
  77013. }
  77014. return FilterPostProcess;
  77015. }(BABYLON.PostProcess));
  77016. BABYLON.FilterPostProcess = FilterPostProcess;
  77017. })(BABYLON || (BABYLON = {}));
  77018. //# sourceMappingURL=babylon.filterPostProcess.js.map
  77019. var BABYLON;
  77020. (function (BABYLON) {
  77021. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  77022. var VolumetricLightScatteringPostProcess = /** @class */ (function (_super) {
  77023. __extends(VolumetricLightScatteringPostProcess, _super);
  77024. /**
  77025. * @constructor
  77026. * @param {string} name - The post-process name
  77027. * @param {any} ratio - The size of the post-process and/or internal pass (0.5 means that your postprocess will have a width = canvas.width 0.5 and a height = canvas.height 0.5)
  77028. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  77029. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  77030. * @param {number} samples - The post-process quality, default 100
  77031. * @param {number} samplingMode - The post-process filtering mode
  77032. * @param {BABYLON.Engine} engine - The babylon engine
  77033. * @param {boolean} reusable - If the post-process is reusable
  77034. * @param {BABYLON.Scene} scene - The constructor needs a scene reference to initialize internal components. If "camera" is null (RenderPipelineà, "scene" must be provided
  77035. */
  77036. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable, scene) {
  77037. if (samples === void 0) { samples = 100; }
  77038. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  77039. 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;
  77040. _this._screenCoordinates = BABYLON.Vector2.Zero();
  77041. /**
  77042. * Custom position of the mesh. Used if "useCustomMeshPosition" is set to "true"
  77043. */
  77044. _this.customMeshPosition = BABYLON.Vector3.Zero();
  77045. /**
  77046. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  77047. */
  77048. _this.useCustomMeshPosition = false;
  77049. /**
  77050. * If the post-process should inverse the light scattering direction
  77051. */
  77052. _this.invert = true;
  77053. /**
  77054. * Array containing the excluded meshes not rendered in the internal pass
  77055. */
  77056. _this.excludedMeshes = new Array();
  77057. /**
  77058. * Controls the overall intensity of the post-process
  77059. */
  77060. _this.exposure = 0.3;
  77061. /**
  77062. * Dissipates each sample's contribution in range [0, 1]
  77063. */
  77064. _this.decay = 0.96815;
  77065. /**
  77066. * Controls the overall intensity of each sample
  77067. */
  77068. _this.weight = 0.58767;
  77069. /**
  77070. * Controls the density of each sample
  77071. */
  77072. _this.density = 0.926;
  77073. scene = ((camera === null) ? scene : camera.getScene()); // parameter "scene" can be null.
  77074. engine = scene.getEngine();
  77075. _this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  77076. // Configure mesh
  77077. _this.mesh = ((mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene));
  77078. // Configure
  77079. _this._createPass(scene, ratio.passRatio || ratio);
  77080. _this.onActivate = function (camera) {
  77081. if (!_this.isSupported) {
  77082. _this.dispose(camera);
  77083. }
  77084. _this.onActivate = null;
  77085. };
  77086. _this.onApplyObservable.add(function (effect) {
  77087. _this._updateMeshScreenCoordinates(scene);
  77088. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  77089. effect.setFloat("exposure", _this.exposure);
  77090. effect.setFloat("decay", _this.decay);
  77091. effect.setFloat("weight", _this.weight);
  77092. effect.setFloat("density", _this.density);
  77093. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  77094. });
  77095. return _this;
  77096. }
  77097. Object.defineProperty(VolumetricLightScatteringPostProcess.prototype, "useDiffuseColor", {
  77098. get: function () {
  77099. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  77100. return false;
  77101. },
  77102. set: function (useDiffuseColor) {
  77103. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  77104. },
  77105. enumerable: true,
  77106. configurable: true
  77107. });
  77108. VolumetricLightScatteringPostProcess.prototype.getClassName = function () {
  77109. return "VolumetricLightScatteringPostProcess";
  77110. };
  77111. VolumetricLightScatteringPostProcess.prototype._isReady = function (subMesh, useInstances) {
  77112. var mesh = subMesh.getMesh();
  77113. // Render this.mesh as default
  77114. if (mesh === this.mesh && mesh.material) {
  77115. return mesh.material.isReady(mesh);
  77116. }
  77117. var defines = [];
  77118. var attribs = [BABYLON.VertexBuffer.PositionKind];
  77119. var material = subMesh.getMaterial();
  77120. // Alpha test
  77121. if (material) {
  77122. if (material.needAlphaTesting()) {
  77123. defines.push("#define ALPHATEST");
  77124. }
  77125. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  77126. attribs.push(BABYLON.VertexBuffer.UVKind);
  77127. defines.push("#define UV1");
  77128. }
  77129. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  77130. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  77131. defines.push("#define UV2");
  77132. }
  77133. }
  77134. // Bones
  77135. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  77136. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  77137. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  77138. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  77139. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  77140. }
  77141. else {
  77142. defines.push("#define NUM_BONE_INFLUENCERS 0");
  77143. }
  77144. // Instances
  77145. if (useInstances) {
  77146. defines.push("#define INSTANCES");
  77147. attribs.push("world0");
  77148. attribs.push("world1");
  77149. attribs.push("world2");
  77150. attribs.push("world3");
  77151. }
  77152. // Get correct effect
  77153. var join = defines.join("\n");
  77154. if (this._cachedDefines !== join) {
  77155. this._cachedDefines = join;
  77156. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  77157. }
  77158. return this._volumetricLightScatteringPass.isReady();
  77159. };
  77160. /**
  77161. * Sets the new light position for light scattering effect
  77162. * @param {BABYLON.Vector3} The new custom light position
  77163. */
  77164. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  77165. this.customMeshPosition = position;
  77166. };
  77167. /**
  77168. * Returns the light position for light scattering effect
  77169. * @return {BABYLON.Vector3} The custom light position
  77170. */
  77171. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  77172. return this.customMeshPosition;
  77173. };
  77174. /**
  77175. * Disposes the internal assets and detaches the post-process from the camera
  77176. */
  77177. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  77178. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  77179. if (rttIndex !== -1) {
  77180. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  77181. }
  77182. this._volumetricLightScatteringRTT.dispose();
  77183. _super.prototype.dispose.call(this, camera);
  77184. };
  77185. /**
  77186. * Returns the render target texture used by the post-process
  77187. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  77188. */
  77189. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  77190. return this._volumetricLightScatteringRTT;
  77191. };
  77192. // Private methods
  77193. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  77194. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  77195. return true;
  77196. }
  77197. return false;
  77198. };
  77199. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  77200. var _this = this;
  77201. var engine = scene.getEngine();
  77202. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  77203. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  77204. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  77205. this._volumetricLightScatteringRTT.renderList = null;
  77206. this._volumetricLightScatteringRTT.renderParticles = false;
  77207. this._volumetricLightScatteringRTT.ignoreCameraViewport = true;
  77208. var camera = this.getCamera();
  77209. if (camera) {
  77210. camera.customRenderTargets.push(this._volumetricLightScatteringRTT);
  77211. }
  77212. else {
  77213. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  77214. }
  77215. // Custom render function for submeshes
  77216. var renderSubMesh = function (subMesh) {
  77217. var mesh = subMesh.getRenderingMesh();
  77218. if (_this._meshExcluded(mesh)) {
  77219. return;
  77220. }
  77221. var material = subMesh.getMaterial();
  77222. if (!material) {
  77223. return;
  77224. }
  77225. var scene = mesh.getScene();
  77226. var engine = scene.getEngine();
  77227. // Culling
  77228. engine.setState(material.backFaceCulling);
  77229. // Managing instances
  77230. var batch = mesh._getInstancesRenderList(subMesh._id);
  77231. if (batch.mustReturn) {
  77232. return;
  77233. }
  77234. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  77235. if (_this._isReady(subMesh, hardwareInstancedRendering)) {
  77236. var effect = _this._volumetricLightScatteringPass;
  77237. if (mesh === _this.mesh) {
  77238. if (subMesh.effect) {
  77239. effect = subMesh.effect;
  77240. }
  77241. else {
  77242. effect = material.getEffect();
  77243. }
  77244. }
  77245. engine.enableEffect(effect);
  77246. mesh._bind(subMesh, effect, BABYLON.Material.TriangleFillMode);
  77247. if (mesh === _this.mesh) {
  77248. material.bind(mesh.getWorldMatrix(), mesh);
  77249. }
  77250. else {
  77251. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  77252. // Alpha test
  77253. if (material && material.needAlphaTesting()) {
  77254. var alphaTexture = material.getAlphaTestTexture();
  77255. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  77256. if (alphaTexture) {
  77257. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  77258. }
  77259. }
  77260. // Bones
  77261. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  77262. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  77263. }
  77264. }
  77265. // Draw
  77266. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return effect.setMatrix("world", world); });
  77267. }
  77268. };
  77269. // Render target texture callbacks
  77270. var savedSceneClearColor;
  77271. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  77272. this._volumetricLightScatteringRTT.onBeforeRenderObservable.add(function () {
  77273. savedSceneClearColor = scene.clearColor;
  77274. scene.clearColor = sceneClearColor;
  77275. });
  77276. this._volumetricLightScatteringRTT.onAfterRenderObservable.add(function () {
  77277. scene.clearColor = savedSceneClearColor;
  77278. });
  77279. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  77280. var engine = scene.getEngine();
  77281. var index;
  77282. if (depthOnlySubMeshes.length) {
  77283. engine.setColorWrite(false);
  77284. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  77285. renderSubMesh(depthOnlySubMeshes.data[index]);
  77286. }
  77287. engine.setColorWrite(true);
  77288. }
  77289. for (index = 0; index < opaqueSubMeshes.length; index++) {
  77290. renderSubMesh(opaqueSubMeshes.data[index]);
  77291. }
  77292. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  77293. renderSubMesh(alphaTestSubMeshes.data[index]);
  77294. }
  77295. if (transparentSubMeshes.length) {
  77296. // Sort sub meshes
  77297. for (index = 0; index < transparentSubMeshes.length; index++) {
  77298. var submesh = transparentSubMeshes.data[index];
  77299. var boundingInfo = submesh.getBoundingInfo();
  77300. if (boundingInfo && scene.activeCamera) {
  77301. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  77302. submesh._distanceToCamera = boundingInfo.boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  77303. }
  77304. }
  77305. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  77306. sortedArray.sort(function (a, b) {
  77307. // Alpha index first
  77308. if (a._alphaIndex > b._alphaIndex) {
  77309. return 1;
  77310. }
  77311. if (a._alphaIndex < b._alphaIndex) {
  77312. return -1;
  77313. }
  77314. // Then distance to camera
  77315. if (a._distanceToCamera < b._distanceToCamera) {
  77316. return 1;
  77317. }
  77318. if (a._distanceToCamera > b._distanceToCamera) {
  77319. return -1;
  77320. }
  77321. return 0;
  77322. });
  77323. // Render sub meshes
  77324. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  77325. for (index = 0; index < sortedArray.length; index++) {
  77326. renderSubMesh(sortedArray[index]);
  77327. }
  77328. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  77329. }
  77330. };
  77331. };
  77332. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  77333. var transform = scene.getTransformMatrix();
  77334. var meshPosition;
  77335. if (this.useCustomMeshPosition) {
  77336. meshPosition = this.customMeshPosition;
  77337. }
  77338. else if (this.attachedNode) {
  77339. meshPosition = this.attachedNode.position;
  77340. }
  77341. else {
  77342. meshPosition = this.mesh.parent ? this.mesh.getAbsolutePosition() : this.mesh.position;
  77343. }
  77344. var pos = BABYLON.Vector3.Project(meshPosition, BABYLON.Matrix.Identity(), transform, this._viewPort);
  77345. this._screenCoordinates.x = pos.x / this._viewPort.width;
  77346. this._screenCoordinates.y = pos.y / this._viewPort.height;
  77347. if (this.invert)
  77348. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  77349. };
  77350. // Static methods
  77351. /**
  77352. * Creates a default mesh for the Volumeric Light Scattering post-process
  77353. * @param {string} The mesh name
  77354. * @param {BABYLON.Scene} The scene where to create the mesh
  77355. * @return {BABYLON.Mesh} the default mesh
  77356. */
  77357. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  77358. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  77359. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  77360. var material = new BABYLON.StandardMaterial(name + "Material", scene);
  77361. material.emissiveColor = new BABYLON.Color3(1, 1, 1);
  77362. mesh.material = material;
  77363. return mesh;
  77364. };
  77365. __decorate([
  77366. BABYLON.serializeAsVector3()
  77367. ], VolumetricLightScatteringPostProcess.prototype, "customMeshPosition", void 0);
  77368. __decorate([
  77369. BABYLON.serialize()
  77370. ], VolumetricLightScatteringPostProcess.prototype, "useCustomMeshPosition", void 0);
  77371. __decorate([
  77372. BABYLON.serialize()
  77373. ], VolumetricLightScatteringPostProcess.prototype, "invert", void 0);
  77374. __decorate([
  77375. BABYLON.serializeAsMeshReference()
  77376. ], VolumetricLightScatteringPostProcess.prototype, "mesh", void 0);
  77377. __decorate([
  77378. BABYLON.serialize()
  77379. ], VolumetricLightScatteringPostProcess.prototype, "excludedMeshes", void 0);
  77380. __decorate([
  77381. BABYLON.serialize()
  77382. ], VolumetricLightScatteringPostProcess.prototype, "exposure", void 0);
  77383. __decorate([
  77384. BABYLON.serialize()
  77385. ], VolumetricLightScatteringPostProcess.prototype, "decay", void 0);
  77386. __decorate([
  77387. BABYLON.serialize()
  77388. ], VolumetricLightScatteringPostProcess.prototype, "weight", void 0);
  77389. __decorate([
  77390. BABYLON.serialize()
  77391. ], VolumetricLightScatteringPostProcess.prototype, "density", void 0);
  77392. return VolumetricLightScatteringPostProcess;
  77393. }(BABYLON.PostProcess));
  77394. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  77395. })(BABYLON || (BABYLON = {}));
  77396. //# sourceMappingURL=babylon.volumetricLightScatteringPostProcess.js.map
  77397. //
  77398. // This post-process allows the modification of rendered colors by using
  77399. // a 'look-up table' (LUT). This effect is also called Color Grading.
  77400. //
  77401. // The object needs to be provided an url to a texture containing the color
  77402. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  77403. // Use an image editing software to tweak the LUT to match your needs.
  77404. //
  77405. // For an example of a color LUT, see here:
  77406. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  77407. // For explanations on color grading, see here:
  77408. // http://udn.epicgames.com/Three/ColorGrading.html
  77409. //
  77410. var BABYLON;
  77411. (function (BABYLON) {
  77412. var ColorCorrectionPostProcess = /** @class */ (function (_super) {
  77413. __extends(ColorCorrectionPostProcess, _super);
  77414. function ColorCorrectionPostProcess(name, colorTableUrl, options, camera, samplingMode, engine, reusable) {
  77415. var _this = _super.call(this, name, 'colorCorrection', null, ['colorTable'], options, camera, samplingMode, engine, reusable) || this;
  77416. _this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  77417. _this._colorTableTexture.anisotropicFilteringLevel = 1;
  77418. _this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  77419. _this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  77420. _this.onApply = function (effect) {
  77421. effect.setTexture("colorTable", _this._colorTableTexture);
  77422. };
  77423. return _this;
  77424. }
  77425. return ColorCorrectionPostProcess;
  77426. }(BABYLON.PostProcess));
  77427. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  77428. })(BABYLON || (BABYLON = {}));
  77429. //# sourceMappingURL=babylon.colorCorrectionPostProcess.js.map
  77430. var BABYLON;
  77431. (function (BABYLON) {
  77432. /** Defines operator used for tonemapping */
  77433. var TonemappingOperator;
  77434. (function (TonemappingOperator) {
  77435. /** Hable */
  77436. TonemappingOperator[TonemappingOperator["Hable"] = 0] = "Hable";
  77437. /** Reinhard */
  77438. TonemappingOperator[TonemappingOperator["Reinhard"] = 1] = "Reinhard";
  77439. /** HejiDawson */
  77440. TonemappingOperator[TonemappingOperator["HejiDawson"] = 2] = "HejiDawson";
  77441. /** Photographic */
  77442. TonemappingOperator[TonemappingOperator["Photographic"] = 3] = "Photographic";
  77443. })(TonemappingOperator = BABYLON.TonemappingOperator || (BABYLON.TonemappingOperator = {}));
  77444. ;
  77445. /**
  77446. * Defines a post process to apply tone mapping
  77447. */
  77448. var TonemapPostProcess = /** @class */ (function (_super) {
  77449. __extends(TonemapPostProcess, _super);
  77450. /**
  77451. * Creates a new TonemapPostProcess
  77452. * @param name defines the name of the postprocess
  77453. * @param _operator defines the operator to use
  77454. * @param exposureAdjustment defines the required exposure adjustement
  77455. * @param camera defines the camera to use (can be null)
  77456. * @param samplingMode defines the required sampling mode (BABYLON.Texture.BILINEAR_SAMPLINGMODE by default)
  77457. * @param engine defines the hosting engine (can be ignore if camera is set)
  77458. * @param textureFormat defines the texture format to use (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  77459. */
  77460. function TonemapPostProcess(name, _operator,
  77461. /** Defines the required exposure adjustement */
  77462. exposureAdjustment, camera, samplingMode, engine, textureFormat) {
  77463. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  77464. if (textureFormat === void 0) { textureFormat = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  77465. var _this = _super.call(this, name, "tonemap", ["_ExposureAdjustment"], null, 1.0, camera, samplingMode, engine, true, null, textureFormat) || this;
  77466. _this._operator = _operator;
  77467. _this.exposureAdjustment = exposureAdjustment;
  77468. var defines = "#define ";
  77469. if (_this._operator === TonemappingOperator.Hable)
  77470. defines += "HABLE_TONEMAPPING";
  77471. else if (_this._operator === TonemappingOperator.Reinhard)
  77472. defines += "REINHARD_TONEMAPPING";
  77473. else if (_this._operator === TonemappingOperator.HejiDawson)
  77474. defines += "OPTIMIZED_HEJIDAWSON_TONEMAPPING";
  77475. else if (_this._operator === TonemappingOperator.Photographic)
  77476. defines += "PHOTOGRAPHIC_TONEMAPPING";
  77477. //sadly a second call to create the effect.
  77478. _this.updateEffect(defines);
  77479. _this.onApply = function (effect) {
  77480. effect.setFloat("_ExposureAdjustment", _this.exposureAdjustment);
  77481. };
  77482. return _this;
  77483. }
  77484. return TonemapPostProcess;
  77485. }(BABYLON.PostProcess));
  77486. BABYLON.TonemapPostProcess = TonemapPostProcess;
  77487. })(BABYLON || (BABYLON = {}));
  77488. //# sourceMappingURL=babylon.tonemapPostProcess.js.map
  77489. var BABYLON;
  77490. (function (BABYLON) {
  77491. var DisplayPassPostProcess = /** @class */ (function (_super) {
  77492. __extends(DisplayPassPostProcess, _super);
  77493. function DisplayPassPostProcess(name, options, camera, samplingMode, engine, reusable) {
  77494. return _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], options, camera, samplingMode, engine, reusable) || this;
  77495. }
  77496. return DisplayPassPostProcess;
  77497. }(BABYLON.PostProcess));
  77498. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  77499. })(BABYLON || (BABYLON = {}));
  77500. //# sourceMappingURL=babylon.displayPassPostProcess.js.map
  77501. var BABYLON;
  77502. (function (BABYLON) {
  77503. var HighlightsPostProcess = /** @class */ (function (_super) {
  77504. __extends(HighlightsPostProcess, _super);
  77505. function HighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  77506. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  77507. return _super.call(this, name, "highlights", null, null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  77508. }
  77509. return HighlightsPostProcess;
  77510. }(BABYLON.PostProcess));
  77511. BABYLON.HighlightsPostProcess = HighlightsPostProcess;
  77512. })(BABYLON || (BABYLON = {}));
  77513. //# sourceMappingURL=babylon.highlightsPostProcess.js.map
  77514. var BABYLON;
  77515. (function (BABYLON) {
  77516. var ImageProcessingPostProcess = /** @class */ (function (_super) {
  77517. __extends(ImageProcessingPostProcess, _super);
  77518. function ImageProcessingPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, imageProcessingConfiguration) {
  77519. if (camera === void 0) { camera = null; }
  77520. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  77521. var _this = _super.call(this, name, "imageProcessing", [], [], options, camera, samplingMode, engine, reusable, null, textureType, "postprocess", null, true) || this;
  77522. _this._fromLinearSpace = true;
  77523. /**
  77524. * Defines cache preventing GC.
  77525. */
  77526. _this._defines = {
  77527. IMAGEPROCESSING: false,
  77528. VIGNETTE: false,
  77529. VIGNETTEBLENDMODEMULTIPLY: false,
  77530. VIGNETTEBLENDMODEOPAQUE: false,
  77531. TONEMAPPING: false,
  77532. CONTRAST: false,
  77533. COLORCURVES: false,
  77534. COLORGRADING: false,
  77535. COLORGRADING3D: false,
  77536. FROMLINEARSPACE: false,
  77537. SAMPLER3DGREENDEPTH: false,
  77538. SAMPLER3DBGRMAP: false,
  77539. IMAGEPROCESSINGPOSTPROCESS: false,
  77540. EXPOSURE: false,
  77541. };
  77542. // Setup the configuration as forced by the constructor. This would then not force the
  77543. // scene materials output in linear space and let untouched the default forward pass.
  77544. if (imageProcessingConfiguration) {
  77545. imageProcessingConfiguration.applyByPostProcess = true;
  77546. _this._attachImageProcessingConfiguration(imageProcessingConfiguration, true);
  77547. // This will cause the shader to be compiled
  77548. _this.fromLinearSpace = false;
  77549. }
  77550. // Setup the default processing configuration to the scene.
  77551. else {
  77552. _this._attachImageProcessingConfiguration(null, true);
  77553. _this.imageProcessingConfiguration.applyByPostProcess = true;
  77554. }
  77555. _this.onApply = function (effect) {
  77556. _this.imageProcessingConfiguration.bind(effect, _this.aspectRatio);
  77557. };
  77558. return _this;
  77559. }
  77560. Object.defineProperty(ImageProcessingPostProcess.prototype, "imageProcessingConfiguration", {
  77561. /**
  77562. * Gets the image processing configuration used either in this material.
  77563. */
  77564. get: function () {
  77565. return this._imageProcessingConfiguration;
  77566. },
  77567. /**
  77568. * Sets the Default image processing configuration used either in the this material.
  77569. *
  77570. * If sets to null, the scene one is in use.
  77571. */
  77572. set: function (value) {
  77573. this._attachImageProcessingConfiguration(value);
  77574. },
  77575. enumerable: true,
  77576. configurable: true
  77577. });
  77578. /**
  77579. * Attaches a new image processing configuration to the PBR Material.
  77580. * @param configuration
  77581. */
  77582. ImageProcessingPostProcess.prototype._attachImageProcessingConfiguration = function (configuration, doNotBuild) {
  77583. var _this = this;
  77584. if (doNotBuild === void 0) { doNotBuild = false; }
  77585. if (configuration === this._imageProcessingConfiguration) {
  77586. return;
  77587. }
  77588. // Detaches observer.
  77589. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  77590. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  77591. }
  77592. // Pick the scene configuration if needed.
  77593. if (!configuration) {
  77594. var scene = null;
  77595. var engine = this.getEngine();
  77596. var camera = this.getCamera();
  77597. if (camera) {
  77598. scene = camera.getScene();
  77599. }
  77600. else if (engine && engine.scenes) {
  77601. var scenes = engine.scenes;
  77602. scene = scenes[scenes.length - 1];
  77603. }
  77604. else {
  77605. scene = BABYLON.Engine.LastCreatedScene;
  77606. }
  77607. this._imageProcessingConfiguration = scene.imageProcessingConfiguration;
  77608. }
  77609. else {
  77610. this._imageProcessingConfiguration = configuration;
  77611. }
  77612. // Attaches observer.
  77613. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  77614. _this._updateParameters();
  77615. });
  77616. // Ensure the effect will be rebuilt.
  77617. if (!doNotBuild) {
  77618. this._updateParameters();
  77619. }
  77620. };
  77621. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurves", {
  77622. /**
  77623. * Gets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  77624. */
  77625. get: function () {
  77626. return this.imageProcessingConfiguration.colorCurves;
  77627. },
  77628. /**
  77629. * Sets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  77630. */
  77631. set: function (value) {
  77632. this.imageProcessingConfiguration.colorCurves = value;
  77633. },
  77634. enumerable: true,
  77635. configurable: true
  77636. });
  77637. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurvesEnabled", {
  77638. /**
  77639. * Gets wether the color curves effect is enabled.
  77640. */
  77641. get: function () {
  77642. return this.imageProcessingConfiguration.colorCurvesEnabled;
  77643. },
  77644. /**
  77645. * Sets wether the color curves effect is enabled.
  77646. */
  77647. set: function (value) {
  77648. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  77649. },
  77650. enumerable: true,
  77651. configurable: true
  77652. });
  77653. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingTexture", {
  77654. /**
  77655. * Gets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  77656. */
  77657. get: function () {
  77658. return this.imageProcessingConfiguration.colorGradingTexture;
  77659. },
  77660. /**
  77661. * Sets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  77662. */
  77663. set: function (value) {
  77664. this.imageProcessingConfiguration.colorGradingTexture = value;
  77665. },
  77666. enumerable: true,
  77667. configurable: true
  77668. });
  77669. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingEnabled", {
  77670. /**
  77671. * Gets wether the color grading effect is enabled.
  77672. */
  77673. get: function () {
  77674. return this.imageProcessingConfiguration.colorGradingEnabled;
  77675. },
  77676. /**
  77677. * Gets wether the color grading effect is enabled.
  77678. */
  77679. set: function (value) {
  77680. this.imageProcessingConfiguration.colorGradingEnabled = value;
  77681. },
  77682. enumerable: true,
  77683. configurable: true
  77684. });
  77685. Object.defineProperty(ImageProcessingPostProcess.prototype, "exposure", {
  77686. /**
  77687. * Gets exposure used in the effect.
  77688. */
  77689. get: function () {
  77690. return this.imageProcessingConfiguration.exposure;
  77691. },
  77692. /**
  77693. * Sets exposure used in the effect.
  77694. */
  77695. set: function (value) {
  77696. this.imageProcessingConfiguration.exposure = value;
  77697. },
  77698. enumerable: true,
  77699. configurable: true
  77700. });
  77701. Object.defineProperty(ImageProcessingPostProcess.prototype, "toneMappingEnabled", {
  77702. /**
  77703. * Gets wether tonemapping is enabled or not.
  77704. */
  77705. get: function () {
  77706. return this._imageProcessingConfiguration.toneMappingEnabled;
  77707. },
  77708. /**
  77709. * Sets wether tonemapping is enabled or not
  77710. */
  77711. set: function (value) {
  77712. this._imageProcessingConfiguration.toneMappingEnabled = value;
  77713. },
  77714. enumerable: true,
  77715. configurable: true
  77716. });
  77717. ;
  77718. ;
  77719. Object.defineProperty(ImageProcessingPostProcess.prototype, "contrast", {
  77720. /**
  77721. * Gets contrast used in the effect.
  77722. */
  77723. get: function () {
  77724. return this.imageProcessingConfiguration.contrast;
  77725. },
  77726. /**
  77727. * Sets contrast used in the effect.
  77728. */
  77729. set: function (value) {
  77730. this.imageProcessingConfiguration.contrast = value;
  77731. },
  77732. enumerable: true,
  77733. configurable: true
  77734. });
  77735. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteStretch", {
  77736. /**
  77737. * Gets Vignette stretch size.
  77738. */
  77739. get: function () {
  77740. return this.imageProcessingConfiguration.vignetteStretch;
  77741. },
  77742. /**
  77743. * Sets Vignette stretch size.
  77744. */
  77745. set: function (value) {
  77746. this.imageProcessingConfiguration.vignetteStretch = value;
  77747. },
  77748. enumerable: true,
  77749. configurable: true
  77750. });
  77751. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreX", {
  77752. /**
  77753. * Gets Vignette centre X Offset.
  77754. */
  77755. get: function () {
  77756. return this.imageProcessingConfiguration.vignetteCentreX;
  77757. },
  77758. /**
  77759. * Sets Vignette centre X Offset.
  77760. */
  77761. set: function (value) {
  77762. this.imageProcessingConfiguration.vignetteCentreX = value;
  77763. },
  77764. enumerable: true,
  77765. configurable: true
  77766. });
  77767. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreY", {
  77768. /**
  77769. * Gets Vignette centre Y Offset.
  77770. */
  77771. get: function () {
  77772. return this.imageProcessingConfiguration.vignetteCentreY;
  77773. },
  77774. /**
  77775. * Sets Vignette centre Y Offset.
  77776. */
  77777. set: function (value) {
  77778. this.imageProcessingConfiguration.vignetteCentreY = value;
  77779. },
  77780. enumerable: true,
  77781. configurable: true
  77782. });
  77783. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteWeight", {
  77784. /**
  77785. * Gets Vignette weight or intensity of the vignette effect.
  77786. */
  77787. get: function () {
  77788. return this.imageProcessingConfiguration.vignetteWeight;
  77789. },
  77790. /**
  77791. * Sets Vignette weight or intensity of the vignette effect.
  77792. */
  77793. set: function (value) {
  77794. this.imageProcessingConfiguration.vignetteWeight = value;
  77795. },
  77796. enumerable: true,
  77797. configurable: true
  77798. });
  77799. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteColor", {
  77800. /**
  77801. * Gets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  77802. * if vignetteEnabled is set to true.
  77803. */
  77804. get: function () {
  77805. return this.imageProcessingConfiguration.vignetteColor;
  77806. },
  77807. /**
  77808. * Sets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  77809. * if vignetteEnabled is set to true.
  77810. */
  77811. set: function (value) {
  77812. this.imageProcessingConfiguration.vignetteColor = value;
  77813. },
  77814. enumerable: true,
  77815. configurable: true
  77816. });
  77817. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCameraFov", {
  77818. /**
  77819. * Gets Camera field of view used by the Vignette effect.
  77820. */
  77821. get: function () {
  77822. return this.imageProcessingConfiguration.vignetteCameraFov;
  77823. },
  77824. /**
  77825. * Sets Camera field of view used by the Vignette effect.
  77826. */
  77827. set: function (value) {
  77828. this.imageProcessingConfiguration.vignetteCameraFov = value;
  77829. },
  77830. enumerable: true,
  77831. configurable: true
  77832. });
  77833. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteBlendMode", {
  77834. /**
  77835. * Gets the vignette blend mode allowing different kind of effect.
  77836. */
  77837. get: function () {
  77838. return this.imageProcessingConfiguration.vignetteBlendMode;
  77839. },
  77840. /**
  77841. * Sets the vignette blend mode allowing different kind of effect.
  77842. */
  77843. set: function (value) {
  77844. this.imageProcessingConfiguration.vignetteBlendMode = value;
  77845. },
  77846. enumerable: true,
  77847. configurable: true
  77848. });
  77849. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteEnabled", {
  77850. /**
  77851. * Gets wether the vignette effect is enabled.
  77852. */
  77853. get: function () {
  77854. return this.imageProcessingConfiguration.vignetteEnabled;
  77855. },
  77856. /**
  77857. * Sets wether the vignette effect is enabled.
  77858. */
  77859. set: function (value) {
  77860. this.imageProcessingConfiguration.vignetteEnabled = value;
  77861. },
  77862. enumerable: true,
  77863. configurable: true
  77864. });
  77865. Object.defineProperty(ImageProcessingPostProcess.prototype, "fromLinearSpace", {
  77866. /**
  77867. * Gets wether the input of the processing is in Gamma or Linear Space.
  77868. */
  77869. get: function () {
  77870. return this._fromLinearSpace;
  77871. },
  77872. /**
  77873. * Sets wether the input of the processing is in Gamma or Linear Space.
  77874. */
  77875. set: function (value) {
  77876. if (this._fromLinearSpace === value) {
  77877. return;
  77878. }
  77879. this._fromLinearSpace = value;
  77880. this._updateParameters();
  77881. },
  77882. enumerable: true,
  77883. configurable: true
  77884. });
  77885. ImageProcessingPostProcess.prototype.getClassName = function () {
  77886. return "ImageProcessingPostProcess";
  77887. };
  77888. ImageProcessingPostProcess.prototype._updateParameters = function () {
  77889. this._defines.FROMLINEARSPACE = this._fromLinearSpace;
  77890. this.imageProcessingConfiguration.prepareDefines(this._defines, true);
  77891. var defines = "";
  77892. for (var define in this._defines) {
  77893. if (this._defines[define]) {
  77894. defines += "#define " + define + ";\r\n";
  77895. }
  77896. }
  77897. var samplers = ["textureSampler"];
  77898. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, this._defines);
  77899. var uniforms = ["scale"];
  77900. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, this._defines);
  77901. this.updateEffect(defines, uniforms, samplers);
  77902. };
  77903. ImageProcessingPostProcess.prototype.dispose = function (camera) {
  77904. _super.prototype.dispose.call(this, camera);
  77905. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  77906. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  77907. }
  77908. this.imageProcessingConfiguration.applyByPostProcess = false;
  77909. };
  77910. __decorate([
  77911. BABYLON.serialize()
  77912. ], ImageProcessingPostProcess.prototype, "_fromLinearSpace", void 0);
  77913. return ImageProcessingPostProcess;
  77914. }(BABYLON.PostProcess));
  77915. BABYLON.ImageProcessingPostProcess = ImageProcessingPostProcess;
  77916. })(BABYLON || (BABYLON = {}));
  77917. //# sourceMappingURL=babylon.imageProcessingPostProcess.js.map
  77918. var BABYLON;
  77919. (function (BABYLON) {
  77920. /**
  77921. * Class used to store bone information
  77922. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  77923. */
  77924. var Bone = /** @class */ (function (_super) {
  77925. __extends(Bone, _super);
  77926. /**
  77927. * Create a new bone
  77928. * @param name defines the bone name
  77929. * @param skeleton defines the parent skeleton
  77930. * @param parentBone defines the parent (can be null if the bone is the root)
  77931. * @param localMatrix defines the local matrix
  77932. * @param restPose defines the rest pose matrix
  77933. * @param baseMatrix defines the base matrix
  77934. * @param index defines index of the bone in the hiearchy
  77935. */
  77936. function Bone(
  77937. /**
  77938. * defines the bone name
  77939. */
  77940. name, skeleton, parentBone, localMatrix, restPose, baseMatrix, index) {
  77941. if (parentBone === void 0) { parentBone = null; }
  77942. if (localMatrix === void 0) { localMatrix = null; }
  77943. if (restPose === void 0) { restPose = null; }
  77944. if (baseMatrix === void 0) { baseMatrix = null; }
  77945. if (index === void 0) { index = null; }
  77946. var _this = _super.call(this, name, skeleton.getScene()) || this;
  77947. _this.name = name;
  77948. /**
  77949. * Gets the list of child bones
  77950. */
  77951. _this.children = new Array();
  77952. /** Gets the animations associated with this bone */
  77953. _this.animations = new Array();
  77954. /**
  77955. * @hidden Internal only
  77956. * Set this value to map this bone to a different index in the transform matrices
  77957. * Set this value to -1 to exclude the bone from the transform matrices
  77958. */
  77959. _this._index = null;
  77960. _this._absoluteTransform = new BABYLON.Matrix();
  77961. _this._invertedAbsoluteTransform = new BABYLON.Matrix();
  77962. _this._scalingDeterminant = 1;
  77963. _this._worldTransform = new BABYLON.Matrix();
  77964. _this._needToDecompose = true;
  77965. _this._needToCompose = false;
  77966. _this._skeleton = skeleton;
  77967. _this._localMatrix = localMatrix ? localMatrix.clone() : BABYLON.Matrix.Identity();
  77968. _this._restPose = restPose ? restPose : _this._localMatrix.clone();
  77969. _this._baseMatrix = baseMatrix ? baseMatrix : _this._localMatrix.clone();
  77970. _this._index = index;
  77971. skeleton.bones.push(_this);
  77972. _this.setParent(parentBone, false);
  77973. if (baseMatrix || localMatrix) {
  77974. _this._updateDifferenceMatrix();
  77975. }
  77976. return _this;
  77977. }
  77978. Object.defineProperty(Bone.prototype, "_matrix", {
  77979. /** @hidden */
  77980. get: function () {
  77981. this._compose();
  77982. return this._localMatrix;
  77983. },
  77984. /** @hidden */
  77985. set: function (value) {
  77986. this._localMatrix.copyFrom(value);
  77987. this._needToDecompose = true;
  77988. },
  77989. enumerable: true,
  77990. configurable: true
  77991. });
  77992. // Members
  77993. /**
  77994. * Gets the parent skeleton
  77995. * @returns a skeleton
  77996. */
  77997. Bone.prototype.getSkeleton = function () {
  77998. return this._skeleton;
  77999. };
  78000. /**
  78001. * Gets parent bone
  78002. * @returns a bone or null if the bone is the root of the bone hierarchy
  78003. */
  78004. Bone.prototype.getParent = function () {
  78005. return this._parent;
  78006. };
  78007. /**
  78008. * Sets the parent bone
  78009. * @param parent defines the parent (can be null if the bone is the root)
  78010. * @param updateDifferenceMatrix defines if the difference matrix must be updated
  78011. */
  78012. Bone.prototype.setParent = function (parent, updateDifferenceMatrix) {
  78013. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  78014. if (this._parent === parent) {
  78015. return;
  78016. }
  78017. if (this._parent) {
  78018. var index = this._parent.children.indexOf(this);
  78019. if (index !== -1) {
  78020. this._parent.children.splice(index, 1);
  78021. }
  78022. }
  78023. this._parent = parent;
  78024. if (this._parent) {
  78025. this._parent.children.push(this);
  78026. }
  78027. if (updateDifferenceMatrix) {
  78028. this._updateDifferenceMatrix();
  78029. }
  78030. this.markAsDirty();
  78031. };
  78032. /**
  78033. * Gets the local matrix
  78034. * @returns a matrix
  78035. */
  78036. Bone.prototype.getLocalMatrix = function () {
  78037. this._compose();
  78038. return this._localMatrix;
  78039. };
  78040. /**
  78041. * Gets the base matrix (initial matrix which remains unchanged)
  78042. * @returns a matrix
  78043. */
  78044. Bone.prototype.getBaseMatrix = function () {
  78045. return this._baseMatrix;
  78046. };
  78047. /**
  78048. * Gets the rest pose matrix
  78049. * @returns a matrix
  78050. */
  78051. Bone.prototype.getRestPose = function () {
  78052. return this._restPose;
  78053. };
  78054. /**
  78055. * Gets a matrix used to store world matrix (ie. the matrix sent to shaders)
  78056. */
  78057. Bone.prototype.getWorldMatrix = function () {
  78058. return this._worldTransform;
  78059. };
  78060. /**
  78061. * Sets the local matrix to rest pose matrix
  78062. */
  78063. Bone.prototype.returnToRest = function () {
  78064. this.updateMatrix(this._restPose.clone());
  78065. };
  78066. /**
  78067. * Gets the inverse of the absolute transform matrix.
  78068. * This matrix will be multiplied by local matrix to get the difference matrix (ie. the difference between original state and current state)
  78069. * @returns a matrix
  78070. */
  78071. Bone.prototype.getInvertedAbsoluteTransform = function () {
  78072. return this._invertedAbsoluteTransform;
  78073. };
  78074. /**
  78075. * Gets the absolute transform matrix (ie base matrix * parent world matrix)
  78076. * @returns a matrix
  78077. */
  78078. Bone.prototype.getAbsoluteTransform = function () {
  78079. return this._absoluteTransform;
  78080. };
  78081. Object.defineProperty(Bone.prototype, "position", {
  78082. // Properties (matches AbstractMesh properties)
  78083. /** Gets or sets current position (in local space) */
  78084. get: function () {
  78085. this._decompose();
  78086. return this._localPosition;
  78087. },
  78088. set: function (newPosition) {
  78089. this._decompose();
  78090. this._localPosition.copyFrom(newPosition);
  78091. this._markAsDirtyAndCompose();
  78092. },
  78093. enumerable: true,
  78094. configurable: true
  78095. });
  78096. Object.defineProperty(Bone.prototype, "rotation", {
  78097. /** Gets or sets current rotation (in local space) */
  78098. get: function () {
  78099. return this.getRotation();
  78100. },
  78101. set: function (newRotation) {
  78102. this.setRotation(newRotation);
  78103. },
  78104. enumerable: true,
  78105. configurable: true
  78106. });
  78107. Object.defineProperty(Bone.prototype, "rotationQuaternion", {
  78108. /** Gets or sets current rotation quaternion (in local space) */
  78109. get: function () {
  78110. this._decompose();
  78111. return this._localRotation;
  78112. },
  78113. set: function (newRotation) {
  78114. this.setRotationQuaternion(newRotation);
  78115. },
  78116. enumerable: true,
  78117. configurable: true
  78118. });
  78119. Object.defineProperty(Bone.prototype, "scaling", {
  78120. /** Gets or sets current scaling (in local space) */
  78121. get: function () {
  78122. return this.getScale();
  78123. },
  78124. set: function (newScaling) {
  78125. this.setScale(newScaling);
  78126. },
  78127. enumerable: true,
  78128. configurable: true
  78129. });
  78130. Object.defineProperty(Bone.prototype, "animationPropertiesOverride", {
  78131. /**
  78132. * Gets the animation properties override
  78133. */
  78134. get: function () {
  78135. return this._skeleton.animationPropertiesOverride;
  78136. },
  78137. enumerable: true,
  78138. configurable: true
  78139. });
  78140. // Methods
  78141. Bone.prototype._decompose = function () {
  78142. if (!this._needToDecompose) {
  78143. return;
  78144. }
  78145. this._needToDecompose = false;
  78146. if (!this._localScaling) {
  78147. this._localScaling = BABYLON.Vector3.Zero();
  78148. this._localRotation = BABYLON.Quaternion.Zero();
  78149. this._localPosition = BABYLON.Vector3.Zero();
  78150. }
  78151. this._localMatrix.decompose(this._localScaling, this._localRotation, this._localPosition);
  78152. };
  78153. Bone.prototype._compose = function () {
  78154. if (!this._needToCompose) {
  78155. return;
  78156. }
  78157. this._needToCompose = false;
  78158. BABYLON.Matrix.ComposeToRef(this._localScaling, this._localRotation, this._localPosition, this._localMatrix);
  78159. };
  78160. /**
  78161. * Update the base and local matrices
  78162. * @param matrix defines the new base or local matrix
  78163. * @param updateDifferenceMatrix defines if the difference matrix must be updated
  78164. * @param updateLocalMatrix defines if the local matrix should be updated
  78165. */
  78166. Bone.prototype.updateMatrix = function (matrix, updateDifferenceMatrix, updateLocalMatrix) {
  78167. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  78168. if (updateLocalMatrix === void 0) { updateLocalMatrix = true; }
  78169. this._baseMatrix.copyFrom(matrix);
  78170. if (updateDifferenceMatrix) {
  78171. this._updateDifferenceMatrix();
  78172. }
  78173. if (updateLocalMatrix) {
  78174. this._localMatrix.copyFrom(matrix);
  78175. this._markAsDirtyAndDecompose();
  78176. }
  78177. else {
  78178. this.markAsDirty();
  78179. }
  78180. };
  78181. /** @hidden */
  78182. Bone.prototype._updateDifferenceMatrix = function (rootMatrix, updateChildren) {
  78183. if (updateChildren === void 0) { updateChildren = true; }
  78184. if (!rootMatrix) {
  78185. rootMatrix = this._baseMatrix;
  78186. }
  78187. if (this._parent) {
  78188. rootMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  78189. }
  78190. else {
  78191. this._absoluteTransform.copyFrom(rootMatrix);
  78192. }
  78193. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  78194. if (updateChildren) {
  78195. for (var index = 0; index < this.children.length; index++) {
  78196. this.children[index]._updateDifferenceMatrix();
  78197. }
  78198. }
  78199. this._scalingDeterminant = (this._absoluteTransform.determinant() < 0 ? -1 : 1);
  78200. };
  78201. /**
  78202. * Flag the bone as dirty (Forcing it to update everything)
  78203. */
  78204. Bone.prototype.markAsDirty = function () {
  78205. this._currentRenderId++;
  78206. this._childRenderId++;
  78207. this._skeleton._markAsDirty();
  78208. };
  78209. Bone.prototype._markAsDirtyAndCompose = function () {
  78210. this.markAsDirty();
  78211. this._needToCompose = true;
  78212. };
  78213. Bone.prototype._markAsDirtyAndDecompose = function () {
  78214. this.markAsDirty();
  78215. this._needToDecompose = true;
  78216. };
  78217. /**
  78218. * Copy an animation range from another bone
  78219. * @param source defines the source bone
  78220. * @param rangeName defines the range name to copy
  78221. * @param frameOffset defines the frame offset
  78222. * @param rescaleAsRequired defines if rescaling must be applied if required
  78223. * @param skelDimensionsRatio defines the scaling ratio
  78224. * @returns true if operation was successful
  78225. */
  78226. Bone.prototype.copyAnimationRange = function (source, rangeName, frameOffset, rescaleAsRequired, skelDimensionsRatio) {
  78227. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  78228. if (skelDimensionsRatio === void 0) { skelDimensionsRatio = null; }
  78229. // all animation may be coming from a library skeleton, so may need to create animation
  78230. if (this.animations.length === 0) {
  78231. this.animations.push(new BABYLON.Animation(this.name, "_matrix", source.animations[0].framePerSecond, BABYLON.Animation.ANIMATIONTYPE_MATRIX, 0));
  78232. this.animations[0].setKeys([]);
  78233. }
  78234. // get animation info / verify there is such a range from the source bone
  78235. var sourceRange = source.animations[0].getRange(rangeName);
  78236. if (!sourceRange) {
  78237. return false;
  78238. }
  78239. var from = sourceRange.from;
  78240. var to = sourceRange.to;
  78241. var sourceKeys = source.animations[0].getKeys();
  78242. // rescaling prep
  78243. var sourceBoneLength = source.length;
  78244. var sourceParent = source.getParent();
  78245. var parent = this.getParent();
  78246. var parentScalingReqd = rescaleAsRequired && sourceParent && sourceBoneLength && this.length && sourceBoneLength !== this.length;
  78247. var parentRatio = parentScalingReqd && parent && sourceParent ? parent.length / sourceParent.length : 1;
  78248. var dimensionsScalingReqd = rescaleAsRequired && !parent && skelDimensionsRatio && (skelDimensionsRatio.x !== 1 || skelDimensionsRatio.y !== 1 || skelDimensionsRatio.z !== 1);
  78249. var destKeys = this.animations[0].getKeys();
  78250. // loop vars declaration
  78251. var orig;
  78252. var origTranslation;
  78253. var mat;
  78254. for (var key = 0, nKeys = sourceKeys.length; key < nKeys; key++) {
  78255. orig = sourceKeys[key];
  78256. if (orig.frame >= from && orig.frame <= to) {
  78257. if (rescaleAsRequired) {
  78258. mat = orig.value.clone();
  78259. // scale based on parent ratio, when bone has parent
  78260. if (parentScalingReqd) {
  78261. origTranslation = mat.getTranslation();
  78262. mat.setTranslation(origTranslation.scaleInPlace(parentRatio));
  78263. // scale based on skeleton dimension ratio when root bone, and value is passed
  78264. }
  78265. else if (dimensionsScalingReqd && skelDimensionsRatio) {
  78266. origTranslation = mat.getTranslation();
  78267. mat.setTranslation(origTranslation.multiplyInPlace(skelDimensionsRatio));
  78268. // use original when root bone, and no data for skelDimensionsRatio
  78269. }
  78270. else {
  78271. mat = orig.value;
  78272. }
  78273. }
  78274. else {
  78275. mat = orig.value;
  78276. }
  78277. destKeys.push({ frame: orig.frame + frameOffset, value: mat });
  78278. }
  78279. }
  78280. this.animations[0].createRange(rangeName, from + frameOffset, to + frameOffset);
  78281. return true;
  78282. };
  78283. /**
  78284. * Translate the bone in local or world space
  78285. * @param vec The amount to translate the bone
  78286. * @param space The space that the translation is in
  78287. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78288. */
  78289. Bone.prototype.translate = function (vec, space, mesh) {
  78290. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78291. var lm = this.getLocalMatrix();
  78292. if (space == BABYLON.Space.LOCAL) {
  78293. lm.m[12] += vec.x;
  78294. lm.m[13] += vec.y;
  78295. lm.m[14] += vec.z;
  78296. }
  78297. else {
  78298. var wm = null;
  78299. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  78300. if (mesh) {
  78301. wm = mesh.getWorldMatrix();
  78302. }
  78303. this._skeleton.computeAbsoluteTransforms();
  78304. var tmat = Bone._tmpMats[0];
  78305. var tvec = Bone._tmpVecs[0];
  78306. if (this._parent) {
  78307. if (mesh && wm) {
  78308. tmat.copyFrom(this._parent.getAbsoluteTransform());
  78309. tmat.multiplyToRef(wm, tmat);
  78310. }
  78311. else {
  78312. tmat.copyFrom(this._parent.getAbsoluteTransform());
  78313. }
  78314. }
  78315. tmat.m[12] = 0;
  78316. tmat.m[13] = 0;
  78317. tmat.m[14] = 0;
  78318. tmat.invert();
  78319. BABYLON.Vector3.TransformCoordinatesToRef(vec, tmat, tvec);
  78320. lm.m[12] += tvec.x;
  78321. lm.m[13] += tvec.y;
  78322. lm.m[14] += tvec.z;
  78323. }
  78324. this._markAsDirtyAndDecompose();
  78325. };
  78326. /**
  78327. * Set the postion of the bone in local or world space
  78328. * @param position The position to set the bone
  78329. * @param space The space that the position is in
  78330. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78331. */
  78332. Bone.prototype.setPosition = function (position, space, mesh) {
  78333. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78334. var lm = this.getLocalMatrix();
  78335. if (space == BABYLON.Space.LOCAL) {
  78336. lm.m[12] = position.x;
  78337. lm.m[13] = position.y;
  78338. lm.m[14] = position.z;
  78339. }
  78340. else {
  78341. var wm = null;
  78342. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  78343. if (mesh) {
  78344. wm = mesh.getWorldMatrix();
  78345. }
  78346. this._skeleton.computeAbsoluteTransforms();
  78347. var tmat = Bone._tmpMats[0];
  78348. var vec = Bone._tmpVecs[0];
  78349. if (this._parent) {
  78350. if (mesh && wm) {
  78351. tmat.copyFrom(this._parent.getAbsoluteTransform());
  78352. tmat.multiplyToRef(wm, tmat);
  78353. }
  78354. else {
  78355. tmat.copyFrom(this._parent.getAbsoluteTransform());
  78356. }
  78357. }
  78358. tmat.invert();
  78359. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, vec);
  78360. lm.m[12] = vec.x;
  78361. lm.m[13] = vec.y;
  78362. lm.m[14] = vec.z;
  78363. }
  78364. this._markAsDirtyAndDecompose();
  78365. };
  78366. /**
  78367. * Set the absolute position of the bone (world space)
  78368. * @param position The position to set the bone
  78369. * @param mesh The mesh that this bone is attached to
  78370. */
  78371. Bone.prototype.setAbsolutePosition = function (position, mesh) {
  78372. this.setPosition(position, BABYLON.Space.WORLD, mesh);
  78373. };
  78374. /**
  78375. * Scale the bone on the x, y and z axes (in local space)
  78376. * @param x The amount to scale the bone on the x axis
  78377. * @param y The amount to scale the bone on the y axis
  78378. * @param z The amount to scale the bone on the z axis
  78379. * @param scaleChildren sets this to true if children of the bone should be scaled as well (false by default)
  78380. */
  78381. Bone.prototype.scale = function (x, y, z, scaleChildren) {
  78382. if (scaleChildren === void 0) { scaleChildren = false; }
  78383. var locMat = this.getLocalMatrix();
  78384. // Apply new scaling on top of current local matrix
  78385. var scaleMat = Bone._tmpMats[0];
  78386. BABYLON.Matrix.ScalingToRef(x, y, z, scaleMat);
  78387. scaleMat.multiplyToRef(locMat, locMat);
  78388. // Invert scaling matrix and apply the inverse to all children
  78389. scaleMat.invert();
  78390. for (var _i = 0, _a = this.children; _i < _a.length; _i++) {
  78391. var child = _a[_i];
  78392. var cm = child.getLocalMatrix();
  78393. cm.multiplyToRef(scaleMat, cm);
  78394. cm.m[12] *= x;
  78395. cm.m[13] *= y;
  78396. cm.m[14] *= z;
  78397. child._markAsDirtyAndDecompose();
  78398. }
  78399. this._markAsDirtyAndDecompose();
  78400. if (scaleChildren) {
  78401. for (var _b = 0, _c = this.children; _b < _c.length; _b++) {
  78402. var child = _c[_b];
  78403. child.scale(x, y, z, scaleChildren);
  78404. }
  78405. }
  78406. };
  78407. /**
  78408. * Set the bone scaling in local space
  78409. * @param scale defines the scaling vector
  78410. */
  78411. Bone.prototype.setScale = function (scale) {
  78412. this._decompose();
  78413. this._localScaling.copyFrom(scale);
  78414. this._markAsDirtyAndCompose();
  78415. };
  78416. /**
  78417. * Gets the current scaling in local space
  78418. * @returns the current scaling vector
  78419. */
  78420. Bone.prototype.getScale = function () {
  78421. this._decompose();
  78422. return this._localScaling;
  78423. };
  78424. /**
  78425. * Gets the current scaling in local space and stores it in a target vector
  78426. * @param result defines the target vector
  78427. */
  78428. Bone.prototype.getScaleToRef = function (result) {
  78429. this._decompose();
  78430. result.copyFrom(this._localScaling);
  78431. };
  78432. /**
  78433. * Set the yaw, pitch, and roll of the bone in local or world space
  78434. * @param yaw The rotation of the bone on the y axis
  78435. * @param pitch The rotation of the bone on the x axis
  78436. * @param roll The rotation of the bone on the z axis
  78437. * @param space The space that the axes of rotation are in
  78438. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78439. */
  78440. Bone.prototype.setYawPitchRoll = function (yaw, pitch, roll, space, mesh) {
  78441. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78442. if (space === BABYLON.Space.LOCAL) {
  78443. var quat = Bone._tmpQuat;
  78444. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, quat);
  78445. this.setRotationQuaternion(quat, space, mesh);
  78446. return;
  78447. }
  78448. var rotMatInv = Bone._tmpMats[0];
  78449. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  78450. return;
  78451. }
  78452. var rotMat = Bone._tmpMats[1];
  78453. BABYLON.Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, rotMat);
  78454. rotMatInv.multiplyToRef(rotMat, rotMat);
  78455. this._rotateWithMatrix(rotMat, space, mesh);
  78456. };
  78457. /**
  78458. * Add a rotation to the bone on an axis in local or world space
  78459. * @param axis The axis to rotate the bone on
  78460. * @param amount The amount to rotate the bone
  78461. * @param space The space that the axis is in
  78462. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78463. */
  78464. Bone.prototype.rotate = function (axis, amount, space, mesh) {
  78465. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78466. var rmat = Bone._tmpMats[0];
  78467. rmat.m[12] = 0;
  78468. rmat.m[13] = 0;
  78469. rmat.m[14] = 0;
  78470. BABYLON.Matrix.RotationAxisToRef(axis, amount, rmat);
  78471. this._rotateWithMatrix(rmat, space, mesh);
  78472. };
  78473. /**
  78474. * Set the rotation of the bone to a particular axis angle in local or world space
  78475. * @param axis The axis to rotate the bone on
  78476. * @param angle The angle that the bone should be rotated to
  78477. * @param space The space that the axis is in
  78478. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78479. */
  78480. Bone.prototype.setAxisAngle = function (axis, angle, space, mesh) {
  78481. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78482. if (space === BABYLON.Space.LOCAL) {
  78483. var quat = Bone._tmpQuat;
  78484. BABYLON.Quaternion.RotationAxisToRef(axis, angle, quat);
  78485. this.setRotationQuaternion(quat, space, mesh);
  78486. return;
  78487. }
  78488. var rotMatInv = Bone._tmpMats[0];
  78489. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  78490. return;
  78491. }
  78492. var rotMat = Bone._tmpMats[1];
  78493. BABYLON.Matrix.RotationAxisToRef(axis, angle, rotMat);
  78494. rotMatInv.multiplyToRef(rotMat, rotMat);
  78495. this._rotateWithMatrix(rotMat, space, mesh);
  78496. };
  78497. /**
  78498. * Set the euler rotation of the bone in local of world space
  78499. * @param rotation The euler rotation that the bone should be set to
  78500. * @param space The space that the rotation is in
  78501. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78502. */
  78503. Bone.prototype.setRotation = function (rotation, space, mesh) {
  78504. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78505. this.setYawPitchRoll(rotation.y, rotation.x, rotation.z, space, mesh);
  78506. };
  78507. /**
  78508. * Set the quaternion rotation of the bone in local of world space
  78509. * @param quat The quaternion rotation that the bone should be set to
  78510. * @param space The space that the rotation is in
  78511. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78512. */
  78513. Bone.prototype.setRotationQuaternion = function (quat, space, mesh) {
  78514. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78515. if (space === BABYLON.Space.LOCAL) {
  78516. this._decompose();
  78517. this._localRotation.copyFrom(quat);
  78518. this._markAsDirtyAndCompose();
  78519. return;
  78520. }
  78521. var rotMatInv = Bone._tmpMats[0];
  78522. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  78523. return;
  78524. }
  78525. var rotMat = Bone._tmpMats[1];
  78526. BABYLON.Matrix.FromQuaternionToRef(quat, rotMat);
  78527. rotMatInv.multiplyToRef(rotMat, rotMat);
  78528. this._rotateWithMatrix(rotMat, space, mesh);
  78529. };
  78530. /**
  78531. * Set the rotation matrix of the bone in local of world space
  78532. * @param rotMat The rotation matrix that the bone should be set to
  78533. * @param space The space that the rotation is in
  78534. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78535. */
  78536. Bone.prototype.setRotationMatrix = function (rotMat, space, mesh) {
  78537. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78538. if (space === BABYLON.Space.LOCAL) {
  78539. var quat = Bone._tmpQuat;
  78540. BABYLON.Quaternion.FromRotationMatrixToRef(rotMat, quat);
  78541. this.setRotationQuaternion(quat, space, mesh);
  78542. return;
  78543. }
  78544. var rotMatInv = Bone._tmpMats[0];
  78545. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  78546. return;
  78547. }
  78548. var rotMat2 = Bone._tmpMats[1];
  78549. rotMat2.copyFrom(rotMat);
  78550. rotMatInv.multiplyToRef(rotMat, rotMat2);
  78551. this._rotateWithMatrix(rotMat2, space, mesh);
  78552. };
  78553. Bone.prototype._rotateWithMatrix = function (rmat, space, mesh) {
  78554. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78555. var lmat = this.getLocalMatrix();
  78556. var lx = lmat.m[12];
  78557. var ly = lmat.m[13];
  78558. var lz = lmat.m[14];
  78559. var parent = this.getParent();
  78560. var parentScale = Bone._tmpMats[3];
  78561. var parentScaleInv = Bone._tmpMats[4];
  78562. if (parent && space == BABYLON.Space.WORLD) {
  78563. if (mesh) {
  78564. parentScale.copyFrom(mesh.getWorldMatrix());
  78565. parent.getAbsoluteTransform().multiplyToRef(parentScale, parentScale);
  78566. }
  78567. else {
  78568. parentScale.copyFrom(parent.getAbsoluteTransform());
  78569. }
  78570. parentScaleInv.copyFrom(parentScale);
  78571. parentScaleInv.invert();
  78572. lmat.multiplyToRef(parentScale, lmat);
  78573. lmat.multiplyToRef(rmat, lmat);
  78574. lmat.multiplyToRef(parentScaleInv, lmat);
  78575. }
  78576. else {
  78577. if (space == BABYLON.Space.WORLD && mesh) {
  78578. parentScale.copyFrom(mesh.getWorldMatrix());
  78579. parentScaleInv.copyFrom(parentScale);
  78580. parentScaleInv.invert();
  78581. lmat.multiplyToRef(parentScale, lmat);
  78582. lmat.multiplyToRef(rmat, lmat);
  78583. lmat.multiplyToRef(parentScaleInv, lmat);
  78584. }
  78585. else {
  78586. lmat.multiplyToRef(rmat, lmat);
  78587. }
  78588. }
  78589. lmat.m[12] = lx;
  78590. lmat.m[13] = ly;
  78591. lmat.m[14] = lz;
  78592. this.computeAbsoluteTransforms();
  78593. this._markAsDirtyAndDecompose();
  78594. };
  78595. Bone.prototype._getNegativeRotationToRef = function (rotMatInv, mesh) {
  78596. var scaleMatrix = Bone._tmpMats[2];
  78597. rotMatInv.copyFrom(this.getAbsoluteTransform());
  78598. if (mesh) {
  78599. rotMatInv.multiplyToRef(mesh.getWorldMatrix(), rotMatInv);
  78600. BABYLON.Matrix.ScalingToRef(mesh.scaling.x, mesh.scaling.y, mesh.scaling.z, scaleMatrix);
  78601. }
  78602. rotMatInv.invert();
  78603. if (isNaN(rotMatInv.m[0])) {
  78604. // Matrix failed to invert.
  78605. // This can happen if scale is zero for example.
  78606. return false;
  78607. }
  78608. scaleMatrix.m[0] *= this._scalingDeterminant;
  78609. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  78610. return true;
  78611. };
  78612. /**
  78613. * Get the position of the bone in local or world space
  78614. * @param space The space that the returned position is in
  78615. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78616. * @returns The position of the bone
  78617. */
  78618. Bone.prototype.getPosition = function (space, mesh) {
  78619. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78620. if (mesh === void 0) { mesh = null; }
  78621. var pos = BABYLON.Vector3.Zero();
  78622. this.getPositionToRef(space, mesh, pos);
  78623. return pos;
  78624. };
  78625. /**
  78626. * Copy the position of the bone to a vector3 in local or world space
  78627. * @param space The space that the returned position is in
  78628. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78629. * @param result The vector3 to copy the position to
  78630. */
  78631. Bone.prototype.getPositionToRef = function (space, mesh, result) {
  78632. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78633. if (space == BABYLON.Space.LOCAL) {
  78634. var lm = this.getLocalMatrix();
  78635. result.x = lm.m[12];
  78636. result.y = lm.m[13];
  78637. result.z = lm.m[14];
  78638. }
  78639. else {
  78640. var wm = null;
  78641. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  78642. if (mesh) {
  78643. wm = mesh.getWorldMatrix();
  78644. }
  78645. this._skeleton.computeAbsoluteTransforms();
  78646. var tmat = Bone._tmpMats[0];
  78647. if (mesh && wm) {
  78648. tmat.copyFrom(this.getAbsoluteTransform());
  78649. tmat.multiplyToRef(wm, tmat);
  78650. }
  78651. else {
  78652. tmat = this.getAbsoluteTransform();
  78653. }
  78654. result.x = tmat.m[12];
  78655. result.y = tmat.m[13];
  78656. result.z = tmat.m[14];
  78657. }
  78658. };
  78659. /**
  78660. * Get the absolute position of the bone (world space)
  78661. * @param mesh The mesh that this bone is attached to
  78662. * @returns The absolute position of the bone
  78663. */
  78664. Bone.prototype.getAbsolutePosition = function (mesh) {
  78665. if (mesh === void 0) { mesh = null; }
  78666. var pos = BABYLON.Vector3.Zero();
  78667. this.getPositionToRef(BABYLON.Space.WORLD, mesh, pos);
  78668. return pos;
  78669. };
  78670. /**
  78671. * Copy the absolute position of the bone (world space) to the result param
  78672. * @param mesh The mesh that this bone is attached to
  78673. * @param result The vector3 to copy the absolute position to
  78674. */
  78675. Bone.prototype.getAbsolutePositionToRef = function (mesh, result) {
  78676. this.getPositionToRef(BABYLON.Space.WORLD, mesh, result);
  78677. };
  78678. /**
  78679. * Compute the absolute transforms of this bone and its children
  78680. */
  78681. Bone.prototype.computeAbsoluteTransforms = function () {
  78682. this._compose();
  78683. if (this._parent) {
  78684. this._localMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  78685. }
  78686. else {
  78687. this._absoluteTransform.copyFrom(this._localMatrix);
  78688. var poseMatrix = this._skeleton.getPoseMatrix();
  78689. if (poseMatrix) {
  78690. this._absoluteTransform.multiplyToRef(poseMatrix, this._absoluteTransform);
  78691. }
  78692. }
  78693. var children = this.children;
  78694. var len = children.length;
  78695. for (var i = 0; i < len; i++) {
  78696. children[i].computeAbsoluteTransforms();
  78697. }
  78698. };
  78699. /**
  78700. * Get the world direction from an axis that is in the local space of the bone
  78701. * @param localAxis The local direction that is used to compute the world direction
  78702. * @param mesh The mesh that this bone is attached to
  78703. * @returns The world direction
  78704. */
  78705. Bone.prototype.getDirection = function (localAxis, mesh) {
  78706. if (mesh === void 0) { mesh = null; }
  78707. var result = BABYLON.Vector3.Zero();
  78708. this.getDirectionToRef(localAxis, mesh, result);
  78709. return result;
  78710. };
  78711. /**
  78712. * Copy the world direction to a vector3 from an axis that is in the local space of the bone
  78713. * @param localAxis The local direction that is used to compute the world direction
  78714. * @param mesh The mesh that this bone is attached to
  78715. * @param result The vector3 that the world direction will be copied to
  78716. */
  78717. Bone.prototype.getDirectionToRef = function (localAxis, mesh, result) {
  78718. if (mesh === void 0) { mesh = null; }
  78719. var wm = null;
  78720. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  78721. if (mesh) {
  78722. wm = mesh.getWorldMatrix();
  78723. }
  78724. this._skeleton.computeAbsoluteTransforms();
  78725. var mat = Bone._tmpMats[0];
  78726. mat.copyFrom(this.getAbsoluteTransform());
  78727. if (mesh && wm) {
  78728. mat.multiplyToRef(wm, mat);
  78729. }
  78730. BABYLON.Vector3.TransformNormalToRef(localAxis, mat, result);
  78731. result.normalize();
  78732. };
  78733. /**
  78734. * Get the euler rotation of the bone in local or world space
  78735. * @param space The space that the rotation should be in
  78736. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78737. * @returns The euler rotation
  78738. */
  78739. Bone.prototype.getRotation = function (space, mesh) {
  78740. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78741. if (mesh === void 0) { mesh = null; }
  78742. var result = BABYLON.Vector3.Zero();
  78743. this.getRotationToRef(space, mesh, result);
  78744. return result;
  78745. };
  78746. /**
  78747. * Copy the euler rotation of the bone to a vector3. The rotation can be in either local or world space
  78748. * @param space The space that the rotation should be in
  78749. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78750. * @param result The vector3 that the rotation should be copied to
  78751. */
  78752. Bone.prototype.getRotationToRef = function (space, mesh, result) {
  78753. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78754. if (mesh === void 0) { mesh = null; }
  78755. var quat = Bone._tmpQuat;
  78756. this.getRotationQuaternionToRef(space, mesh, quat);
  78757. quat.toEulerAnglesToRef(result);
  78758. };
  78759. /**
  78760. * Get the quaternion rotation of the bone in either local or world space
  78761. * @param space The space that the rotation should be in
  78762. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78763. * @returns The quaternion rotation
  78764. */
  78765. Bone.prototype.getRotationQuaternion = function (space, mesh) {
  78766. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78767. if (mesh === void 0) { mesh = null; }
  78768. var result = BABYLON.Quaternion.Identity();
  78769. this.getRotationQuaternionToRef(space, mesh, result);
  78770. return result;
  78771. };
  78772. /**
  78773. * Copy the quaternion rotation of the bone to a quaternion. The rotation can be in either local or world space
  78774. * @param space The space that the rotation should be in
  78775. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78776. * @param result The quaternion that the rotation should be copied to
  78777. */
  78778. Bone.prototype.getRotationQuaternionToRef = function (space, mesh, result) {
  78779. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78780. if (mesh === void 0) { mesh = null; }
  78781. if (space == BABYLON.Space.LOCAL) {
  78782. this._decompose();
  78783. result.copyFrom(this._localRotation);
  78784. }
  78785. else {
  78786. var mat = Bone._tmpMats[0];
  78787. var amat = this.getAbsoluteTransform();
  78788. if (mesh) {
  78789. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  78790. }
  78791. else {
  78792. mat.copyFrom(amat);
  78793. }
  78794. mat.m[0] *= this._scalingDeterminant;
  78795. mat.m[1] *= this._scalingDeterminant;
  78796. mat.m[2] *= this._scalingDeterminant;
  78797. mat.decompose(undefined, result, undefined);
  78798. }
  78799. };
  78800. /**
  78801. * Get the rotation matrix of the bone in local or world space
  78802. * @param space The space that the rotation should be in
  78803. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78804. * @returns The rotation matrix
  78805. */
  78806. Bone.prototype.getRotationMatrix = function (space, mesh) {
  78807. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78808. var result = BABYLON.Matrix.Identity();
  78809. this.getRotationMatrixToRef(space, mesh, result);
  78810. return result;
  78811. };
  78812. /**
  78813. * Copy the rotation matrix of the bone to a matrix. The rotation can be in either local or world space
  78814. * @param space The space that the rotation should be in
  78815. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78816. * @param result The quaternion that the rotation should be copied to
  78817. */
  78818. Bone.prototype.getRotationMatrixToRef = function (space, mesh, result) {
  78819. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78820. if (space == BABYLON.Space.LOCAL) {
  78821. this.getLocalMatrix().getRotationMatrixToRef(result);
  78822. }
  78823. else {
  78824. var mat = Bone._tmpMats[0];
  78825. var amat = this.getAbsoluteTransform();
  78826. if (mesh) {
  78827. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  78828. }
  78829. else {
  78830. mat.copyFrom(amat);
  78831. }
  78832. mat.m[0] *= this._scalingDeterminant;
  78833. mat.m[1] *= this._scalingDeterminant;
  78834. mat.m[2] *= this._scalingDeterminant;
  78835. mat.getRotationMatrixToRef(result);
  78836. }
  78837. };
  78838. /**
  78839. * Get the world position of a point that is in the local space of the bone
  78840. * @param position The local position
  78841. * @param mesh The mesh that this bone is attached to
  78842. * @returns The world position
  78843. */
  78844. Bone.prototype.getAbsolutePositionFromLocal = function (position, mesh) {
  78845. if (mesh === void 0) { mesh = null; }
  78846. var result = BABYLON.Vector3.Zero();
  78847. this.getAbsolutePositionFromLocalToRef(position, mesh, result);
  78848. return result;
  78849. };
  78850. /**
  78851. * Get the world position of a point that is in the local space of the bone and copy it to the result param
  78852. * @param position The local position
  78853. * @param mesh The mesh that this bone is attached to
  78854. * @param result The vector3 that the world position should be copied to
  78855. */
  78856. Bone.prototype.getAbsolutePositionFromLocalToRef = function (position, mesh, result) {
  78857. if (mesh === void 0) { mesh = null; }
  78858. var wm = null;
  78859. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  78860. if (mesh) {
  78861. wm = mesh.getWorldMatrix();
  78862. }
  78863. this._skeleton.computeAbsoluteTransforms();
  78864. var tmat = Bone._tmpMats[0];
  78865. if (mesh && wm) {
  78866. tmat.copyFrom(this.getAbsoluteTransform());
  78867. tmat.multiplyToRef(wm, tmat);
  78868. }
  78869. else {
  78870. tmat = this.getAbsoluteTransform();
  78871. }
  78872. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  78873. };
  78874. /**
  78875. * Get the local position of a point that is in world space
  78876. * @param position The world position
  78877. * @param mesh The mesh that this bone is attached to
  78878. * @returns The local position
  78879. */
  78880. Bone.prototype.getLocalPositionFromAbsolute = function (position, mesh) {
  78881. if (mesh === void 0) { mesh = null; }
  78882. var result = BABYLON.Vector3.Zero();
  78883. this.getLocalPositionFromAbsoluteToRef(position, mesh, result);
  78884. return result;
  78885. };
  78886. /**
  78887. * Get the local position of a point that is in world space and copy it to the result param
  78888. * @param position The world position
  78889. * @param mesh The mesh that this bone is attached to
  78890. * @param result The vector3 that the local position should be copied to
  78891. */
  78892. Bone.prototype.getLocalPositionFromAbsoluteToRef = function (position, mesh, result) {
  78893. if (mesh === void 0) { mesh = null; }
  78894. var wm = null;
  78895. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  78896. if (mesh) {
  78897. wm = mesh.getWorldMatrix();
  78898. }
  78899. this._skeleton.computeAbsoluteTransforms();
  78900. var tmat = Bone._tmpMats[0];
  78901. tmat.copyFrom(this.getAbsoluteTransform());
  78902. if (mesh && wm) {
  78903. tmat.multiplyToRef(wm, tmat);
  78904. }
  78905. tmat.invert();
  78906. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  78907. };
  78908. Bone._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  78909. Bone._tmpQuat = BABYLON.Quaternion.Identity();
  78910. Bone._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  78911. return Bone;
  78912. }(BABYLON.Node));
  78913. BABYLON.Bone = Bone;
  78914. })(BABYLON || (BABYLON = {}));
  78915. //# sourceMappingURL=babylon.bone.js.map
  78916. var BABYLON;
  78917. (function (BABYLON) {
  78918. /**
  78919. * Class used to apply inverse kinematics to bones
  78920. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons#boneikcontroller
  78921. */
  78922. var BoneIKController = /** @class */ (function () {
  78923. /**
  78924. * Creates a new BoneIKController
  78925. * @param mesh defines the mesh to control
  78926. * @param bone defines the bone to control
  78927. * @param options defines options to set up the controller
  78928. */
  78929. function BoneIKController(mesh, bone, options) {
  78930. /**
  78931. * Gets or sets the target position
  78932. */
  78933. this.targetPosition = BABYLON.Vector3.Zero();
  78934. /**
  78935. * Gets or sets the pole target position
  78936. */
  78937. this.poleTargetPosition = BABYLON.Vector3.Zero();
  78938. /**
  78939. * Gets or sets the pole target local offset
  78940. */
  78941. this.poleTargetLocalOffset = BABYLON.Vector3.Zero();
  78942. /**
  78943. * Gets or sets the pole angle
  78944. */
  78945. this.poleAngle = 0;
  78946. /**
  78947. * 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)
  78948. */
  78949. this.slerpAmount = 1;
  78950. this._bone1Quat = BABYLON.Quaternion.Identity();
  78951. this._bone1Mat = BABYLON.Matrix.Identity();
  78952. this._bone2Ang = Math.PI;
  78953. this._maxAngle = Math.PI;
  78954. this._rightHandedSystem = false;
  78955. this._bendAxis = BABYLON.Vector3.Right();
  78956. this._slerping = false;
  78957. this._adjustRoll = 0;
  78958. this._bone2 = bone;
  78959. this._bone1 = bone.getParent();
  78960. if (!this._bone1) {
  78961. return;
  78962. }
  78963. this.mesh = mesh;
  78964. var bonePos = bone.getPosition();
  78965. if (bone.getAbsoluteTransform().determinant() > 0) {
  78966. this._rightHandedSystem = true;
  78967. this._bendAxis.x = 0;
  78968. this._bendAxis.y = 0;
  78969. this._bendAxis.z = -1;
  78970. if (bonePos.x > bonePos.y && bonePos.x > bonePos.z) {
  78971. this._adjustRoll = Math.PI * .5;
  78972. this._bendAxis.z = 1;
  78973. }
  78974. }
  78975. if (this._bone1.length) {
  78976. var boneScale1 = this._bone1.getScale();
  78977. var boneScale2 = this._bone2.getScale();
  78978. this._bone1Length = this._bone1.length * boneScale1.y * this.mesh.scaling.y;
  78979. this._bone2Length = this._bone2.length * boneScale2.y * this.mesh.scaling.y;
  78980. }
  78981. else if (this._bone1.children[0]) {
  78982. mesh.computeWorldMatrix(true);
  78983. var pos1 = this._bone2.children[0].getAbsolutePosition(mesh);
  78984. var pos2 = this._bone2.getAbsolutePosition(mesh);
  78985. var pos3 = this._bone1.getAbsolutePosition(mesh);
  78986. this._bone1Length = BABYLON.Vector3.Distance(pos1, pos2);
  78987. this._bone2Length = BABYLON.Vector3.Distance(pos2, pos3);
  78988. }
  78989. this._bone1.getRotationMatrixToRef(BABYLON.Space.WORLD, mesh, this._bone1Mat);
  78990. this.maxAngle = Math.PI;
  78991. if (options) {
  78992. if (options.targetMesh) {
  78993. this.targetMesh = options.targetMesh;
  78994. this.targetMesh.computeWorldMatrix(true);
  78995. }
  78996. if (options.poleTargetMesh) {
  78997. this.poleTargetMesh = options.poleTargetMesh;
  78998. this.poleTargetMesh.computeWorldMatrix(true);
  78999. }
  79000. else if (options.poleTargetBone) {
  79001. this.poleTargetBone = options.poleTargetBone;
  79002. }
  79003. else if (this._bone1.getParent()) {
  79004. this.poleTargetBone = this._bone1.getParent();
  79005. }
  79006. if (options.poleTargetLocalOffset) {
  79007. this.poleTargetLocalOffset.copyFrom(options.poleTargetLocalOffset);
  79008. }
  79009. if (options.poleAngle) {
  79010. this.poleAngle = options.poleAngle;
  79011. }
  79012. if (options.bendAxis) {
  79013. this._bendAxis.copyFrom(options.bendAxis);
  79014. }
  79015. if (options.maxAngle) {
  79016. this.maxAngle = options.maxAngle;
  79017. }
  79018. if (options.slerpAmount) {
  79019. this.slerpAmount = options.slerpAmount;
  79020. }
  79021. }
  79022. }
  79023. Object.defineProperty(BoneIKController.prototype, "maxAngle", {
  79024. /**
  79025. * Gets or sets maximum allowed angle
  79026. */
  79027. get: function () {
  79028. return this._maxAngle;
  79029. },
  79030. set: function (value) {
  79031. this._setMaxAngle(value);
  79032. },
  79033. enumerable: true,
  79034. configurable: true
  79035. });
  79036. BoneIKController.prototype._setMaxAngle = function (ang) {
  79037. if (ang < 0) {
  79038. ang = 0;
  79039. }
  79040. if (ang > Math.PI || ang == undefined) {
  79041. ang = Math.PI;
  79042. }
  79043. this._maxAngle = ang;
  79044. var a = this._bone1Length;
  79045. var b = this._bone2Length;
  79046. this._maxReach = Math.sqrt(a * a + b * b - 2 * a * b * Math.cos(ang));
  79047. };
  79048. /**
  79049. * Force the controller to update the bones
  79050. */
  79051. BoneIKController.prototype.update = function () {
  79052. var bone1 = this._bone1;
  79053. if (!bone1) {
  79054. return;
  79055. }
  79056. var target = this.targetPosition;
  79057. var poleTarget = this.poleTargetPosition;
  79058. var mat1 = BoneIKController._tmpMats[0];
  79059. var mat2 = BoneIKController._tmpMats[1];
  79060. if (this.targetMesh) {
  79061. target.copyFrom(this.targetMesh.getAbsolutePosition());
  79062. }
  79063. if (this.poleTargetBone) {
  79064. this.poleTargetBone.getAbsolutePositionFromLocalToRef(this.poleTargetLocalOffset, this.mesh, poleTarget);
  79065. }
  79066. else if (this.poleTargetMesh) {
  79067. BABYLON.Vector3.TransformCoordinatesToRef(this.poleTargetLocalOffset, this.poleTargetMesh.getWorldMatrix(), poleTarget);
  79068. }
  79069. var bonePos = BoneIKController._tmpVecs[0];
  79070. var zaxis = BoneIKController._tmpVecs[1];
  79071. var xaxis = BoneIKController._tmpVecs[2];
  79072. var yaxis = BoneIKController._tmpVecs[3];
  79073. var upAxis = BoneIKController._tmpVecs[4];
  79074. var _tmpQuat = BoneIKController._tmpQuat;
  79075. bone1.getAbsolutePositionToRef(this.mesh, bonePos);
  79076. poleTarget.subtractToRef(bonePos, upAxis);
  79077. if (upAxis.x == 0 && upAxis.y == 0 && upAxis.z == 0) {
  79078. upAxis.y = 1;
  79079. }
  79080. else {
  79081. upAxis.normalize();
  79082. }
  79083. target.subtractToRef(bonePos, yaxis);
  79084. yaxis.normalize();
  79085. BABYLON.Vector3.CrossToRef(yaxis, upAxis, zaxis);
  79086. zaxis.normalize();
  79087. BABYLON.Vector3.CrossToRef(yaxis, zaxis, xaxis);
  79088. xaxis.normalize();
  79089. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, mat1);
  79090. var a = this._bone1Length;
  79091. var b = this._bone2Length;
  79092. var c = BABYLON.Vector3.Distance(bonePos, target);
  79093. if (this._maxReach > 0) {
  79094. c = Math.min(this._maxReach, c);
  79095. }
  79096. var acosa = (b * b + c * c - a * a) / (2 * b * c);
  79097. var acosb = (c * c + a * a - b * b) / (2 * c * a);
  79098. if (acosa > 1) {
  79099. acosa = 1;
  79100. }
  79101. if (acosb > 1) {
  79102. acosb = 1;
  79103. }
  79104. if (acosa < -1) {
  79105. acosa = -1;
  79106. }
  79107. if (acosb < -1) {
  79108. acosb = -1;
  79109. }
  79110. var angA = Math.acos(acosa);
  79111. var angB = Math.acos(acosb);
  79112. var angC = -angA - angB;
  79113. if (this._rightHandedSystem) {
  79114. BABYLON.Matrix.RotationYawPitchRollToRef(0, 0, this._adjustRoll, mat2);
  79115. mat2.multiplyToRef(mat1, mat1);
  79116. BABYLON.Matrix.RotationAxisToRef(this._bendAxis, angB, mat2);
  79117. mat2.multiplyToRef(mat1, mat1);
  79118. }
  79119. else {
  79120. var _tmpVec = BoneIKController._tmpVecs[5];
  79121. _tmpVec.copyFrom(this._bendAxis);
  79122. _tmpVec.x *= -1;
  79123. BABYLON.Matrix.RotationAxisToRef(_tmpVec, -angB, mat2);
  79124. mat2.multiplyToRef(mat1, mat1);
  79125. }
  79126. if (this.poleAngle) {
  79127. BABYLON.Matrix.RotationAxisToRef(yaxis, this.poleAngle, mat2);
  79128. mat1.multiplyToRef(mat2, mat1);
  79129. }
  79130. if (this._bone1) {
  79131. if (this.slerpAmount < 1) {
  79132. if (!this._slerping) {
  79133. BABYLON.Quaternion.FromRotationMatrixToRef(this._bone1Mat, this._bone1Quat);
  79134. }
  79135. BABYLON.Quaternion.FromRotationMatrixToRef(mat1, _tmpQuat);
  79136. BABYLON.Quaternion.SlerpToRef(this._bone1Quat, _tmpQuat, this.slerpAmount, this._bone1Quat);
  79137. angC = this._bone2Ang * (1.0 - this.slerpAmount) + angC * this.slerpAmount;
  79138. this._bone1.setRotationQuaternion(this._bone1Quat, BABYLON.Space.WORLD, this.mesh);
  79139. this._slerping = true;
  79140. }
  79141. else {
  79142. this._bone1.setRotationMatrix(mat1, BABYLON.Space.WORLD, this.mesh);
  79143. this._bone1Mat.copyFrom(mat1);
  79144. this._slerping = false;
  79145. }
  79146. }
  79147. this._bone2.setAxisAngle(this._bendAxis, angC, BABYLON.Space.LOCAL);
  79148. this._bone2Ang = angC;
  79149. };
  79150. BoneIKController._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  79151. BoneIKController._tmpQuat = BABYLON.Quaternion.Identity();
  79152. BoneIKController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  79153. return BoneIKController;
  79154. }());
  79155. BABYLON.BoneIKController = BoneIKController;
  79156. })(BABYLON || (BABYLON = {}));
  79157. //# sourceMappingURL=babylon.boneIKController.js.map
  79158. var BABYLON;
  79159. (function (BABYLON) {
  79160. /**
  79161. * Class used to make a bone look toward a point in space
  79162. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons#bonelookcontroller
  79163. */
  79164. var BoneLookController = /** @class */ (function () {
  79165. /**
  79166. * Create a BoneLookController
  79167. * @param mesh the mesh that the bone belongs to
  79168. * @param bone the bone that will be looking to the target
  79169. * @param target the target Vector3 to look at
  79170. * @param settings optional settings:
  79171. * * maxYaw: the maximum angle the bone will yaw to
  79172. * * minYaw: the minimum angle the bone will yaw to
  79173. * * maxPitch: the maximum angle the bone will pitch to
  79174. * * minPitch: the minimum angle the bone will yaw to
  79175. * * slerpAmount: set the between 0 and 1 to make the bone slerp to the target.
  79176. * * upAxis: the up axis of the coordinate system
  79177. * * upAxisSpace: the space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  79178. * * yawAxis: set yawAxis if the bone does not yaw on the y axis
  79179. * * pitchAxis: set pitchAxis if the bone does not pitch on the x axis
  79180. * * adjustYaw: used to make an adjustment to the yaw of the bone
  79181. * * adjustPitch: used to make an adjustment to the pitch of the bone
  79182. * * adjustRoll: used to make an adjustment to the roll of the bone
  79183. **/
  79184. function BoneLookController(mesh, bone, target, options) {
  79185. /**
  79186. * The up axis of the coordinate system that is used when the bone is rotated
  79187. */
  79188. this.upAxis = BABYLON.Vector3.Up();
  79189. /**
  79190. * The space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD
  79191. */
  79192. this.upAxisSpace = BABYLON.Space.LOCAL;
  79193. /**
  79194. * Used to make an adjustment to the yaw of the bone
  79195. */
  79196. this.adjustYaw = 0;
  79197. /**
  79198. * Used to make an adjustment to the pitch of the bone
  79199. */
  79200. this.adjustPitch = 0;
  79201. /**
  79202. * Used to make an adjustment to the roll of the bone
  79203. */
  79204. this.adjustRoll = 0;
  79205. /**
  79206. * 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)
  79207. */
  79208. this.slerpAmount = 1;
  79209. this._boneQuat = BABYLON.Quaternion.Identity();
  79210. this._slerping = false;
  79211. this._firstFrameSkipped = false;
  79212. this._fowardAxis = BABYLON.Vector3.Forward();
  79213. this.mesh = mesh;
  79214. this.bone = bone;
  79215. this.target = target;
  79216. if (options) {
  79217. if (options.adjustYaw) {
  79218. this.adjustYaw = options.adjustYaw;
  79219. }
  79220. if (options.adjustPitch) {
  79221. this.adjustPitch = options.adjustPitch;
  79222. }
  79223. if (options.adjustRoll) {
  79224. this.adjustRoll = options.adjustRoll;
  79225. }
  79226. if (options.maxYaw != null) {
  79227. this.maxYaw = options.maxYaw;
  79228. }
  79229. else {
  79230. this.maxYaw = Math.PI;
  79231. }
  79232. if (options.minYaw != null) {
  79233. this.minYaw = options.minYaw;
  79234. }
  79235. else {
  79236. this.minYaw = -Math.PI;
  79237. }
  79238. if (options.maxPitch != null) {
  79239. this.maxPitch = options.maxPitch;
  79240. }
  79241. else {
  79242. this.maxPitch = Math.PI;
  79243. }
  79244. if (options.minPitch != null) {
  79245. this.minPitch = options.minPitch;
  79246. }
  79247. else {
  79248. this.minPitch = -Math.PI;
  79249. }
  79250. if (options.slerpAmount != null) {
  79251. this.slerpAmount = options.slerpAmount;
  79252. }
  79253. if (options.upAxis != null) {
  79254. this.upAxis = options.upAxis;
  79255. }
  79256. if (options.upAxisSpace != null) {
  79257. this.upAxisSpace = options.upAxisSpace;
  79258. }
  79259. if (options.yawAxis != null || options.pitchAxis != null) {
  79260. var newYawAxis = BABYLON.Axis.Y;
  79261. var newPitchAxis = BABYLON.Axis.X;
  79262. if (options.yawAxis != null) {
  79263. newYawAxis = options.yawAxis.clone();
  79264. newYawAxis.normalize();
  79265. }
  79266. if (options.pitchAxis != null) {
  79267. newPitchAxis = options.pitchAxis.clone();
  79268. newPitchAxis.normalize();
  79269. }
  79270. var newRollAxis = BABYLON.Vector3.Cross(newPitchAxis, newYawAxis);
  79271. this._transformYawPitch = BABYLON.Matrix.Identity();
  79272. BABYLON.Matrix.FromXYZAxesToRef(newPitchAxis, newYawAxis, newRollAxis, this._transformYawPitch);
  79273. this._transformYawPitchInv = this._transformYawPitch.clone();
  79274. this._transformYawPitch.invert();
  79275. }
  79276. }
  79277. if (!bone.getParent() && this.upAxisSpace == BABYLON.Space.BONE) {
  79278. this.upAxisSpace = BABYLON.Space.LOCAL;
  79279. }
  79280. }
  79281. Object.defineProperty(BoneLookController.prototype, "minYaw", {
  79282. /**
  79283. * Gets or sets the minimum yaw angle that the bone can look to
  79284. */
  79285. get: function () {
  79286. return this._minYaw;
  79287. },
  79288. set: function (value) {
  79289. this._minYaw = value;
  79290. this._minYawSin = Math.sin(value);
  79291. this._minYawCos = Math.cos(value);
  79292. if (this._maxYaw != null) {
  79293. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  79294. this._yawRange = this._maxYaw - this._minYaw;
  79295. }
  79296. },
  79297. enumerable: true,
  79298. configurable: true
  79299. });
  79300. Object.defineProperty(BoneLookController.prototype, "maxYaw", {
  79301. /**
  79302. * Gets or sets the maximum yaw angle that the bone can look to
  79303. */
  79304. get: function () {
  79305. return this._maxYaw;
  79306. },
  79307. set: function (value) {
  79308. this._maxYaw = value;
  79309. this._maxYawSin = Math.sin(value);
  79310. this._maxYawCos = Math.cos(value);
  79311. if (this._minYaw != null) {
  79312. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  79313. this._yawRange = this._maxYaw - this._minYaw;
  79314. }
  79315. },
  79316. enumerable: true,
  79317. configurable: true
  79318. });
  79319. Object.defineProperty(BoneLookController.prototype, "minPitch", {
  79320. /**
  79321. * Gets or sets the minimum pitch angle that the bone can look to
  79322. */
  79323. get: function () {
  79324. return this._minPitch;
  79325. },
  79326. set: function (value) {
  79327. this._minPitch = value;
  79328. this._minPitchTan = Math.tan(value);
  79329. },
  79330. enumerable: true,
  79331. configurable: true
  79332. });
  79333. Object.defineProperty(BoneLookController.prototype, "maxPitch", {
  79334. /**
  79335. * Gets or sets the maximum pitch angle that the bone can look to
  79336. */
  79337. get: function () {
  79338. return this._maxPitch;
  79339. },
  79340. set: function (value) {
  79341. this._maxPitch = value;
  79342. this._maxPitchTan = Math.tan(value);
  79343. },
  79344. enumerable: true,
  79345. configurable: true
  79346. });
  79347. /**
  79348. * Update the bone to look at the target. This should be called before the scene is rendered (use scene.registerBeforeRender())
  79349. */
  79350. BoneLookController.prototype.update = function () {
  79351. //skip the first frame when slerping so that the mesh rotation is correct
  79352. if (this.slerpAmount < 1 && !this._firstFrameSkipped) {
  79353. this._firstFrameSkipped = true;
  79354. return;
  79355. }
  79356. var bone = this.bone;
  79357. var bonePos = BoneLookController._tmpVecs[0];
  79358. bone.getAbsolutePositionToRef(this.mesh, bonePos);
  79359. var target = this.target;
  79360. var _tmpMat1 = BoneLookController._tmpMats[0];
  79361. var _tmpMat2 = BoneLookController._tmpMats[1];
  79362. var mesh = this.mesh;
  79363. var parentBone = bone.getParent();
  79364. var upAxis = BoneLookController._tmpVecs[1];
  79365. upAxis.copyFrom(this.upAxis);
  79366. if (this.upAxisSpace == BABYLON.Space.BONE && parentBone) {
  79367. if (this._transformYawPitch) {
  79368. BABYLON.Vector3.TransformCoordinatesToRef(upAxis, this._transformYawPitchInv, upAxis);
  79369. }
  79370. parentBone.getDirectionToRef(upAxis, this.mesh, upAxis);
  79371. }
  79372. else if (this.upAxisSpace == BABYLON.Space.LOCAL) {
  79373. mesh.getDirectionToRef(upAxis, upAxis);
  79374. if (mesh.scaling.x != 1 || mesh.scaling.y != 1 || mesh.scaling.z != 1) {
  79375. upAxis.normalize();
  79376. }
  79377. }
  79378. var checkYaw = false;
  79379. var checkPitch = false;
  79380. if (this._maxYaw != Math.PI || this._minYaw != -Math.PI) {
  79381. checkYaw = true;
  79382. }
  79383. if (this._maxPitch != Math.PI || this._minPitch != -Math.PI) {
  79384. checkPitch = true;
  79385. }
  79386. if (checkYaw || checkPitch) {
  79387. var spaceMat = BoneLookController._tmpMats[2];
  79388. var spaceMatInv = BoneLookController._tmpMats[3];
  79389. if (this.upAxisSpace == BABYLON.Space.BONE && upAxis.y == 1 && parentBone) {
  79390. parentBone.getRotationMatrixToRef(BABYLON.Space.WORLD, this.mesh, spaceMat);
  79391. }
  79392. else if (this.upAxisSpace == BABYLON.Space.LOCAL && upAxis.y == 1 && !parentBone) {
  79393. spaceMat.copyFrom(mesh.getWorldMatrix());
  79394. }
  79395. else {
  79396. var forwardAxis = BoneLookController._tmpVecs[2];
  79397. forwardAxis.copyFrom(this._fowardAxis);
  79398. if (this._transformYawPitch) {
  79399. BABYLON.Vector3.TransformCoordinatesToRef(forwardAxis, this._transformYawPitchInv, forwardAxis);
  79400. }
  79401. if (parentBone) {
  79402. parentBone.getDirectionToRef(forwardAxis, this.mesh, forwardAxis);
  79403. }
  79404. else {
  79405. mesh.getDirectionToRef(forwardAxis, forwardAxis);
  79406. }
  79407. var rightAxis = BABYLON.Vector3.Cross(upAxis, forwardAxis);
  79408. rightAxis.normalize();
  79409. var forwardAxis = BABYLON.Vector3.Cross(rightAxis, upAxis);
  79410. BABYLON.Matrix.FromXYZAxesToRef(rightAxis, upAxis, forwardAxis, spaceMat);
  79411. }
  79412. spaceMat.invertToRef(spaceMatInv);
  79413. var xzlen = null;
  79414. if (checkPitch) {
  79415. var localTarget = BoneLookController._tmpVecs[3];
  79416. target.subtractToRef(bonePos, localTarget);
  79417. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  79418. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  79419. var pitch = Math.atan2(localTarget.y, xzlen);
  79420. var newPitch = pitch;
  79421. if (pitch > this._maxPitch) {
  79422. localTarget.y = this._maxPitchTan * xzlen;
  79423. newPitch = this._maxPitch;
  79424. }
  79425. else if (pitch < this._minPitch) {
  79426. localTarget.y = this._minPitchTan * xzlen;
  79427. newPitch = this._minPitch;
  79428. }
  79429. if (pitch != newPitch) {
  79430. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  79431. localTarget.addInPlace(bonePos);
  79432. target = localTarget;
  79433. }
  79434. }
  79435. if (checkYaw) {
  79436. var localTarget = BoneLookController._tmpVecs[4];
  79437. target.subtractToRef(bonePos, localTarget);
  79438. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  79439. var yaw = Math.atan2(localTarget.x, localTarget.z);
  79440. var newYaw = yaw;
  79441. if (yaw > this._maxYaw || yaw < this._minYaw) {
  79442. if (xzlen == null) {
  79443. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  79444. }
  79445. if (this._yawRange > Math.PI) {
  79446. if (this._isAngleBetween(yaw, this._maxYaw, this._midYawConstraint)) {
  79447. localTarget.z = this._maxYawCos * xzlen;
  79448. localTarget.x = this._maxYawSin * xzlen;
  79449. newYaw = this._maxYaw;
  79450. }
  79451. else if (this._isAngleBetween(yaw, this._midYawConstraint, this._minYaw)) {
  79452. localTarget.z = this._minYawCos * xzlen;
  79453. localTarget.x = this._minYawSin * xzlen;
  79454. newYaw = this._minYaw;
  79455. }
  79456. }
  79457. else {
  79458. if (yaw > this._maxYaw) {
  79459. localTarget.z = this._maxYawCos * xzlen;
  79460. localTarget.x = this._maxYawSin * xzlen;
  79461. newYaw = this._maxYaw;
  79462. }
  79463. else if (yaw < this._minYaw) {
  79464. localTarget.z = this._minYawCos * xzlen;
  79465. localTarget.x = this._minYawSin * xzlen;
  79466. newYaw = this._minYaw;
  79467. }
  79468. }
  79469. }
  79470. if (this._slerping && this._yawRange > Math.PI) {
  79471. //are we going to be crossing into the min/max region?
  79472. var boneFwd = BoneLookController._tmpVecs[8];
  79473. boneFwd.copyFrom(BABYLON.Axis.Z);
  79474. if (this._transformYawPitch) {
  79475. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, this._transformYawPitchInv, boneFwd);
  79476. }
  79477. var boneRotMat = BoneLookController._tmpMats[4];
  79478. this._boneQuat.toRotationMatrix(boneRotMat);
  79479. this.mesh.getWorldMatrix().multiplyToRef(boneRotMat, boneRotMat);
  79480. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, boneRotMat, boneFwd);
  79481. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, spaceMatInv, boneFwd);
  79482. var boneYaw = Math.atan2(boneFwd.x, boneFwd.z);
  79483. var angBtwTar = this._getAngleBetween(boneYaw, yaw);
  79484. var angBtwMidYaw = this._getAngleBetween(boneYaw, this._midYawConstraint);
  79485. if (angBtwTar > angBtwMidYaw) {
  79486. if (xzlen == null) {
  79487. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  79488. }
  79489. var angBtwMax = this._getAngleBetween(boneYaw, this._maxYaw);
  79490. var angBtwMin = this._getAngleBetween(boneYaw, this._minYaw);
  79491. if (angBtwMin < angBtwMax) {
  79492. newYaw = boneYaw + Math.PI * .75;
  79493. localTarget.z = Math.cos(newYaw) * xzlen;
  79494. localTarget.x = Math.sin(newYaw) * xzlen;
  79495. }
  79496. else {
  79497. newYaw = boneYaw - Math.PI * .75;
  79498. localTarget.z = Math.cos(newYaw) * xzlen;
  79499. localTarget.x = Math.sin(newYaw) * xzlen;
  79500. }
  79501. }
  79502. }
  79503. if (yaw != newYaw) {
  79504. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  79505. localTarget.addInPlace(bonePos);
  79506. target = localTarget;
  79507. }
  79508. }
  79509. }
  79510. var zaxis = BoneLookController._tmpVecs[5];
  79511. var xaxis = BoneLookController._tmpVecs[6];
  79512. var yaxis = BoneLookController._tmpVecs[7];
  79513. var _tmpQuat = BoneLookController._tmpQuat;
  79514. target.subtractToRef(bonePos, zaxis);
  79515. zaxis.normalize();
  79516. BABYLON.Vector3.CrossToRef(upAxis, zaxis, xaxis);
  79517. xaxis.normalize();
  79518. BABYLON.Vector3.CrossToRef(zaxis, xaxis, yaxis);
  79519. yaxis.normalize();
  79520. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, _tmpMat1);
  79521. if (xaxis.x === 0 && xaxis.y === 0 && xaxis.z === 0) {
  79522. return;
  79523. }
  79524. if (yaxis.x === 0 && yaxis.y === 0 && yaxis.z === 0) {
  79525. return;
  79526. }
  79527. if (zaxis.x === 0 && zaxis.y === 0 && zaxis.z === 0) {
  79528. return;
  79529. }
  79530. if (this.adjustYaw || this.adjustPitch || this.adjustRoll) {
  79531. BABYLON.Matrix.RotationYawPitchRollToRef(this.adjustYaw, this.adjustPitch, this.adjustRoll, _tmpMat2);
  79532. _tmpMat2.multiplyToRef(_tmpMat1, _tmpMat1);
  79533. }
  79534. if (this.slerpAmount < 1) {
  79535. if (!this._slerping) {
  79536. this.bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, this.mesh, this._boneQuat);
  79537. }
  79538. if (this._transformYawPitch) {
  79539. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  79540. }
  79541. BABYLON.Quaternion.FromRotationMatrixToRef(_tmpMat1, _tmpQuat);
  79542. BABYLON.Quaternion.SlerpToRef(this._boneQuat, _tmpQuat, this.slerpAmount, this._boneQuat);
  79543. this.bone.setRotationQuaternion(this._boneQuat, BABYLON.Space.WORLD, this.mesh);
  79544. this._slerping = true;
  79545. }
  79546. else {
  79547. if (this._transformYawPitch) {
  79548. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  79549. }
  79550. this.bone.setRotationMatrix(_tmpMat1, BABYLON.Space.WORLD, this.mesh);
  79551. this._slerping = false;
  79552. }
  79553. };
  79554. BoneLookController.prototype._getAngleDiff = function (ang1, ang2) {
  79555. var angDiff = ang2 - ang1;
  79556. angDiff %= Math.PI * 2;
  79557. if (angDiff > Math.PI) {
  79558. angDiff -= Math.PI * 2;
  79559. }
  79560. else if (angDiff < -Math.PI) {
  79561. angDiff += Math.PI * 2;
  79562. }
  79563. return angDiff;
  79564. };
  79565. BoneLookController.prototype._getAngleBetween = function (ang1, ang2) {
  79566. ang1 %= (2 * Math.PI);
  79567. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  79568. ang2 %= (2 * Math.PI);
  79569. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  79570. var ab = 0;
  79571. if (ang1 < ang2) {
  79572. ab = ang2 - ang1;
  79573. }
  79574. else {
  79575. ab = ang1 - ang2;
  79576. }
  79577. if (ab > Math.PI) {
  79578. ab = Math.PI * 2 - ab;
  79579. }
  79580. return ab;
  79581. };
  79582. BoneLookController.prototype._isAngleBetween = function (ang, ang1, ang2) {
  79583. ang %= (2 * Math.PI);
  79584. ang = (ang < 0) ? ang + (2 * Math.PI) : ang;
  79585. ang1 %= (2 * Math.PI);
  79586. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  79587. ang2 %= (2 * Math.PI);
  79588. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  79589. if (ang1 < ang2) {
  79590. if (ang > ang1 && ang < ang2) {
  79591. return true;
  79592. }
  79593. }
  79594. else {
  79595. if (ang > ang2 && ang < ang1) {
  79596. return true;
  79597. }
  79598. }
  79599. return false;
  79600. };
  79601. BoneLookController._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  79602. BoneLookController._tmpQuat = BABYLON.Quaternion.Identity();
  79603. BoneLookController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  79604. return BoneLookController;
  79605. }());
  79606. BABYLON.BoneLookController = BoneLookController;
  79607. })(BABYLON || (BABYLON = {}));
  79608. //# sourceMappingURL=babylon.boneLookController.js.map
  79609. var BABYLON;
  79610. (function (BABYLON) {
  79611. /**
  79612. * Class used to handle skinning animations
  79613. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  79614. */
  79615. var Skeleton = /** @class */ (function () {
  79616. /**
  79617. * Creates a new skeleton
  79618. * @param name defines the skeleton name
  79619. * @param id defines the skeleton Id
  79620. * @param scene defines the hosting scene
  79621. */
  79622. function Skeleton(
  79623. /** defines the skeleton name */
  79624. name,
  79625. /** defines the skeleton Id */
  79626. id, scene) {
  79627. this.name = name;
  79628. this.id = id;
  79629. /**
  79630. * Gets the list of child bones
  79631. */
  79632. this.bones = new Array();
  79633. /**
  79634. * Gets a boolean indicating if the root matrix is provided by meshes or by the current skeleton (this is the default value)
  79635. */
  79636. this.needInitialSkinMatrix = false;
  79637. this._isDirty = true;
  79638. this._meshesWithPoseMatrix = new Array();
  79639. this._identity = BABYLON.Matrix.Identity();
  79640. this._ranges = {};
  79641. this._lastAbsoluteTransformsUpdateId = -1;
  79642. /**
  79643. * Specifies if the skeleton should be serialized
  79644. */
  79645. this.doNotSerialize = false;
  79646. this._animationPropertiesOverride = null;
  79647. // Events
  79648. /**
  79649. * An observable triggered before computing the skeleton's matrices
  79650. */
  79651. this.onBeforeComputeObservable = new BABYLON.Observable();
  79652. this.bones = [];
  79653. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  79654. scene.skeletons.push(this);
  79655. //make sure it will recalculate the matrix next time prepare is called.
  79656. this._isDirty = true;
  79657. }
  79658. Object.defineProperty(Skeleton.prototype, "animationPropertiesOverride", {
  79659. /**
  79660. * Gets or sets the animation properties override
  79661. */
  79662. get: function () {
  79663. if (!this._animationPropertiesOverride) {
  79664. return this._scene.animationPropertiesOverride;
  79665. }
  79666. return this._animationPropertiesOverride;
  79667. },
  79668. set: function (value) {
  79669. this._animationPropertiesOverride = value;
  79670. },
  79671. enumerable: true,
  79672. configurable: true
  79673. });
  79674. // Members
  79675. /**
  79676. * Gets the list of transform matrices to send to shaders (one matrix per bone)
  79677. * @param mesh defines the mesh to use to get the root matrix (if needInitialSkinMatrix === true)
  79678. * @returns a Float32Array containing matrices data
  79679. */
  79680. Skeleton.prototype.getTransformMatrices = function (mesh) {
  79681. if (this.needInitialSkinMatrix && mesh._bonesTransformMatrices) {
  79682. return mesh._bonesTransformMatrices;
  79683. }
  79684. if (!this._transformMatrices) {
  79685. this.prepare();
  79686. }
  79687. return this._transformMatrices;
  79688. };
  79689. /**
  79690. * Gets the current hosting scene
  79691. * @returns a scene object
  79692. */
  79693. Skeleton.prototype.getScene = function () {
  79694. return this._scene;
  79695. };
  79696. // Methods
  79697. /**
  79698. * Gets a string representing the current skeleton data
  79699. * @param fullDetails defines a boolean indicating if we want a verbose version
  79700. * @returns a string representing the current skeleton data
  79701. */
  79702. Skeleton.prototype.toString = function (fullDetails) {
  79703. var ret = "Name: " + this.name + ", nBones: " + this.bones.length;
  79704. ret += ", nAnimationRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  79705. if (fullDetails) {
  79706. ret += ", Ranges: {";
  79707. var first = true;
  79708. for (var name_1 in this._ranges) {
  79709. if (first) {
  79710. ret += ", ";
  79711. first = false;
  79712. }
  79713. ret += name_1;
  79714. }
  79715. ret += "}";
  79716. }
  79717. return ret;
  79718. };
  79719. /**
  79720. * Get bone's index searching by name
  79721. * @param name defines bone's name to search for
  79722. * @return the indice of the bone. Returns -1 if not found
  79723. */
  79724. Skeleton.prototype.getBoneIndexByName = function (name) {
  79725. for (var boneIndex = 0, cache = this.bones.length; boneIndex < cache; boneIndex++) {
  79726. if (this.bones[boneIndex].name === name) {
  79727. return boneIndex;
  79728. }
  79729. }
  79730. return -1;
  79731. };
  79732. /**
  79733. * Creater a new animation range
  79734. * @param name defines the name of the range
  79735. * @param from defines the start key
  79736. * @param to defines the end key
  79737. */
  79738. Skeleton.prototype.createAnimationRange = function (name, from, to) {
  79739. // check name not already in use
  79740. if (!this._ranges[name]) {
  79741. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  79742. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  79743. if (this.bones[i].animations[0]) {
  79744. this.bones[i].animations[0].createRange(name, from, to);
  79745. }
  79746. }
  79747. }
  79748. };
  79749. /**
  79750. * Delete a specific animation range
  79751. * @param name defines the name of the range
  79752. * @param deleteFrames defines if frames must be removed as well
  79753. */
  79754. Skeleton.prototype.deleteAnimationRange = function (name, deleteFrames) {
  79755. if (deleteFrames === void 0) { deleteFrames = true; }
  79756. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  79757. if (this.bones[i].animations[0]) {
  79758. this.bones[i].animations[0].deleteRange(name, deleteFrames);
  79759. }
  79760. }
  79761. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  79762. };
  79763. /**
  79764. * Gets a specific animation range
  79765. * @param name defines the name of the range to look for
  79766. * @returns the requested animation range or null if not found
  79767. */
  79768. Skeleton.prototype.getAnimationRange = function (name) {
  79769. return this._ranges[name];
  79770. };
  79771. /**
  79772. * Gets the list of all animation ranges defined on this skeleton
  79773. * @returns an array
  79774. */
  79775. Skeleton.prototype.getAnimationRanges = function () {
  79776. var animationRanges = [];
  79777. var name;
  79778. var i = 0;
  79779. for (name in this._ranges) {
  79780. animationRanges[i] = this._ranges[name];
  79781. i++;
  79782. }
  79783. return animationRanges;
  79784. };
  79785. /**
  79786. * Copy animation range from a source skeleton.
  79787. * This is not for a complete retargeting, only between very similar skeleton's with only possible bone length differences
  79788. * @param source defines the source skeleton
  79789. * @param name defines the name of the range to copy
  79790. * @param rescaleAsRequired defines if rescaling must be applied if required
  79791. * @returns true if operation was successful
  79792. */
  79793. Skeleton.prototype.copyAnimationRange = function (source, name, rescaleAsRequired) {
  79794. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  79795. if (this._ranges[name] || !source.getAnimationRange(name)) {
  79796. return false;
  79797. }
  79798. var ret = true;
  79799. var frameOffset = this._getHighestAnimationFrame() + 1;
  79800. // make a dictionary of source skeleton's bones, so exact same order or doublely nested loop is not required
  79801. var boneDict = {};
  79802. var sourceBones = source.bones;
  79803. var nBones;
  79804. var i;
  79805. for (i = 0, nBones = sourceBones.length; i < nBones; i++) {
  79806. boneDict[sourceBones[i].name] = sourceBones[i];
  79807. }
  79808. if (this.bones.length !== sourceBones.length) {
  79809. BABYLON.Tools.Warn("copyAnimationRange: this rig has " + this.bones.length + " bones, while source as " + sourceBones.length);
  79810. ret = false;
  79811. }
  79812. var skelDimensionsRatio = (rescaleAsRequired && this.dimensionsAtRest && source.dimensionsAtRest) ? this.dimensionsAtRest.divide(source.dimensionsAtRest) : null;
  79813. for (i = 0, nBones = this.bones.length; i < nBones; i++) {
  79814. var boneName = this.bones[i].name;
  79815. var sourceBone = boneDict[boneName];
  79816. if (sourceBone) {
  79817. ret = ret && this.bones[i].copyAnimationRange(sourceBone, name, frameOffset, rescaleAsRequired, skelDimensionsRatio);
  79818. }
  79819. else {
  79820. BABYLON.Tools.Warn("copyAnimationRange: not same rig, missing source bone " + boneName);
  79821. ret = false;
  79822. }
  79823. }
  79824. // do not call createAnimationRange(), since it also is done to bones, which was already done
  79825. var range = source.getAnimationRange(name);
  79826. if (range) {
  79827. this._ranges[name] = new BABYLON.AnimationRange(name, range.from + frameOffset, range.to + frameOffset);
  79828. }
  79829. return ret;
  79830. };
  79831. /**
  79832. * Forces the skeleton to go to rest pose
  79833. */
  79834. Skeleton.prototype.returnToRest = function () {
  79835. for (var index = 0; index < this.bones.length; index++) {
  79836. this.bones[index].returnToRest();
  79837. }
  79838. };
  79839. Skeleton.prototype._getHighestAnimationFrame = function () {
  79840. var ret = 0;
  79841. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  79842. if (this.bones[i].animations[0]) {
  79843. var highest = this.bones[i].animations[0].getHighestFrame();
  79844. if (ret < highest) {
  79845. ret = highest;
  79846. }
  79847. }
  79848. }
  79849. return ret;
  79850. };
  79851. /**
  79852. * Begin a specific animation range
  79853. * @param name defines the name of the range to start
  79854. * @param loop defines if looping must be turned on (false by default)
  79855. * @param speedRatio defines the speed ratio to apply (1 by default)
  79856. * @param onAnimationEnd defines a callback which will be called when animation will end
  79857. * @returns a new animatable
  79858. */
  79859. Skeleton.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  79860. var range = this.getAnimationRange(name);
  79861. if (!range) {
  79862. return null;
  79863. }
  79864. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  79865. };
  79866. /** @hidden */
  79867. Skeleton.prototype._markAsDirty = function () {
  79868. this._isDirty = true;
  79869. };
  79870. /** @hidden */
  79871. Skeleton.prototype._registerMeshWithPoseMatrix = function (mesh) {
  79872. this._meshesWithPoseMatrix.push(mesh);
  79873. };
  79874. /** @hidden */
  79875. Skeleton.prototype._unregisterMeshWithPoseMatrix = function (mesh) {
  79876. var index = this._meshesWithPoseMatrix.indexOf(mesh);
  79877. if (index > -1) {
  79878. this._meshesWithPoseMatrix.splice(index, 1);
  79879. }
  79880. };
  79881. /** @hidden */
  79882. Skeleton.prototype._computeTransformMatrices = function (targetMatrix, initialSkinMatrix) {
  79883. this.onBeforeComputeObservable.notifyObservers(this);
  79884. for (var index = 0; index < this.bones.length; index++) {
  79885. var bone = this.bones[index];
  79886. var parentBone = bone.getParent();
  79887. if (parentBone) {
  79888. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  79889. }
  79890. else {
  79891. if (initialSkinMatrix) {
  79892. bone.getLocalMatrix().multiplyToRef(initialSkinMatrix, bone.getWorldMatrix());
  79893. }
  79894. else {
  79895. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  79896. }
  79897. }
  79898. if (bone._index !== -1) {
  79899. var mappedIndex = bone._index === null ? index : bone._index;
  79900. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), targetMatrix, mappedIndex * 16);
  79901. }
  79902. }
  79903. this._identity.copyToArray(targetMatrix, this.bones.length * 16);
  79904. };
  79905. /**
  79906. * Build all resources required to render a skeleton
  79907. */
  79908. Skeleton.prototype.prepare = function () {
  79909. if (!this._isDirty) {
  79910. return;
  79911. }
  79912. if (this.needInitialSkinMatrix) {
  79913. for (var index = 0; index < this._meshesWithPoseMatrix.length; index++) {
  79914. var mesh = this._meshesWithPoseMatrix[index];
  79915. var poseMatrix = mesh.getPoseMatrix();
  79916. if (!mesh._bonesTransformMatrices || mesh._bonesTransformMatrices.length !== 16 * (this.bones.length + 1)) {
  79917. mesh._bonesTransformMatrices = new Float32Array(16 * (this.bones.length + 1));
  79918. }
  79919. if (this._synchronizedWithMesh !== mesh) {
  79920. this._synchronizedWithMesh = mesh;
  79921. // Prepare bones
  79922. for (var boneIndex = 0; boneIndex < this.bones.length; boneIndex++) {
  79923. var bone = this.bones[boneIndex];
  79924. if (!bone.getParent()) {
  79925. var matrix = bone.getBaseMatrix();
  79926. matrix.multiplyToRef(poseMatrix, BABYLON.Tmp.Matrix[1]);
  79927. bone._updateDifferenceMatrix(BABYLON.Tmp.Matrix[1]);
  79928. }
  79929. }
  79930. }
  79931. this._computeTransformMatrices(mesh._bonesTransformMatrices, poseMatrix);
  79932. }
  79933. }
  79934. else {
  79935. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  79936. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  79937. }
  79938. this._computeTransformMatrices(this._transformMatrices, null);
  79939. }
  79940. this._isDirty = false;
  79941. this._scene._activeBones.addCount(this.bones.length, false);
  79942. };
  79943. /**
  79944. * Gets the list of animatables currently running for this skeleton
  79945. * @returns an array of animatables
  79946. */
  79947. Skeleton.prototype.getAnimatables = function () {
  79948. if (!this._animatables || this._animatables.length !== this.bones.length) {
  79949. this._animatables = [];
  79950. for (var index = 0; index < this.bones.length; index++) {
  79951. this._animatables.push(this.bones[index]);
  79952. }
  79953. }
  79954. return this._animatables;
  79955. };
  79956. /**
  79957. * Clone the current skeleton
  79958. * @param name defines the name of the new skeleton
  79959. * @param id defines the id of the enw skeleton
  79960. * @returns the new skeleton
  79961. */
  79962. Skeleton.prototype.clone = function (name, id) {
  79963. var result = new Skeleton(name, id || name, this._scene);
  79964. result.needInitialSkinMatrix = this.needInitialSkinMatrix;
  79965. for (var index = 0; index < this.bones.length; index++) {
  79966. var source = this.bones[index];
  79967. var parentBone = null;
  79968. var parent_1 = source.getParent();
  79969. if (parent_1) {
  79970. var parentIndex = this.bones.indexOf(parent_1);
  79971. parentBone = result.bones[parentIndex];
  79972. }
  79973. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix().clone(), source.getRestPose().clone());
  79974. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  79975. }
  79976. if (this._ranges) {
  79977. result._ranges = {};
  79978. for (var rangeName in this._ranges) {
  79979. var range = this._ranges[rangeName];
  79980. if (range) {
  79981. result._ranges[rangeName] = range.clone();
  79982. }
  79983. }
  79984. }
  79985. this._isDirty = true;
  79986. return result;
  79987. };
  79988. /**
  79989. * Enable animation blending for this skeleton
  79990. * @param blendingSpeed defines the blending speed to apply
  79991. * @see http://doc.babylonjs.com/babylon101/animations#animation-blending
  79992. */
  79993. Skeleton.prototype.enableBlending = function (blendingSpeed) {
  79994. if (blendingSpeed === void 0) { blendingSpeed = 0.01; }
  79995. this.bones.forEach(function (bone) {
  79996. bone.animations.forEach(function (animation) {
  79997. animation.enableBlending = true;
  79998. animation.blendingSpeed = blendingSpeed;
  79999. });
  80000. });
  80001. };
  80002. /**
  80003. * Releases all resources associated with the current skeleton
  80004. */
  80005. Skeleton.prototype.dispose = function () {
  80006. this._meshesWithPoseMatrix = [];
  80007. // Animations
  80008. this.getScene().stopAnimation(this);
  80009. // Remove from scene
  80010. this.getScene().removeSkeleton(this);
  80011. };
  80012. /**
  80013. * Serialize the skeleton in a JSON object
  80014. * @returns a JSON object
  80015. */
  80016. Skeleton.prototype.serialize = function () {
  80017. var serializationObject = {};
  80018. serializationObject.name = this.name;
  80019. serializationObject.id = this.id;
  80020. if (this.dimensionsAtRest) {
  80021. serializationObject.dimensionsAtRest = this.dimensionsAtRest.asArray();
  80022. }
  80023. serializationObject.bones = [];
  80024. serializationObject.needInitialSkinMatrix = this.needInitialSkinMatrix;
  80025. for (var index = 0; index < this.bones.length; index++) {
  80026. var bone = this.bones[index];
  80027. var parent_2 = bone.getParent();
  80028. var serializedBone = {
  80029. parentBoneIndex: parent_2 ? this.bones.indexOf(parent_2) : -1,
  80030. name: bone.name,
  80031. matrix: bone.getBaseMatrix().toArray(),
  80032. rest: bone.getRestPose().toArray()
  80033. };
  80034. serializationObject.bones.push(serializedBone);
  80035. if (bone.length) {
  80036. serializedBone.length = bone.length;
  80037. }
  80038. if (bone.metadata) {
  80039. serializedBone.metadata = bone.metadata;
  80040. }
  80041. if (bone.animations && bone.animations.length > 0) {
  80042. serializedBone.animation = bone.animations[0].serialize();
  80043. }
  80044. serializationObject.ranges = [];
  80045. for (var name in this._ranges) {
  80046. var source = this._ranges[name];
  80047. if (!source) {
  80048. continue;
  80049. }
  80050. var range = {};
  80051. range.name = name;
  80052. range.from = source.from;
  80053. range.to = source.to;
  80054. serializationObject.ranges.push(range);
  80055. }
  80056. }
  80057. return serializationObject;
  80058. };
  80059. /**
  80060. * Creates a new skeleton from serialized data
  80061. * @param parsedSkeleton defines the serialized data
  80062. * @param scene defines the hosting scene
  80063. * @returns a new skeleton
  80064. */
  80065. Skeleton.Parse = function (parsedSkeleton, scene) {
  80066. var skeleton = new Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  80067. if (parsedSkeleton.dimensionsAtRest) {
  80068. skeleton.dimensionsAtRest = BABYLON.Vector3.FromArray(parsedSkeleton.dimensionsAtRest);
  80069. }
  80070. skeleton.needInitialSkinMatrix = parsedSkeleton.needInitialSkinMatrix;
  80071. var index;
  80072. for (index = 0; index < parsedSkeleton.bones.length; index++) {
  80073. var parsedBone = parsedSkeleton.bones[index];
  80074. var parentBone = null;
  80075. if (parsedBone.parentBoneIndex > -1) {
  80076. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  80077. }
  80078. var rest = parsedBone.rest ? BABYLON.Matrix.FromArray(parsedBone.rest) : null;
  80079. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix), rest);
  80080. if (parsedBone.length) {
  80081. bone.length = parsedBone.length;
  80082. }
  80083. if (parsedBone.metadata) {
  80084. bone.metadata = parsedBone.metadata;
  80085. }
  80086. if (parsedBone.animation) {
  80087. bone.animations.push(BABYLON.Animation.Parse(parsedBone.animation));
  80088. }
  80089. }
  80090. // placed after bones, so createAnimationRange can cascade down
  80091. if (parsedSkeleton.ranges) {
  80092. for (index = 0; index < parsedSkeleton.ranges.length; index++) {
  80093. var data = parsedSkeleton.ranges[index];
  80094. skeleton.createAnimationRange(data.name, data.from, data.to);
  80095. }
  80096. }
  80097. return skeleton;
  80098. };
  80099. /**
  80100. * Compute all node absolute transforms
  80101. * @param forceUpdate defines if computation must be done even if cache is up to date
  80102. */
  80103. Skeleton.prototype.computeAbsoluteTransforms = function (forceUpdate) {
  80104. if (forceUpdate === void 0) { forceUpdate = false; }
  80105. var renderId = this._scene.getRenderId();
  80106. if (this._lastAbsoluteTransformsUpdateId != renderId || forceUpdate) {
  80107. this.bones[0].computeAbsoluteTransforms();
  80108. this._lastAbsoluteTransformsUpdateId = renderId;
  80109. }
  80110. };
  80111. /**
  80112. * Gets the root pose matrix
  80113. * @returns a matrix
  80114. */
  80115. Skeleton.prototype.getPoseMatrix = function () {
  80116. var poseMatrix = null;
  80117. if (this._meshesWithPoseMatrix.length > 0) {
  80118. poseMatrix = this._meshesWithPoseMatrix[0].getPoseMatrix();
  80119. }
  80120. return poseMatrix;
  80121. };
  80122. /**
  80123. * Sorts bones per internal index
  80124. */
  80125. Skeleton.prototype.sortBones = function () {
  80126. var bones = new Array();
  80127. var visited = new Array(this.bones.length);
  80128. for (var index = 0; index < this.bones.length; index++) {
  80129. this._sortBones(index, bones, visited);
  80130. }
  80131. this.bones = bones;
  80132. };
  80133. Skeleton.prototype._sortBones = function (index, bones, visited) {
  80134. if (visited[index]) {
  80135. return;
  80136. }
  80137. visited[index] = true;
  80138. var bone = this.bones[index];
  80139. if (bone._index === undefined) {
  80140. bone._index = index;
  80141. }
  80142. var parentBone = bone.getParent();
  80143. if (parentBone) {
  80144. this._sortBones(this.bones.indexOf(parentBone), bones, visited);
  80145. }
  80146. bones.push(bone);
  80147. };
  80148. return Skeleton;
  80149. }());
  80150. BABYLON.Skeleton = Skeleton;
  80151. })(BABYLON || (BABYLON = {}));
  80152. //# sourceMappingURL=babylon.skeleton.js.map
  80153. var BABYLON;
  80154. (function (BABYLON) {
  80155. var SphericalPolynomial = /** @class */ (function () {
  80156. function SphericalPolynomial() {
  80157. this.x = BABYLON.Vector3.Zero();
  80158. this.y = BABYLON.Vector3.Zero();
  80159. this.z = BABYLON.Vector3.Zero();
  80160. this.xx = BABYLON.Vector3.Zero();
  80161. this.yy = BABYLON.Vector3.Zero();
  80162. this.zz = BABYLON.Vector3.Zero();
  80163. this.xy = BABYLON.Vector3.Zero();
  80164. this.yz = BABYLON.Vector3.Zero();
  80165. this.zx = BABYLON.Vector3.Zero();
  80166. }
  80167. SphericalPolynomial.prototype.addAmbient = function (color) {
  80168. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  80169. this.xx = this.xx.add(colorVector);
  80170. this.yy = this.yy.add(colorVector);
  80171. this.zz = this.zz.add(colorVector);
  80172. };
  80173. SphericalPolynomial.getSphericalPolynomialFromHarmonics = function (harmonics) {
  80174. var result = new SphericalPolynomial();
  80175. result.x = harmonics.L11.scale(1.02333);
  80176. result.y = harmonics.L1_1.scale(1.02333);
  80177. result.z = harmonics.L10.scale(1.02333);
  80178. result.xx = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).add(harmonics.L22.scale(0.429043));
  80179. result.yy = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).subtract(harmonics.L22.scale(0.429043));
  80180. result.zz = harmonics.L00.scale(0.886277).add(harmonics.L20.scale(0.495417));
  80181. result.yz = harmonics.L2_1.scale(0.858086);
  80182. result.zx = harmonics.L21.scale(0.858086);
  80183. result.xy = harmonics.L2_2.scale(0.858086);
  80184. result.scale(1.0 / Math.PI);
  80185. return result;
  80186. };
  80187. SphericalPolynomial.prototype.scale = function (scale) {
  80188. this.x = this.x.scale(scale);
  80189. this.y = this.y.scale(scale);
  80190. this.z = this.z.scale(scale);
  80191. this.xx = this.xx.scale(scale);
  80192. this.yy = this.yy.scale(scale);
  80193. this.zz = this.zz.scale(scale);
  80194. this.yz = this.yz.scale(scale);
  80195. this.zx = this.zx.scale(scale);
  80196. this.xy = this.xy.scale(scale);
  80197. };
  80198. return SphericalPolynomial;
  80199. }());
  80200. BABYLON.SphericalPolynomial = SphericalPolynomial;
  80201. var SphericalHarmonics = /** @class */ (function () {
  80202. function SphericalHarmonics() {
  80203. this.L00 = BABYLON.Vector3.Zero();
  80204. this.L1_1 = BABYLON.Vector3.Zero();
  80205. this.L10 = BABYLON.Vector3.Zero();
  80206. this.L11 = BABYLON.Vector3.Zero();
  80207. this.L2_2 = BABYLON.Vector3.Zero();
  80208. this.L2_1 = BABYLON.Vector3.Zero();
  80209. this.L20 = BABYLON.Vector3.Zero();
  80210. this.L21 = BABYLON.Vector3.Zero();
  80211. this.L22 = BABYLON.Vector3.Zero();
  80212. }
  80213. SphericalHarmonics.prototype.addLight = function (direction, color, deltaSolidAngle) {
  80214. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  80215. var c = colorVector.scale(deltaSolidAngle);
  80216. this.L00 = this.L00.add(c.scale(0.282095));
  80217. this.L1_1 = this.L1_1.add(c.scale(0.488603 * direction.y));
  80218. this.L10 = this.L10.add(c.scale(0.488603 * direction.z));
  80219. this.L11 = this.L11.add(c.scale(0.488603 * direction.x));
  80220. this.L2_2 = this.L2_2.add(c.scale(1.092548 * direction.x * direction.y));
  80221. this.L2_1 = this.L2_1.add(c.scale(1.092548 * direction.y * direction.z));
  80222. this.L21 = this.L21.add(c.scale(1.092548 * direction.x * direction.z));
  80223. this.L20 = this.L20.add(c.scale(0.315392 * (3.0 * direction.z * direction.z - 1.0)));
  80224. this.L22 = this.L22.add(c.scale(0.546274 * (direction.x * direction.x - direction.y * direction.y)));
  80225. };
  80226. SphericalHarmonics.prototype.scale = function (scale) {
  80227. this.L00 = this.L00.scale(scale);
  80228. this.L1_1 = this.L1_1.scale(scale);
  80229. this.L10 = this.L10.scale(scale);
  80230. this.L11 = this.L11.scale(scale);
  80231. this.L2_2 = this.L2_2.scale(scale);
  80232. this.L2_1 = this.L2_1.scale(scale);
  80233. this.L20 = this.L20.scale(scale);
  80234. this.L21 = this.L21.scale(scale);
  80235. this.L22 = this.L22.scale(scale);
  80236. };
  80237. SphericalHarmonics.prototype.convertIncidentRadianceToIrradiance = function () {
  80238. // Convert from incident radiance (Li) to irradiance (E) by applying convolution with the cosine-weighted hemisphere.
  80239. //
  80240. // E_lm = A_l * L_lm
  80241. //
  80242. // In spherical harmonics this convolution amounts to scaling factors for each frequency band.
  80243. // This corresponds to equation 5 in "An Efficient Representation for Irradiance Environment Maps", where
  80244. // the scaling factors are given in equation 9.
  80245. // Constant (Band 0)
  80246. this.L00 = this.L00.scale(3.141593);
  80247. // Linear (Band 1)
  80248. this.L1_1 = this.L1_1.scale(2.094395);
  80249. this.L10 = this.L10.scale(2.094395);
  80250. this.L11 = this.L11.scale(2.094395);
  80251. // Quadratic (Band 2)
  80252. this.L2_2 = this.L2_2.scale(0.785398);
  80253. this.L2_1 = this.L2_1.scale(0.785398);
  80254. this.L20 = this.L20.scale(0.785398);
  80255. this.L21 = this.L21.scale(0.785398);
  80256. this.L22 = this.L22.scale(0.785398);
  80257. };
  80258. SphericalHarmonics.prototype.convertIrradianceToLambertianRadiance = function () {
  80259. // Convert from irradiance to outgoing radiance for Lambertian BDRF, suitable for efficient shader evaluation.
  80260. // L = (1/pi) * E * rho
  80261. //
  80262. // This is done by an additional scale by 1/pi, so is a fairly trivial operation but important conceptually.
  80263. this.scale(1.0 / Math.PI);
  80264. // The resultant SH now represents outgoing radiance, so includes the Lambert 1/pi normalisation factor but without albedo (rho) applied
  80265. // (The pixel shader must apply albedo after texture fetches, etc).
  80266. };
  80267. SphericalHarmonics.getsphericalHarmonicsFromPolynomial = function (polynomial) {
  80268. var result = new SphericalHarmonics();
  80269. result.L00 = polynomial.xx.scale(0.376127).add(polynomial.yy.scale(0.376127)).add(polynomial.zz.scale(0.376126));
  80270. result.L1_1 = polynomial.y.scale(0.977204);
  80271. result.L10 = polynomial.z.scale(0.977204);
  80272. result.L11 = polynomial.x.scale(0.977204);
  80273. result.L2_2 = polynomial.xy.scale(1.16538);
  80274. result.L2_1 = polynomial.yz.scale(1.16538);
  80275. result.L20 = polynomial.zz.scale(1.34567).subtract(polynomial.xx.scale(0.672834)).subtract(polynomial.yy.scale(0.672834));
  80276. result.L21 = polynomial.zx.scale(1.16538);
  80277. result.L22 = polynomial.xx.scale(1.16538).subtract(polynomial.yy.scale(1.16538));
  80278. result.scale(Math.PI);
  80279. return result;
  80280. };
  80281. return SphericalHarmonics;
  80282. }());
  80283. BABYLON.SphericalHarmonics = SphericalHarmonics;
  80284. })(BABYLON || (BABYLON = {}));
  80285. //# sourceMappingURL=babylon.sphericalPolynomial.js.map
  80286. var BABYLON;
  80287. (function (BABYLON) {
  80288. var FileFaceOrientation = /** @class */ (function () {
  80289. function FileFaceOrientation(name, worldAxisForNormal, worldAxisForFileX, worldAxisForFileY) {
  80290. this.name = name;
  80291. this.worldAxisForNormal = worldAxisForNormal;
  80292. this.worldAxisForFileX = worldAxisForFileX;
  80293. this.worldAxisForFileY = worldAxisForFileY;
  80294. }
  80295. return FileFaceOrientation;
  80296. }());
  80297. ;
  80298. /**
  80299. * Helper class dealing with the extraction of spherical polynomial dataArray
  80300. * from a cube map.
  80301. */
  80302. var CubeMapToSphericalPolynomialTools = /** @class */ (function () {
  80303. function CubeMapToSphericalPolynomialTools() {
  80304. }
  80305. /**
  80306. * Converts a texture to the according Spherical Polynomial data.
  80307. * This extracts the first 3 orders only as they are the only one used in the lighting.
  80308. *
  80309. * @param texture The texture to extract the information from.
  80310. * @return The Spherical Polynomial data.
  80311. */
  80312. CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial = function (texture) {
  80313. if (!texture.isCube) {
  80314. // Only supports cube Textures currently.
  80315. return null;
  80316. }
  80317. var size = texture.getSize().width;
  80318. var right = texture.readPixels(0);
  80319. var left = texture.readPixels(1);
  80320. var up;
  80321. var down;
  80322. if (texture.isRenderTarget) {
  80323. up = texture.readPixels(3);
  80324. down = texture.readPixels(2);
  80325. }
  80326. else {
  80327. up = texture.readPixels(2);
  80328. down = texture.readPixels(3);
  80329. }
  80330. var front = texture.readPixels(4);
  80331. var back = texture.readPixels(5);
  80332. var gammaSpace = texture.gammaSpace;
  80333. // Always read as RGBA.
  80334. var format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  80335. var type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  80336. if (texture.textureType && texture.textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  80337. type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  80338. }
  80339. var cubeInfo = {
  80340. size: size,
  80341. right: right,
  80342. left: left,
  80343. up: up,
  80344. down: down,
  80345. front: front,
  80346. back: back,
  80347. format: format,
  80348. type: type,
  80349. gammaSpace: gammaSpace,
  80350. };
  80351. return this.ConvertCubeMapToSphericalPolynomial(cubeInfo);
  80352. };
  80353. /**
  80354. * Converts a cubemap to the according Spherical Polynomial data.
  80355. * This extracts the first 3 orders only as they are the only one used in the lighting.
  80356. *
  80357. * @param cubeInfo The Cube map to extract the information from.
  80358. * @return The Spherical Polynomial data.
  80359. */
  80360. CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial = function (cubeInfo) {
  80361. var sphericalHarmonics = new BABYLON.SphericalHarmonics();
  80362. var totalSolidAngle = 0.0;
  80363. // The (u,v) range is [-1,+1], so the distance between each texel is 2/Size.
  80364. var du = 2.0 / cubeInfo.size;
  80365. var dv = du;
  80366. // The (u,v) of the first texel is half a texel from the corner (-1,-1).
  80367. var minUV = du * 0.5 - 1.0;
  80368. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  80369. var fileFace = this.FileFaces[faceIndex];
  80370. var dataArray = cubeInfo[fileFace.name];
  80371. var v = minUV;
  80372. // TODO: we could perform the summation directly into a SphericalPolynomial (SP), which is more efficient than SphericalHarmonic (SH).
  80373. // This is possible because during the summation we do not need the SH-specific properties, e.g. orthogonality.
  80374. // Because SP is still linear, so summation is fine in that basis.
  80375. var stride = cubeInfo.format === BABYLON.Engine.TEXTUREFORMAT_RGBA ? 4 : 3;
  80376. for (var y = 0; y < cubeInfo.size; y++) {
  80377. var u = minUV;
  80378. for (var x = 0; x < cubeInfo.size; x++) {
  80379. // World direction (not normalised)
  80380. var worldDirection = fileFace.worldAxisForFileX.scale(u).add(fileFace.worldAxisForFileY.scale(v)).add(fileFace.worldAxisForNormal);
  80381. worldDirection.normalize();
  80382. var deltaSolidAngle = Math.pow(1.0 + u * u + v * v, -3.0 / 2.0);
  80383. var r = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 0];
  80384. var g = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 1];
  80385. var b = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 2];
  80386. // Handle Integer types.
  80387. if (cubeInfo.type === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  80388. r /= 255;
  80389. g /= 255;
  80390. b /= 255;
  80391. }
  80392. // Handle Gamma space textures.
  80393. if (cubeInfo.gammaSpace) {
  80394. r = Math.pow(BABYLON.Scalar.Clamp(r), BABYLON.ToLinearSpace);
  80395. g = Math.pow(BABYLON.Scalar.Clamp(g), BABYLON.ToLinearSpace);
  80396. b = Math.pow(BABYLON.Scalar.Clamp(b), BABYLON.ToLinearSpace);
  80397. }
  80398. var color = new BABYLON.Color3(r, g, b);
  80399. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  80400. totalSolidAngle += deltaSolidAngle;
  80401. u += du;
  80402. }
  80403. v += dv;
  80404. }
  80405. }
  80406. // Solid angle for entire sphere is 4*pi
  80407. var sphereSolidAngle = 4.0 * Math.PI;
  80408. // Adjust the solid angle to allow for how many faces we processed.
  80409. var facesProcessed = 6.0;
  80410. var expectedSolidAngle = sphereSolidAngle * facesProcessed / 6.0;
  80411. // Adjust the harmonics so that the accumulated solid angle matches the expected solid angle.
  80412. // This is needed because the numerical integration over the cube uses a
  80413. // small angle approximation of solid angle for each texel (see deltaSolidAngle),
  80414. // and also to compensate for accumulative error due to float precision in the summation.
  80415. var correctionFactor = expectedSolidAngle / totalSolidAngle;
  80416. sphericalHarmonics.scale(correctionFactor);
  80417. sphericalHarmonics.convertIncidentRadianceToIrradiance();
  80418. sphericalHarmonics.convertIrradianceToLambertianRadiance();
  80419. return BABYLON.SphericalPolynomial.getSphericalPolynomialFromHarmonics(sphericalHarmonics);
  80420. };
  80421. CubeMapToSphericalPolynomialTools.FileFaces = [
  80422. new FileFaceOrientation("right", new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(0, -1, 0)),
  80423. new FileFaceOrientation("left", new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(0, -1, 0)),
  80424. new FileFaceOrientation("up", new BABYLON.Vector3(0, 1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, 1)),
  80425. new FileFaceOrientation("down", new BABYLON.Vector3(0, -1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1)),
  80426. new FileFaceOrientation("front", new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, -1, 0)),
  80427. new FileFaceOrientation("back", new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, -1, 0)) // -Z bottom
  80428. ];
  80429. return CubeMapToSphericalPolynomialTools;
  80430. }());
  80431. BABYLON.CubeMapToSphericalPolynomialTools = CubeMapToSphericalPolynomialTools;
  80432. })(BABYLON || (BABYLON = {}));
  80433. //# sourceMappingURL=babylon.cubemapToSphericalPolynomial.js.map
  80434. var BABYLON;
  80435. (function (BABYLON) {
  80436. /**
  80437. * Helper class usefull to convert panorama picture to their cubemap representation in 6 faces.
  80438. */
  80439. var PanoramaToCubeMapTools = /** @class */ (function () {
  80440. function PanoramaToCubeMapTools() {
  80441. }
  80442. /**
  80443. * Converts a panorma stored in RGB right to left up to down format into a cubemap (6 faces).
  80444. *
  80445. * @param float32Array The source data.
  80446. * @param inputWidth The width of the input panorama.
  80447. * @param inputhHeight The height of the input panorama.
  80448. * @param size The willing size of the generated cubemap (each faces will be size * size pixels)
  80449. * @return The cubemap data
  80450. */
  80451. PanoramaToCubeMapTools.ConvertPanoramaToCubemap = function (float32Array, inputWidth, inputHeight, size) {
  80452. if (!float32Array) {
  80453. throw "ConvertPanoramaToCubemap: input cannot be null";
  80454. }
  80455. if (float32Array.length != inputWidth * inputHeight * 3) {
  80456. throw "ConvertPanoramaToCubemap: input size is wrong";
  80457. }
  80458. var textureFront = this.CreateCubemapTexture(size, this.FACE_FRONT, float32Array, inputWidth, inputHeight);
  80459. var textureBack = this.CreateCubemapTexture(size, this.FACE_BACK, float32Array, inputWidth, inputHeight);
  80460. var textureLeft = this.CreateCubemapTexture(size, this.FACE_LEFT, float32Array, inputWidth, inputHeight);
  80461. var textureRight = this.CreateCubemapTexture(size, this.FACE_RIGHT, float32Array, inputWidth, inputHeight);
  80462. var textureUp = this.CreateCubemapTexture(size, this.FACE_UP, float32Array, inputWidth, inputHeight);
  80463. var textureDown = this.CreateCubemapTexture(size, this.FACE_DOWN, float32Array, inputWidth, inputHeight);
  80464. return {
  80465. front: textureFront,
  80466. back: textureBack,
  80467. left: textureLeft,
  80468. right: textureRight,
  80469. up: textureUp,
  80470. down: textureDown,
  80471. size: size,
  80472. type: BABYLON.Engine.TEXTURETYPE_FLOAT,
  80473. format: BABYLON.Engine.TEXTUREFORMAT_RGB,
  80474. gammaSpace: false,
  80475. };
  80476. };
  80477. PanoramaToCubeMapTools.CreateCubemapTexture = function (texSize, faceData, float32Array, inputWidth, inputHeight) {
  80478. var buffer = new ArrayBuffer(texSize * texSize * 4 * 3);
  80479. var textureArray = new Float32Array(buffer);
  80480. var rotDX1 = faceData[1].subtract(faceData[0]).scale(1 / texSize);
  80481. var rotDX2 = faceData[3].subtract(faceData[2]).scale(1 / texSize);
  80482. var dy = 1 / texSize;
  80483. var fy = 0;
  80484. for (var y = 0; y < texSize; y++) {
  80485. var xv1 = faceData[0];
  80486. var xv2 = faceData[2];
  80487. for (var x = 0; x < texSize; x++) {
  80488. var v = xv2.subtract(xv1).scale(fy).add(xv1);
  80489. v.normalize();
  80490. var color = this.CalcProjectionSpherical(v, float32Array, inputWidth, inputHeight);
  80491. // 3 channels per pixels
  80492. textureArray[y * texSize * 3 + (x * 3) + 0] = color.r;
  80493. textureArray[y * texSize * 3 + (x * 3) + 1] = color.g;
  80494. textureArray[y * texSize * 3 + (x * 3) + 2] = color.b;
  80495. xv1 = xv1.add(rotDX1);
  80496. xv2 = xv2.add(rotDX2);
  80497. }
  80498. fy += dy;
  80499. }
  80500. return textureArray;
  80501. };
  80502. PanoramaToCubeMapTools.CalcProjectionSpherical = function (vDir, float32Array, inputWidth, inputHeight) {
  80503. var theta = Math.atan2(vDir.z, vDir.x);
  80504. var phi = Math.acos(vDir.y);
  80505. while (theta < -Math.PI)
  80506. theta += 2 * Math.PI;
  80507. while (theta > Math.PI)
  80508. theta -= 2 * Math.PI;
  80509. var dx = theta / Math.PI;
  80510. var dy = phi / Math.PI;
  80511. // recenter.
  80512. dx = dx * 0.5 + 0.5;
  80513. var px = Math.round(dx * inputWidth);
  80514. if (px < 0)
  80515. px = 0;
  80516. else if (px >= inputWidth)
  80517. px = inputWidth - 1;
  80518. var py = Math.round(dy * inputHeight);
  80519. if (py < 0)
  80520. py = 0;
  80521. else if (py >= inputHeight)
  80522. py = inputHeight - 1;
  80523. var inputY = (inputHeight - py - 1);
  80524. var r = float32Array[inputY * inputWidth * 3 + (px * 3) + 0];
  80525. var g = float32Array[inputY * inputWidth * 3 + (px * 3) + 1];
  80526. var b = float32Array[inputY * inputWidth * 3 + (px * 3) + 2];
  80527. return {
  80528. r: r,
  80529. g: g,
  80530. b: b
  80531. };
  80532. };
  80533. PanoramaToCubeMapTools.FACE_FRONT = [
  80534. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  80535. new BABYLON.Vector3(1.0, -1.0, -1.0),
  80536. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  80537. new BABYLON.Vector3(1.0, 1.0, -1.0)
  80538. ];
  80539. PanoramaToCubeMapTools.FACE_BACK = [
  80540. new BABYLON.Vector3(1.0, -1.0, 1.0),
  80541. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  80542. new BABYLON.Vector3(1.0, 1.0, 1.0),
  80543. new BABYLON.Vector3(-1.0, 1.0, 1.0)
  80544. ];
  80545. PanoramaToCubeMapTools.FACE_RIGHT = [
  80546. new BABYLON.Vector3(1.0, -1.0, -1.0),
  80547. new BABYLON.Vector3(1.0, -1.0, 1.0),
  80548. new BABYLON.Vector3(1.0, 1.0, -1.0),
  80549. new BABYLON.Vector3(1.0, 1.0, 1.0)
  80550. ];
  80551. PanoramaToCubeMapTools.FACE_LEFT = [
  80552. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  80553. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  80554. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  80555. new BABYLON.Vector3(-1.0, 1.0, -1.0)
  80556. ];
  80557. PanoramaToCubeMapTools.FACE_DOWN = [
  80558. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  80559. new BABYLON.Vector3(1.0, 1.0, -1.0),
  80560. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  80561. new BABYLON.Vector3(1.0, 1.0, 1.0)
  80562. ];
  80563. PanoramaToCubeMapTools.FACE_UP = [
  80564. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  80565. new BABYLON.Vector3(1.0, -1.0, 1.0),
  80566. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  80567. new BABYLON.Vector3(1.0, -1.0, -1.0)
  80568. ];
  80569. return PanoramaToCubeMapTools;
  80570. }());
  80571. BABYLON.PanoramaToCubeMapTools = PanoramaToCubeMapTools;
  80572. })(BABYLON || (BABYLON = {}));
  80573. //# sourceMappingURL=babylon.panoramaToCubemap.js.map
  80574. var BABYLON;
  80575. (function (BABYLON) {
  80576. ;
  80577. /**
  80578. * This groups tools to convert HDR texture to native colors array.
  80579. */
  80580. var HDRTools = /** @class */ (function () {
  80581. function HDRTools() {
  80582. }
  80583. HDRTools.Ldexp = function (mantissa, exponent) {
  80584. if (exponent > 1023) {
  80585. return mantissa * Math.pow(2, 1023) * Math.pow(2, exponent - 1023);
  80586. }
  80587. if (exponent < -1074) {
  80588. return mantissa * Math.pow(2, -1074) * Math.pow(2, exponent + 1074);
  80589. }
  80590. return mantissa * Math.pow(2, exponent);
  80591. };
  80592. HDRTools.Rgbe2float = function (float32array, red, green, blue, exponent, index) {
  80593. if (exponent > 0) { /*nonzero pixel*/
  80594. exponent = this.Ldexp(1.0, exponent - (128 + 8));
  80595. float32array[index + 0] = red * exponent;
  80596. float32array[index + 1] = green * exponent;
  80597. float32array[index + 2] = blue * exponent;
  80598. }
  80599. else {
  80600. float32array[index + 0] = 0;
  80601. float32array[index + 1] = 0;
  80602. float32array[index + 2] = 0;
  80603. }
  80604. };
  80605. HDRTools.readStringLine = function (uint8array, startIndex) {
  80606. var line = "";
  80607. var character = "";
  80608. for (var i = startIndex; i < uint8array.length - startIndex; i++) {
  80609. character = String.fromCharCode(uint8array[i]);
  80610. if (character == "\n") {
  80611. break;
  80612. }
  80613. line += character;
  80614. }
  80615. return line;
  80616. };
  80617. /**
  80618. * Reads header information from an RGBE texture stored in a native array.
  80619. * More information on this format are available here:
  80620. * https://en.wikipedia.org/wiki/RGBE_image_format
  80621. *
  80622. * @param uint8array The binary file stored in native array.
  80623. * @return The header information.
  80624. */
  80625. HDRTools.RGBE_ReadHeader = function (uint8array) {
  80626. var height = 0;
  80627. var width = 0;
  80628. var line = this.readStringLine(uint8array, 0);
  80629. if (line[0] != '#' || line[1] != '?') {
  80630. throw "Bad HDR Format.";
  80631. }
  80632. var endOfHeader = false;
  80633. var findFormat = false;
  80634. var lineIndex = 0;
  80635. do {
  80636. lineIndex += (line.length + 1);
  80637. line = this.readStringLine(uint8array, lineIndex);
  80638. if (line == "FORMAT=32-bit_rle_rgbe") {
  80639. findFormat = true;
  80640. }
  80641. else if (line.length == 0) {
  80642. endOfHeader = true;
  80643. }
  80644. } while (!endOfHeader);
  80645. if (!findFormat) {
  80646. throw "HDR Bad header format, unsupported FORMAT";
  80647. }
  80648. lineIndex += (line.length + 1);
  80649. line = this.readStringLine(uint8array, lineIndex);
  80650. var sizeRegexp = /^\-Y (.*) \+X (.*)$/g;
  80651. var match = sizeRegexp.exec(line);
  80652. // TODO. Support +Y and -X if needed.
  80653. if (!match || match.length < 3) {
  80654. throw "HDR Bad header format, no size";
  80655. }
  80656. width = parseInt(match[2]);
  80657. height = parseInt(match[1]);
  80658. if (width < 8 || width > 0x7fff) {
  80659. throw "HDR Bad header format, unsupported size";
  80660. }
  80661. lineIndex += (line.length + 1);
  80662. return {
  80663. height: height,
  80664. width: width,
  80665. dataPosition: lineIndex
  80666. };
  80667. };
  80668. /**
  80669. * Returns the cubemap information (each faces texture data) extracted from an RGBE texture.
  80670. * This RGBE texture needs to store the information as a panorama.
  80671. *
  80672. * More information on this format are available here:
  80673. * https://en.wikipedia.org/wiki/RGBE_image_format
  80674. *
  80675. * @param buffer The binary file stored in an array buffer.
  80676. * @param size The expected size of the extracted cubemap.
  80677. * @return The Cube Map information.
  80678. */
  80679. HDRTools.GetCubeMapTextureData = function (buffer, size) {
  80680. var uint8array = new Uint8Array(buffer);
  80681. var hdrInfo = this.RGBE_ReadHeader(uint8array);
  80682. var data = this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  80683. var cubeMapData = BABYLON.PanoramaToCubeMapTools.ConvertPanoramaToCubemap(data, hdrInfo.width, hdrInfo.height, size);
  80684. return cubeMapData;
  80685. };
  80686. /**
  80687. * Returns the pixels data extracted from an RGBE texture.
  80688. * This pixels will be stored left to right up to down in the R G B order in one array.
  80689. *
  80690. * More information on this format are available here:
  80691. * https://en.wikipedia.org/wiki/RGBE_image_format
  80692. *
  80693. * @param uint8array The binary file stored in an array buffer.
  80694. * @param hdrInfo The header information of the file.
  80695. * @return The pixels data in RGB right to left up to down order.
  80696. */
  80697. HDRTools.RGBE_ReadPixels = function (uint8array, hdrInfo) {
  80698. // Keep for multi format supports.
  80699. return this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  80700. };
  80701. HDRTools.RGBE_ReadPixels_RLE = function (uint8array, hdrInfo) {
  80702. var num_scanlines = hdrInfo.height;
  80703. var scanline_width = hdrInfo.width;
  80704. var a, b, c, d, count;
  80705. var dataIndex = hdrInfo.dataPosition;
  80706. var index = 0, endIndex = 0, i = 0;
  80707. var scanLineArrayBuffer = new ArrayBuffer(scanline_width * 4); // four channel R G B E
  80708. var scanLineArray = new Uint8Array(scanLineArrayBuffer);
  80709. // 3 channels of 4 bytes per pixel in float.
  80710. var resultBuffer = new ArrayBuffer(hdrInfo.width * hdrInfo.height * 4 * 3);
  80711. var resultArray = new Float32Array(resultBuffer);
  80712. // read in each successive scanline
  80713. while (num_scanlines > 0) {
  80714. a = uint8array[dataIndex++];
  80715. b = uint8array[dataIndex++];
  80716. c = uint8array[dataIndex++];
  80717. d = uint8array[dataIndex++];
  80718. if (a != 2 || b != 2 || (c & 0x80)) {
  80719. // this file is not run length encoded
  80720. throw "HDR Bad header format, not RLE";
  80721. }
  80722. if (((c << 8) | d) != scanline_width) {
  80723. throw "HDR Bad header format, wrong scan line width";
  80724. }
  80725. index = 0;
  80726. // read each of the four channels for the scanline into the buffer
  80727. for (i = 0; i < 4; i++) {
  80728. endIndex = (i + 1) * scanline_width;
  80729. while (index < endIndex) {
  80730. a = uint8array[dataIndex++];
  80731. b = uint8array[dataIndex++];
  80732. if (a > 128) {
  80733. // a run of the same value
  80734. count = a - 128;
  80735. if ((count == 0) || (count > endIndex - index)) {
  80736. throw "HDR Bad Format, bad scanline data (run)";
  80737. }
  80738. while (count-- > 0) {
  80739. scanLineArray[index++] = b;
  80740. }
  80741. }
  80742. else {
  80743. // a non-run
  80744. count = a;
  80745. if ((count == 0) || (count > endIndex - index)) {
  80746. throw "HDR Bad Format, bad scanline data (non-run)";
  80747. }
  80748. scanLineArray[index++] = b;
  80749. if (--count > 0) {
  80750. for (var j = 0; j < count; j++) {
  80751. scanLineArray[index++] = uint8array[dataIndex++];
  80752. }
  80753. }
  80754. }
  80755. }
  80756. }
  80757. // now convert data from buffer into floats
  80758. for (i = 0; i < scanline_width; i++) {
  80759. a = scanLineArray[i];
  80760. b = scanLineArray[i + scanline_width];
  80761. c = scanLineArray[i + 2 * scanline_width];
  80762. d = scanLineArray[i + 3 * scanline_width];
  80763. this.Rgbe2float(resultArray, a, b, c, d, (hdrInfo.height - num_scanlines) * scanline_width * 3 + i * 3);
  80764. }
  80765. num_scanlines--;
  80766. }
  80767. return resultArray;
  80768. };
  80769. return HDRTools;
  80770. }());
  80771. BABYLON.HDRTools = HDRTools;
  80772. })(BABYLON || (BABYLON = {}));
  80773. //# sourceMappingURL=babylon.hdr.js.map
  80774. var BABYLON;
  80775. (function (BABYLON) {
  80776. /**
  80777. * This represents a texture coming from an HDR input.
  80778. *
  80779. * The only supported format is currently panorama picture stored in RGBE format.
  80780. * Example of such files can be found on HDRLib: http://hdrlib.com/
  80781. */
  80782. var HDRCubeTexture = /** @class */ (function (_super) {
  80783. __extends(HDRCubeTexture, _super);
  80784. /**
  80785. * Instantiates an HDRTexture from the following parameters.
  80786. *
  80787. * @param url The location of the HDR raw data (Panorama stored in RGBE format)
  80788. * @param scene The scene the texture will be used in
  80789. * @param size The cubemap desired size (the more it increases the longer the generation will be)
  80790. * @param noMipmap Forces to not generate the mipmap if true
  80791. * @param generateHarmonics Specifies whether you want to extract the polynomial harmonics during the generation process
  80792. * @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)
  80793. * @param reserved Reserved flag for internal use.
  80794. */
  80795. function HDRCubeTexture(url, scene, size, noMipmap, generateHarmonics, gammaSpace, reserved, onLoad, onError) {
  80796. if (noMipmap === void 0) { noMipmap = false; }
  80797. if (generateHarmonics === void 0) { generateHarmonics = true; }
  80798. if (gammaSpace === void 0) { gammaSpace = false; }
  80799. if (reserved === void 0) { reserved = false; }
  80800. if (onLoad === void 0) { onLoad = null; }
  80801. if (onError === void 0) { onError = null; }
  80802. var _this = _super.call(this, scene) || this;
  80803. _this._generateHarmonics = true;
  80804. _this._onLoad = null;
  80805. _this._onError = null;
  80806. /**
  80807. * The texture coordinates mode. As this texture is stored in a cube format, please modify carefully.
  80808. */
  80809. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  80810. _this._isBlocking = true;
  80811. _this._rotationY = 0;
  80812. /**
  80813. * Gets or sets the center of the bounding box associated with the cube texture
  80814. * It must define where the camera used to render the texture was set
  80815. */
  80816. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  80817. if (!url) {
  80818. return _this;
  80819. }
  80820. _this.name = url;
  80821. _this.url = url;
  80822. _this.hasAlpha = false;
  80823. _this.isCube = true;
  80824. _this._textureMatrix = BABYLON.Matrix.Identity();
  80825. _this._onLoad = onLoad;
  80826. _this._onError = onError;
  80827. _this.gammaSpace = gammaSpace;
  80828. _this._noMipmap = noMipmap;
  80829. _this._size = size;
  80830. _this._texture = _this._getFromCache(url, _this._noMipmap);
  80831. if (!_this._texture) {
  80832. if (!scene.useDelayedTextureLoading) {
  80833. _this.loadTexture();
  80834. }
  80835. else {
  80836. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  80837. }
  80838. }
  80839. return _this;
  80840. }
  80841. Object.defineProperty(HDRCubeTexture.prototype, "isBlocking", {
  80842. /**
  80843. * Gets wether or not the texture is blocking during loading.
  80844. */
  80845. get: function () {
  80846. return this._isBlocking;
  80847. },
  80848. /**
  80849. * Sets wether or not the texture is blocking during loading.
  80850. */
  80851. set: function (value) {
  80852. this._isBlocking = value;
  80853. },
  80854. enumerable: true,
  80855. configurable: true
  80856. });
  80857. Object.defineProperty(HDRCubeTexture.prototype, "rotationY", {
  80858. /**
  80859. * Gets texture matrix rotation angle around Y axis radians.
  80860. */
  80861. get: function () {
  80862. return this._rotationY;
  80863. },
  80864. /**
  80865. * Sets texture matrix rotation angle around Y axis in radians.
  80866. */
  80867. set: function (value) {
  80868. this._rotationY = value;
  80869. this.setReflectionTextureMatrix(BABYLON.Matrix.RotationY(this._rotationY));
  80870. },
  80871. enumerable: true,
  80872. configurable: true
  80873. });
  80874. Object.defineProperty(HDRCubeTexture.prototype, "boundingBoxSize", {
  80875. get: function () {
  80876. return this._boundingBoxSize;
  80877. },
  80878. /**
  80879. * Gets or sets the size of the bounding box associated with the cube texture
  80880. * When defined, the cubemap will switch to local mode
  80881. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  80882. * @example https://www.babylonjs-playground.com/#RNASML
  80883. */
  80884. set: function (value) {
  80885. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  80886. return;
  80887. }
  80888. this._boundingBoxSize = value;
  80889. var scene = this.getScene();
  80890. if (scene) {
  80891. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  80892. }
  80893. },
  80894. enumerable: true,
  80895. configurable: true
  80896. });
  80897. /**
  80898. * Occurs when the file is raw .hdr file.
  80899. */
  80900. HDRCubeTexture.prototype.loadTexture = function () {
  80901. var _this = this;
  80902. var callback = function (buffer) {
  80903. var scene = _this.getScene();
  80904. if (!scene) {
  80905. return null;
  80906. }
  80907. // Extract the raw linear data.
  80908. var data = BABYLON.HDRTools.GetCubeMapTextureData(buffer, _this._size);
  80909. // Generate harmonics if needed.
  80910. if (_this._generateHarmonics) {
  80911. var sphericalPolynomial = BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(data);
  80912. _this.sphericalPolynomial = sphericalPolynomial;
  80913. }
  80914. var results = [];
  80915. var byteArray = null;
  80916. // Push each faces.
  80917. for (var j = 0; j < 6; j++) {
  80918. // Create uintarray fallback.
  80919. if (!scene.getEngine().getCaps().textureFloat) {
  80920. // 3 channels of 1 bytes per pixel in bytes.
  80921. var byteBuffer = new ArrayBuffer(_this._size * _this._size * 3);
  80922. byteArray = new Uint8Array(byteBuffer);
  80923. }
  80924. var dataFace = (data[HDRCubeTexture._facesMapping[j]]);
  80925. // If special cases.
  80926. if (_this.gammaSpace || byteArray) {
  80927. for (var i = 0; i < _this._size * _this._size; i++) {
  80928. // Put in gamma space if requested.
  80929. if (_this.gammaSpace) {
  80930. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  80931. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  80932. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  80933. }
  80934. // Convert to int texture for fallback.
  80935. if (byteArray) {
  80936. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  80937. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  80938. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  80939. // May use luminance instead if the result is not accurate.
  80940. var max = Math.max(Math.max(r, g), b);
  80941. if (max > 255) {
  80942. var scale = 255 / max;
  80943. r *= scale;
  80944. g *= scale;
  80945. b *= scale;
  80946. }
  80947. byteArray[(i * 3) + 0] = r;
  80948. byteArray[(i * 3) + 1] = g;
  80949. byteArray[(i * 3) + 2] = b;
  80950. }
  80951. }
  80952. }
  80953. if (byteArray) {
  80954. results.push(byteArray);
  80955. }
  80956. else {
  80957. results.push(dataFace);
  80958. }
  80959. }
  80960. return results;
  80961. };
  80962. var scene = this.getScene();
  80963. if (scene) {
  80964. 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);
  80965. }
  80966. };
  80967. HDRCubeTexture.prototype.clone = function () {
  80968. var scene = this.getScene();
  80969. if (!scene) {
  80970. return this;
  80971. }
  80972. var newTexture = new HDRCubeTexture(this.url, scene, this._size, this._noMipmap, this._generateHarmonics, this.gammaSpace);
  80973. // Base texture
  80974. newTexture.level = this.level;
  80975. newTexture.wrapU = this.wrapU;
  80976. newTexture.wrapV = this.wrapV;
  80977. newTexture.coordinatesIndex = this.coordinatesIndex;
  80978. newTexture.coordinatesMode = this.coordinatesMode;
  80979. return newTexture;
  80980. };
  80981. // Methods
  80982. HDRCubeTexture.prototype.delayLoad = function () {
  80983. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  80984. return;
  80985. }
  80986. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  80987. this._texture = this._getFromCache(this.url, this._noMipmap);
  80988. if (!this._texture) {
  80989. this.loadTexture();
  80990. }
  80991. };
  80992. HDRCubeTexture.prototype.getReflectionTextureMatrix = function () {
  80993. return this._textureMatrix;
  80994. };
  80995. HDRCubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  80996. this._textureMatrix = value;
  80997. };
  80998. HDRCubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  80999. var texture = null;
  81000. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  81001. texture = new HDRCubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.size, parsedTexture.noMipmap, parsedTexture.generateHarmonics, parsedTexture.useInGammaSpace);
  81002. texture.name = parsedTexture.name;
  81003. texture.hasAlpha = parsedTexture.hasAlpha;
  81004. texture.level = parsedTexture.level;
  81005. texture.coordinatesMode = parsedTexture.coordinatesMode;
  81006. texture.isBlocking = parsedTexture.isBlocking;
  81007. }
  81008. if (texture) {
  81009. if (parsedTexture.boundingBoxPosition) {
  81010. texture.boundingBoxPosition = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxPosition);
  81011. }
  81012. if (parsedTexture.boundingBoxSize) {
  81013. texture.boundingBoxSize = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxSize);
  81014. }
  81015. if (parsedTexture.rotationY) {
  81016. texture.rotationY = parsedTexture.rotationY;
  81017. }
  81018. }
  81019. return texture;
  81020. };
  81021. HDRCubeTexture.prototype.serialize = function () {
  81022. if (!this.name) {
  81023. return null;
  81024. }
  81025. var serializationObject = {};
  81026. serializationObject.name = this.name;
  81027. serializationObject.hasAlpha = this.hasAlpha;
  81028. serializationObject.isCube = true;
  81029. serializationObject.level = this.level;
  81030. serializationObject.size = this._size;
  81031. serializationObject.coordinatesMode = this.coordinatesMode;
  81032. serializationObject.useInGammaSpace = this.gammaSpace;
  81033. serializationObject.generateHarmonics = this._generateHarmonics;
  81034. serializationObject.customType = "BABYLON.HDRCubeTexture";
  81035. serializationObject.noMipmap = this._noMipmap;
  81036. serializationObject.isBlocking = this._isBlocking;
  81037. serializationObject.rotationY = this._rotationY;
  81038. return serializationObject;
  81039. };
  81040. HDRCubeTexture._facesMapping = [
  81041. "right",
  81042. "left",
  81043. "up",
  81044. "down",
  81045. "front",
  81046. "back"
  81047. ];
  81048. return HDRCubeTexture;
  81049. }(BABYLON.BaseTexture));
  81050. BABYLON.HDRCubeTexture = HDRCubeTexture;
  81051. })(BABYLON || (BABYLON = {}));
  81052. //# sourceMappingURL=babylon.hdrCubeTexture.js.map
  81053. var BABYLON;
  81054. (function (BABYLON) {
  81055. var IndexedVector2 = /** @class */ (function (_super) {
  81056. __extends(IndexedVector2, _super);
  81057. function IndexedVector2(original, index) {
  81058. var _this = _super.call(this, original.x, original.y) || this;
  81059. _this.index = index;
  81060. return _this;
  81061. }
  81062. return IndexedVector2;
  81063. }(BABYLON.Vector2));
  81064. var PolygonPoints = /** @class */ (function () {
  81065. function PolygonPoints() {
  81066. this.elements = new Array();
  81067. }
  81068. PolygonPoints.prototype.add = function (originalPoints) {
  81069. var _this = this;
  81070. var result = new Array();
  81071. originalPoints.forEach(function (point) {
  81072. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  81073. var newPoint = new IndexedVector2(point, _this.elements.length);
  81074. result.push(newPoint);
  81075. _this.elements.push(newPoint);
  81076. }
  81077. });
  81078. return result;
  81079. };
  81080. PolygonPoints.prototype.computeBounds = function () {
  81081. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  81082. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  81083. this.elements.forEach(function (point) {
  81084. // x
  81085. if (point.x < lmin.x) {
  81086. lmin.x = point.x;
  81087. }
  81088. else if (point.x > lmax.x) {
  81089. lmax.x = point.x;
  81090. }
  81091. // y
  81092. if (point.y < lmin.y) {
  81093. lmin.y = point.y;
  81094. }
  81095. else if (point.y > lmax.y) {
  81096. lmax.y = point.y;
  81097. }
  81098. });
  81099. return {
  81100. min: lmin,
  81101. max: lmax,
  81102. width: lmax.x - lmin.x,
  81103. height: lmax.y - lmin.y
  81104. };
  81105. };
  81106. return PolygonPoints;
  81107. }());
  81108. var Polygon = /** @class */ (function () {
  81109. function Polygon() {
  81110. }
  81111. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  81112. return [
  81113. new BABYLON.Vector2(xmin, ymin),
  81114. new BABYLON.Vector2(xmax, ymin),
  81115. new BABYLON.Vector2(xmax, ymax),
  81116. new BABYLON.Vector2(xmin, ymax)
  81117. ];
  81118. };
  81119. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  81120. if (cx === void 0) { cx = 0; }
  81121. if (cy === void 0) { cy = 0; }
  81122. if (numberOfSides === void 0) { numberOfSides = 32; }
  81123. var result = new Array();
  81124. var angle = 0;
  81125. var increment = (Math.PI * 2) / numberOfSides;
  81126. for (var i = 0; i < numberOfSides; i++) {
  81127. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  81128. angle -= increment;
  81129. }
  81130. return result;
  81131. };
  81132. Polygon.Parse = function (input) {
  81133. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  81134. var i, result = [];
  81135. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  81136. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  81137. }
  81138. return result;
  81139. };
  81140. Polygon.StartingAt = function (x, y) {
  81141. return BABYLON.Path2.StartingAt(x, y);
  81142. };
  81143. return Polygon;
  81144. }());
  81145. BABYLON.Polygon = Polygon;
  81146. var PolygonMeshBuilder = /** @class */ (function () {
  81147. function PolygonMeshBuilder(name, contours, scene) {
  81148. this._points = new PolygonPoints();
  81149. this._outlinepoints = new PolygonPoints();
  81150. this._holes = new Array();
  81151. this._epoints = new Array();
  81152. this._eholes = new Array();
  81153. this._name = name;
  81154. this._scene = scene;
  81155. var points;
  81156. if (contours instanceof BABYLON.Path2) {
  81157. points = contours.getPoints();
  81158. }
  81159. else {
  81160. points = contours;
  81161. }
  81162. this._addToepoint(points);
  81163. this._points.add(points);
  81164. this._outlinepoints.add(points);
  81165. if (typeof earcut === 'undefined') {
  81166. BABYLON.Tools.Warn("Earcut was not found, the polygon will not be built.");
  81167. }
  81168. }
  81169. PolygonMeshBuilder.prototype._addToepoint = function (points) {
  81170. for (var _i = 0, points_1 = points; _i < points_1.length; _i++) {
  81171. var p = points_1[_i];
  81172. this._epoints.push(p.x, p.y);
  81173. }
  81174. };
  81175. PolygonMeshBuilder.prototype.addHole = function (hole) {
  81176. this._points.add(hole);
  81177. var holepoints = new PolygonPoints();
  81178. holepoints.add(hole);
  81179. this._holes.push(holepoints);
  81180. this._eholes.push(this._epoints.length / 2);
  81181. this._addToepoint(hole);
  81182. return this;
  81183. };
  81184. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  81185. var _this = this;
  81186. if (updatable === void 0) { updatable = false; }
  81187. if (depth === void 0) { depth = 0; }
  81188. var result = new BABYLON.Mesh(this._name, this._scene);
  81189. var normals = new Array();
  81190. var positions = new Array();
  81191. var uvs = new Array();
  81192. var bounds = this._points.computeBounds();
  81193. this._points.elements.forEach(function (p) {
  81194. normals.push(0, 1.0, 0);
  81195. positions.push(p.x, 0, p.y);
  81196. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  81197. });
  81198. var indices = new Array();
  81199. var res = earcut(this._epoints, this._eholes, 2);
  81200. for (var i = 0; i < res.length; i++) {
  81201. indices.push(res[i]);
  81202. }
  81203. if (depth > 0) {
  81204. var positionscount = (positions.length / 3); //get the current pointcount
  81205. this._points.elements.forEach(function (p) {
  81206. normals.push(0, -1.0, 0);
  81207. positions.push(p.x, -depth, p.y);
  81208. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  81209. });
  81210. var totalCount = indices.length;
  81211. for (var i = 0; i < totalCount; i += 3) {
  81212. var i0 = indices[i + 0];
  81213. var i1 = indices[i + 1];
  81214. var i2 = indices[i + 2];
  81215. indices.push(i2 + positionscount);
  81216. indices.push(i1 + positionscount);
  81217. indices.push(i0 + positionscount);
  81218. }
  81219. //Add the sides
  81220. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  81221. this._holes.forEach(function (hole) {
  81222. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  81223. });
  81224. }
  81225. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  81226. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  81227. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  81228. result.setIndices(indices);
  81229. return result;
  81230. };
  81231. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  81232. var StartIndex = positions.length / 3;
  81233. var ulength = 0;
  81234. for (var i = 0; i < points.elements.length; i++) {
  81235. var p = points.elements[i];
  81236. var p1;
  81237. if ((i + 1) > points.elements.length - 1) {
  81238. p1 = points.elements[0];
  81239. }
  81240. else {
  81241. p1 = points.elements[i + 1];
  81242. }
  81243. positions.push(p.x, 0, p.y);
  81244. positions.push(p.x, -depth, p.y);
  81245. positions.push(p1.x, 0, p1.y);
  81246. positions.push(p1.x, -depth, p1.y);
  81247. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  81248. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  81249. var v3 = v2.subtract(v1);
  81250. var v4 = new BABYLON.Vector3(0, 1, 0);
  81251. var vn = BABYLON.Vector3.Cross(v3, v4);
  81252. vn = vn.normalize();
  81253. uvs.push(ulength / bounds.width, 0);
  81254. uvs.push(ulength / bounds.width, 1);
  81255. ulength += v3.length();
  81256. uvs.push((ulength / bounds.width), 0);
  81257. uvs.push((ulength / bounds.width), 1);
  81258. if (!flip) {
  81259. normals.push(-vn.x, -vn.y, -vn.z);
  81260. normals.push(-vn.x, -vn.y, -vn.z);
  81261. normals.push(-vn.x, -vn.y, -vn.z);
  81262. normals.push(-vn.x, -vn.y, -vn.z);
  81263. indices.push(StartIndex);
  81264. indices.push(StartIndex + 1);
  81265. indices.push(StartIndex + 2);
  81266. indices.push(StartIndex + 1);
  81267. indices.push(StartIndex + 3);
  81268. indices.push(StartIndex + 2);
  81269. }
  81270. else {
  81271. normals.push(vn.x, vn.y, vn.z);
  81272. normals.push(vn.x, vn.y, vn.z);
  81273. normals.push(vn.x, vn.y, vn.z);
  81274. normals.push(vn.x, vn.y, vn.z);
  81275. indices.push(StartIndex);
  81276. indices.push(StartIndex + 2);
  81277. indices.push(StartIndex + 1);
  81278. indices.push(StartIndex + 1);
  81279. indices.push(StartIndex + 2);
  81280. indices.push(StartIndex + 3);
  81281. }
  81282. StartIndex += 4;
  81283. }
  81284. ;
  81285. };
  81286. return PolygonMeshBuilder;
  81287. }());
  81288. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  81289. })(BABYLON || (BABYLON = {}));
  81290. //# sourceMappingURL=babylon.polygonMesh.js.map
  81291. var BABYLON;
  81292. (function (BABYLON) {
  81293. // Unique ID when we import meshes from Babylon to CSG
  81294. var currentCSGMeshId = 0;
  81295. // # class Vertex
  81296. // Represents a vertex of a polygon. Use your own vertex class instead of this
  81297. // one to provide additional features like texture coordinates and vertex
  81298. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  81299. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  81300. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  81301. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  81302. // is not used anywhere else.
  81303. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  81304. var Vertex = /** @class */ (function () {
  81305. function Vertex(pos, normal, uv) {
  81306. this.pos = pos;
  81307. this.normal = normal;
  81308. this.uv = uv;
  81309. }
  81310. Vertex.prototype.clone = function () {
  81311. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  81312. };
  81313. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  81314. // orientation of a polygon is flipped.
  81315. Vertex.prototype.flip = function () {
  81316. this.normal = this.normal.scale(-1);
  81317. };
  81318. // Create a new vertex between this vertex and `other` by linearly
  81319. // interpolating all properties using a parameter of `t`. Subclasses should
  81320. // override this to interpolate additional properties.
  81321. Vertex.prototype.interpolate = function (other, t) {
  81322. 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));
  81323. };
  81324. return Vertex;
  81325. }());
  81326. // # class Plane
  81327. // Represents a plane in 3D space.
  81328. var Plane = /** @class */ (function () {
  81329. function Plane(normal, w) {
  81330. this.normal = normal;
  81331. this.w = w;
  81332. }
  81333. Plane.FromPoints = function (a, b, c) {
  81334. var v0 = c.subtract(a);
  81335. var v1 = b.subtract(a);
  81336. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  81337. return null;
  81338. }
  81339. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  81340. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  81341. };
  81342. Plane.prototype.clone = function () {
  81343. return new Plane(this.normal.clone(), this.w);
  81344. };
  81345. Plane.prototype.flip = function () {
  81346. this.normal.scaleInPlace(-1);
  81347. this.w = -this.w;
  81348. };
  81349. // Split `polygon` by this plane if needed, then put the polygon or polygon
  81350. // fragments in the appropriate lists. Coplanar polygons go into either
  81351. // `coplanarFront` or `coplanarBack` depending on their orientation with
  81352. // respect to this plane. Polygons in front or in back of this plane go into
  81353. // either `front` or `back`.
  81354. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  81355. var COPLANAR = 0;
  81356. var FRONT = 1;
  81357. var BACK = 2;
  81358. var SPANNING = 3;
  81359. // Classify each point as well as the entire polygon into one of the above
  81360. // four classes.
  81361. var polygonType = 0;
  81362. var types = [];
  81363. var i;
  81364. var t;
  81365. for (i = 0; i < polygon.vertices.length; i++) {
  81366. t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  81367. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  81368. polygonType |= type;
  81369. types.push(type);
  81370. }
  81371. // Put the polygon in the correct list, splitting it when necessary.
  81372. switch (polygonType) {
  81373. case COPLANAR:
  81374. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  81375. break;
  81376. case FRONT:
  81377. front.push(polygon);
  81378. break;
  81379. case BACK:
  81380. back.push(polygon);
  81381. break;
  81382. case SPANNING:
  81383. var f = [], b = [];
  81384. for (i = 0; i < polygon.vertices.length; i++) {
  81385. var j = (i + 1) % polygon.vertices.length;
  81386. var ti = types[i], tj = types[j];
  81387. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  81388. if (ti !== BACK)
  81389. f.push(vi);
  81390. if (ti !== FRONT)
  81391. b.push(ti !== BACK ? vi.clone() : vi);
  81392. if ((ti | tj) === SPANNING) {
  81393. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  81394. var v = vi.interpolate(vj, t);
  81395. f.push(v);
  81396. b.push(v.clone());
  81397. }
  81398. }
  81399. var poly;
  81400. if (f.length >= 3) {
  81401. poly = new Polygon(f, polygon.shared);
  81402. if (poly.plane)
  81403. front.push(poly);
  81404. }
  81405. if (b.length >= 3) {
  81406. poly = new Polygon(b, polygon.shared);
  81407. if (poly.plane)
  81408. back.push(poly);
  81409. }
  81410. break;
  81411. }
  81412. };
  81413. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  81414. // point is on the plane.
  81415. Plane.EPSILON = 1e-5;
  81416. return Plane;
  81417. }());
  81418. // # class Polygon
  81419. // Represents a convex polygon. The vertices used to initialize a polygon must
  81420. // be coplanar and form a convex loop.
  81421. //
  81422. // Each convex polygon has a `shared` property, which is shared between all
  81423. // polygons that are clones of each other or were split from the same polygon.
  81424. // This can be used to define per-polygon properties (such as surface color).
  81425. var Polygon = /** @class */ (function () {
  81426. function Polygon(vertices, shared) {
  81427. this.vertices = vertices;
  81428. this.shared = shared;
  81429. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  81430. }
  81431. Polygon.prototype.clone = function () {
  81432. var vertices = this.vertices.map(function (v) { return v.clone(); });
  81433. return new Polygon(vertices, this.shared);
  81434. };
  81435. Polygon.prototype.flip = function () {
  81436. this.vertices.reverse().map(function (v) { v.flip(); });
  81437. this.plane.flip();
  81438. };
  81439. return Polygon;
  81440. }());
  81441. // # class Node
  81442. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  81443. // by picking a polygon to split along. That polygon (and all other coplanar
  81444. // polygons) are added directly to that node and the other polygons are added to
  81445. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  81446. // no distinction between internal and leaf nodes.
  81447. var Node = /** @class */ (function () {
  81448. function Node(polygons) {
  81449. this.plane = null;
  81450. this.front = null;
  81451. this.back = null;
  81452. this.polygons = new Array();
  81453. if (polygons) {
  81454. this.build(polygons);
  81455. }
  81456. }
  81457. Node.prototype.clone = function () {
  81458. var node = new Node();
  81459. node.plane = this.plane && this.plane.clone();
  81460. node.front = this.front && this.front.clone();
  81461. node.back = this.back && this.back.clone();
  81462. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  81463. return node;
  81464. };
  81465. // Convert solid space to empty space and empty space to solid space.
  81466. Node.prototype.invert = function () {
  81467. for (var i = 0; i < this.polygons.length; i++) {
  81468. this.polygons[i].flip();
  81469. }
  81470. if (this.plane) {
  81471. this.plane.flip();
  81472. }
  81473. if (this.front) {
  81474. this.front.invert();
  81475. }
  81476. if (this.back) {
  81477. this.back.invert();
  81478. }
  81479. var temp = this.front;
  81480. this.front = this.back;
  81481. this.back = temp;
  81482. };
  81483. // Recursively remove all polygons in `polygons` that are inside this BSP
  81484. // tree.
  81485. Node.prototype.clipPolygons = function (polygons) {
  81486. if (!this.plane)
  81487. return polygons.slice();
  81488. var front = new Array(), back = new Array();
  81489. for (var i = 0; i < polygons.length; i++) {
  81490. this.plane.splitPolygon(polygons[i], front, back, front, back);
  81491. }
  81492. if (this.front) {
  81493. front = this.front.clipPolygons(front);
  81494. }
  81495. if (this.back) {
  81496. back = this.back.clipPolygons(back);
  81497. }
  81498. else {
  81499. back = [];
  81500. }
  81501. return front.concat(back);
  81502. };
  81503. // Remove all polygons in this BSP tree that are inside the other BSP tree
  81504. // `bsp`.
  81505. Node.prototype.clipTo = function (bsp) {
  81506. this.polygons = bsp.clipPolygons(this.polygons);
  81507. if (this.front)
  81508. this.front.clipTo(bsp);
  81509. if (this.back)
  81510. this.back.clipTo(bsp);
  81511. };
  81512. // Return a list of all polygons in this BSP tree.
  81513. Node.prototype.allPolygons = function () {
  81514. var polygons = this.polygons.slice();
  81515. if (this.front)
  81516. polygons = polygons.concat(this.front.allPolygons());
  81517. if (this.back)
  81518. polygons = polygons.concat(this.back.allPolygons());
  81519. return polygons;
  81520. };
  81521. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  81522. // new polygons are filtered down to the bottom of the tree and become new
  81523. // nodes there. Each set of polygons is partitioned using the first polygon
  81524. // (no heuristic is used to pick a good split).
  81525. Node.prototype.build = function (polygons) {
  81526. if (!polygons.length)
  81527. return;
  81528. if (!this.plane)
  81529. this.plane = polygons[0].plane.clone();
  81530. var front = new Array(), back = new Array();
  81531. for (var i = 0; i < polygons.length; i++) {
  81532. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  81533. }
  81534. if (front.length) {
  81535. if (!this.front)
  81536. this.front = new Node();
  81537. this.front.build(front);
  81538. }
  81539. if (back.length) {
  81540. if (!this.back)
  81541. this.back = new Node();
  81542. this.back.build(back);
  81543. }
  81544. };
  81545. return Node;
  81546. }());
  81547. var CSG = /** @class */ (function () {
  81548. function CSG() {
  81549. this.polygons = new Array();
  81550. }
  81551. // Convert BABYLON.Mesh to BABYLON.CSG
  81552. CSG.FromMesh = function (mesh) {
  81553. var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
  81554. var matrix, meshPosition, meshRotation, meshRotationQuaternion = null, meshScaling;
  81555. if (mesh instanceof BABYLON.Mesh) {
  81556. mesh.computeWorldMatrix(true);
  81557. matrix = mesh.getWorldMatrix();
  81558. meshPosition = mesh.position.clone();
  81559. meshRotation = mesh.rotation.clone();
  81560. if (mesh.rotationQuaternion) {
  81561. meshRotationQuaternion = mesh.rotationQuaternion.clone();
  81562. }
  81563. meshScaling = mesh.scaling.clone();
  81564. }
  81565. else {
  81566. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  81567. }
  81568. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  81569. var subMeshes = mesh.subMeshes;
  81570. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  81571. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  81572. vertices = [];
  81573. for (var j = 0; j < 3; j++) {
  81574. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  81575. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  81576. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  81577. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  81578. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  81579. vertex = new Vertex(position, normal, uv);
  81580. vertices.push(vertex);
  81581. }
  81582. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  81583. // To handle the case of degenerated triangle
  81584. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  81585. if (polygon.plane)
  81586. polygons.push(polygon);
  81587. }
  81588. }
  81589. var csg = CSG.FromPolygons(polygons);
  81590. csg.matrix = matrix;
  81591. csg.position = meshPosition;
  81592. csg.rotation = meshRotation;
  81593. csg.scaling = meshScaling;
  81594. csg.rotationQuaternion = meshRotationQuaternion;
  81595. currentCSGMeshId++;
  81596. return csg;
  81597. };
  81598. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  81599. CSG.FromPolygons = function (polygons) {
  81600. var csg = new CSG();
  81601. csg.polygons = polygons;
  81602. return csg;
  81603. };
  81604. CSG.prototype.clone = function () {
  81605. var csg = new CSG();
  81606. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  81607. csg.copyTransformAttributes(this);
  81608. return csg;
  81609. };
  81610. CSG.prototype.union = function (csg) {
  81611. var a = new Node(this.clone().polygons);
  81612. var b = new Node(csg.clone().polygons);
  81613. a.clipTo(b);
  81614. b.clipTo(a);
  81615. b.invert();
  81616. b.clipTo(a);
  81617. b.invert();
  81618. a.build(b.allPolygons());
  81619. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  81620. };
  81621. CSG.prototype.unionInPlace = function (csg) {
  81622. var a = new Node(this.polygons);
  81623. var b = new Node(csg.polygons);
  81624. a.clipTo(b);
  81625. b.clipTo(a);
  81626. b.invert();
  81627. b.clipTo(a);
  81628. b.invert();
  81629. a.build(b.allPolygons());
  81630. this.polygons = a.allPolygons();
  81631. };
  81632. CSG.prototype.subtract = function (csg) {
  81633. var a = new Node(this.clone().polygons);
  81634. var b = new Node(csg.clone().polygons);
  81635. a.invert();
  81636. a.clipTo(b);
  81637. b.clipTo(a);
  81638. b.invert();
  81639. b.clipTo(a);
  81640. b.invert();
  81641. a.build(b.allPolygons());
  81642. a.invert();
  81643. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  81644. };
  81645. CSG.prototype.subtractInPlace = function (csg) {
  81646. var a = new Node(this.polygons);
  81647. var b = new Node(csg.polygons);
  81648. a.invert();
  81649. a.clipTo(b);
  81650. b.clipTo(a);
  81651. b.invert();
  81652. b.clipTo(a);
  81653. b.invert();
  81654. a.build(b.allPolygons());
  81655. a.invert();
  81656. this.polygons = a.allPolygons();
  81657. };
  81658. CSG.prototype.intersect = function (csg) {
  81659. var a = new Node(this.clone().polygons);
  81660. var b = new Node(csg.clone().polygons);
  81661. a.invert();
  81662. b.clipTo(a);
  81663. b.invert();
  81664. a.clipTo(b);
  81665. b.clipTo(a);
  81666. a.build(b.allPolygons());
  81667. a.invert();
  81668. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  81669. };
  81670. CSG.prototype.intersectInPlace = function (csg) {
  81671. var a = new Node(this.polygons);
  81672. var b = new Node(csg.polygons);
  81673. a.invert();
  81674. b.clipTo(a);
  81675. b.invert();
  81676. a.clipTo(b);
  81677. b.clipTo(a);
  81678. a.build(b.allPolygons());
  81679. a.invert();
  81680. this.polygons = a.allPolygons();
  81681. };
  81682. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  81683. // not modified.
  81684. CSG.prototype.inverse = function () {
  81685. var csg = this.clone();
  81686. csg.inverseInPlace();
  81687. return csg;
  81688. };
  81689. CSG.prototype.inverseInPlace = function () {
  81690. this.polygons.map(function (p) { p.flip(); });
  81691. };
  81692. // This is used to keep meshes transformations so they can be restored
  81693. // when we build back a Babylon Mesh
  81694. // NB : All CSG operations are performed in world coordinates
  81695. CSG.prototype.copyTransformAttributes = function (csg) {
  81696. this.matrix = csg.matrix;
  81697. this.position = csg.position;
  81698. this.rotation = csg.rotation;
  81699. this.scaling = csg.scaling;
  81700. this.rotationQuaternion = csg.rotationQuaternion;
  81701. return this;
  81702. };
  81703. // Build Raw mesh from CSG
  81704. // Coordinates here are in world space
  81705. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  81706. var matrix = this.matrix.clone();
  81707. matrix.invert();
  81708. 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;
  81709. if (keepSubMeshes) {
  81710. // Sort Polygons, since subMeshes are indices range
  81711. polygons.sort(function (a, b) {
  81712. if (a.shared.meshId === b.shared.meshId) {
  81713. return a.shared.subMeshId - b.shared.subMeshId;
  81714. }
  81715. else {
  81716. return a.shared.meshId - b.shared.meshId;
  81717. }
  81718. });
  81719. }
  81720. for (var i = 0, il = polygons.length; i < il; i++) {
  81721. polygon = polygons[i];
  81722. // Building SubMeshes
  81723. if (!subMesh_dict[polygon.shared.meshId]) {
  81724. subMesh_dict[polygon.shared.meshId] = {};
  81725. }
  81726. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  81727. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  81728. indexStart: +Infinity,
  81729. indexEnd: -Infinity,
  81730. materialIndex: polygon.shared.materialIndex
  81731. };
  81732. }
  81733. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  81734. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  81735. polygonIndices[0] = 0;
  81736. polygonIndices[1] = j - 1;
  81737. polygonIndices[2] = j;
  81738. for (var k = 0; k < 3; k++) {
  81739. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  81740. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  81741. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  81742. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  81743. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  81744. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  81745. // Check if 2 points can be merged
  81746. if (!(typeof vertex_idx !== 'undefined' &&
  81747. normals[vertex_idx * 3] === localNormal.x &&
  81748. normals[vertex_idx * 3 + 1] === localNormal.y &&
  81749. normals[vertex_idx * 3 + 2] === localNormal.z &&
  81750. uvs[vertex_idx * 2] === uv.x &&
  81751. uvs[vertex_idx * 2 + 1] === uv.y)) {
  81752. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  81753. uvs.push(uv.x, uv.y);
  81754. normals.push(normal.x, normal.y, normal.z);
  81755. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  81756. }
  81757. indices.push(vertex_idx);
  81758. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  81759. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  81760. currentIndex++;
  81761. }
  81762. }
  81763. }
  81764. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  81765. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  81766. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  81767. mesh.setIndices(indices, null);
  81768. if (keepSubMeshes) {
  81769. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  81770. var materialIndexOffset = 0, materialMaxIndex;
  81771. mesh.subMeshes = new Array();
  81772. for (var m in subMesh_dict) {
  81773. materialMaxIndex = -1;
  81774. for (var sm in subMesh_dict[m]) {
  81775. subMesh_obj = subMesh_dict[m][sm];
  81776. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  81777. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  81778. }
  81779. materialIndexOffset += ++materialMaxIndex;
  81780. }
  81781. }
  81782. return mesh;
  81783. };
  81784. // Build Mesh from CSG taking material and transforms into account
  81785. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  81786. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  81787. mesh.material = material;
  81788. mesh.position.copyFrom(this.position);
  81789. mesh.rotation.copyFrom(this.rotation);
  81790. if (this.rotationQuaternion) {
  81791. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  81792. }
  81793. mesh.scaling.copyFrom(this.scaling);
  81794. mesh.computeWorldMatrix(true);
  81795. return mesh;
  81796. };
  81797. return CSG;
  81798. }());
  81799. BABYLON.CSG = CSG;
  81800. })(BABYLON || (BABYLON = {}));
  81801. //# sourceMappingURL=babylon.csg.js.map
  81802. var BABYLON;
  81803. (function (BABYLON) {
  81804. var LensFlare = /** @class */ (function () {
  81805. function LensFlare(size, position, color, imgUrl, system) {
  81806. this.size = size;
  81807. this.position = position;
  81808. this.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  81809. this.color = color || new BABYLON.Color3(1, 1, 1);
  81810. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  81811. this._system = system;
  81812. system.lensFlares.push(this);
  81813. }
  81814. LensFlare.AddFlare = function (size, position, color, imgUrl, system) {
  81815. return new LensFlare(size, position, color, imgUrl, system);
  81816. };
  81817. LensFlare.prototype.dispose = function () {
  81818. if (this.texture) {
  81819. this.texture.dispose();
  81820. }
  81821. // Remove from scene
  81822. var index = this._system.lensFlares.indexOf(this);
  81823. this._system.lensFlares.splice(index, 1);
  81824. };
  81825. ;
  81826. return LensFlare;
  81827. }());
  81828. BABYLON.LensFlare = LensFlare;
  81829. })(BABYLON || (BABYLON = {}));
  81830. //# sourceMappingURL=babylon.lensFlare.js.map
  81831. var BABYLON;
  81832. (function (BABYLON) {
  81833. var LensFlareSystem = /** @class */ (function () {
  81834. function LensFlareSystem(name, emitter, scene) {
  81835. this.name = name;
  81836. this.lensFlares = new Array();
  81837. this.borderLimit = 300;
  81838. this.viewportBorder = 0;
  81839. this.layerMask = 0x0FFFFFFF;
  81840. this._vertexBuffers = {};
  81841. this._isEnabled = true;
  81842. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  81843. this._emitter = emitter;
  81844. this.id = name;
  81845. scene.lensFlareSystems.push(this);
  81846. this.meshesSelectionPredicate = function (m) { return (scene.activeCamera && m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0)); };
  81847. var engine = scene.getEngine();
  81848. // VBO
  81849. var vertices = [];
  81850. vertices.push(1, 1);
  81851. vertices.push(-1, 1);
  81852. vertices.push(-1, -1);
  81853. vertices.push(1, -1);
  81854. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  81855. // Indices
  81856. var indices = [];
  81857. indices.push(0);
  81858. indices.push(1);
  81859. indices.push(2);
  81860. indices.push(0);
  81861. indices.push(2);
  81862. indices.push(3);
  81863. this._indexBuffer = engine.createIndexBuffer(indices);
  81864. // Effects
  81865. this._effect = engine.createEffect("lensFlare", [BABYLON.VertexBuffer.PositionKind], ["color", "viewportMatrix"], ["textureSampler"], "");
  81866. }
  81867. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  81868. get: function () {
  81869. return this._isEnabled;
  81870. },
  81871. set: function (value) {
  81872. this._isEnabled = value;
  81873. },
  81874. enumerable: true,
  81875. configurable: true
  81876. });
  81877. LensFlareSystem.prototype.getScene = function () {
  81878. return this._scene;
  81879. };
  81880. LensFlareSystem.prototype.getEmitter = function () {
  81881. return this._emitter;
  81882. };
  81883. LensFlareSystem.prototype.setEmitter = function (newEmitter) {
  81884. this._emitter = newEmitter;
  81885. };
  81886. LensFlareSystem.prototype.getEmitterPosition = function () {
  81887. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  81888. };
  81889. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  81890. var position = this.getEmitterPosition();
  81891. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  81892. this._positionX = position.x;
  81893. this._positionY = position.y;
  81894. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  81895. if (this.viewportBorder > 0) {
  81896. globalViewport.x -= this.viewportBorder;
  81897. globalViewport.y -= this.viewportBorder;
  81898. globalViewport.width += this.viewportBorder * 2;
  81899. globalViewport.height += this.viewportBorder * 2;
  81900. position.x += this.viewportBorder;
  81901. position.y += this.viewportBorder;
  81902. this._positionX += this.viewportBorder;
  81903. this._positionY += this.viewportBorder;
  81904. }
  81905. if (position.z > 0) {
  81906. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  81907. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  81908. return true;
  81909. }
  81910. return true;
  81911. }
  81912. return false;
  81913. };
  81914. LensFlareSystem.prototype._isVisible = function () {
  81915. if (!this._isEnabled || !this._scene.activeCamera) {
  81916. return false;
  81917. }
  81918. var emitterPosition = this.getEmitterPosition();
  81919. var direction = emitterPosition.subtract(this._scene.activeCamera.globalPosition);
  81920. var distance = direction.length();
  81921. direction.normalize();
  81922. var ray = new BABYLON.Ray(this._scene.activeCamera.globalPosition, direction);
  81923. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  81924. return !pickInfo || !pickInfo.hit || pickInfo.distance > distance;
  81925. };
  81926. LensFlareSystem.prototype.render = function () {
  81927. if (!this._effect.isReady() || !this._scene.activeCamera)
  81928. return false;
  81929. var engine = this._scene.getEngine();
  81930. var viewport = this._scene.activeCamera.viewport;
  81931. var globalViewport = viewport.toGlobal(engine.getRenderWidth(true), engine.getRenderHeight(true));
  81932. // Position
  81933. if (!this.computeEffectivePosition(globalViewport)) {
  81934. return false;
  81935. }
  81936. // Visibility
  81937. if (!this._isVisible()) {
  81938. return false;
  81939. }
  81940. // Intensity
  81941. var awayX;
  81942. var awayY;
  81943. if (this._positionX < this.borderLimit + globalViewport.x) {
  81944. awayX = this.borderLimit + globalViewport.x - this._positionX;
  81945. }
  81946. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  81947. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  81948. }
  81949. else {
  81950. awayX = 0;
  81951. }
  81952. if (this._positionY < this.borderLimit + globalViewport.y) {
  81953. awayY = this.borderLimit + globalViewport.y - this._positionY;
  81954. }
  81955. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  81956. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  81957. }
  81958. else {
  81959. awayY = 0;
  81960. }
  81961. var away = (awayX > awayY) ? awayX : awayY;
  81962. away -= this.viewportBorder;
  81963. if (away > this.borderLimit) {
  81964. away = this.borderLimit;
  81965. }
  81966. var intensity = 1.0 - (away / this.borderLimit);
  81967. if (intensity < 0) {
  81968. return false;
  81969. }
  81970. if (intensity > 1.0) {
  81971. intensity = 1.0;
  81972. }
  81973. if (this.viewportBorder > 0) {
  81974. globalViewport.x += this.viewportBorder;
  81975. globalViewport.y += this.viewportBorder;
  81976. globalViewport.width -= this.viewportBorder * 2;
  81977. globalViewport.height -= this.viewportBorder * 2;
  81978. this._positionX -= this.viewportBorder;
  81979. this._positionY -= this.viewportBorder;
  81980. }
  81981. // Position
  81982. var centerX = globalViewport.x + globalViewport.width / 2;
  81983. var centerY = globalViewport.y + globalViewport.height / 2;
  81984. var distX = centerX - this._positionX;
  81985. var distY = centerY - this._positionY;
  81986. // Effects
  81987. engine.enableEffect(this._effect);
  81988. engine.setState(false);
  81989. engine.setDepthBuffer(false);
  81990. // VBOs
  81991. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  81992. // Flares
  81993. for (var index = 0; index < this.lensFlares.length; index++) {
  81994. var flare = this.lensFlares[index];
  81995. engine.setAlphaMode(flare.alphaMode);
  81996. var x = centerX - (distX * flare.position);
  81997. var y = centerY - (distY * flare.position);
  81998. var cw = flare.size;
  81999. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera, true);
  82000. var cx = 2 * (x / (globalViewport.width + globalViewport.x * 2)) - 1.0;
  82001. var cy = 1.0 - 2 * (y / (globalViewport.height + globalViewport.y * 2));
  82002. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  82003. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  82004. // Texture
  82005. this._effect.setTexture("textureSampler", flare.texture);
  82006. // Color
  82007. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  82008. // Draw order
  82009. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  82010. }
  82011. engine.setDepthBuffer(true);
  82012. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  82013. return true;
  82014. };
  82015. LensFlareSystem.prototype.dispose = function () {
  82016. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  82017. if (vertexBuffer) {
  82018. vertexBuffer.dispose();
  82019. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  82020. }
  82021. if (this._indexBuffer) {
  82022. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  82023. this._indexBuffer = null;
  82024. }
  82025. while (this.lensFlares.length) {
  82026. this.lensFlares[0].dispose();
  82027. }
  82028. // Remove from scene
  82029. var index = this._scene.lensFlareSystems.indexOf(this);
  82030. this._scene.lensFlareSystems.splice(index, 1);
  82031. };
  82032. LensFlareSystem.Parse = function (parsedLensFlareSystem, scene, rootUrl) {
  82033. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  82034. var name = parsedLensFlareSystem.name || "lensFlareSystem#" + parsedLensFlareSystem.emitterId;
  82035. var lensFlareSystem = new LensFlareSystem(name, emitter, scene);
  82036. lensFlareSystem.id = parsedLensFlareSystem.id || name;
  82037. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  82038. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  82039. var parsedFlare = parsedLensFlareSystem.flares[index];
  82040. BABYLON.LensFlare.AddFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), parsedFlare.textureName ? rootUrl + parsedFlare.textureName : "", lensFlareSystem);
  82041. }
  82042. return lensFlareSystem;
  82043. };
  82044. LensFlareSystem.prototype.serialize = function () {
  82045. var serializationObject = {};
  82046. serializationObject.id = this.id;
  82047. serializationObject.name = this.name;
  82048. serializationObject.emitterId = this.getEmitter().id;
  82049. serializationObject.borderLimit = this.borderLimit;
  82050. serializationObject.flares = [];
  82051. for (var index = 0; index < this.lensFlares.length; index++) {
  82052. var flare = this.lensFlares[index];
  82053. serializationObject.flares.push({
  82054. size: flare.size,
  82055. position: flare.position,
  82056. color: flare.color.asArray(),
  82057. textureName: BABYLON.Tools.GetFilename(flare.texture ? flare.texture.name : "")
  82058. });
  82059. }
  82060. return serializationObject;
  82061. };
  82062. return LensFlareSystem;
  82063. }());
  82064. BABYLON.LensFlareSystem = LensFlareSystem;
  82065. })(BABYLON || (BABYLON = {}));
  82066. //# sourceMappingURL=babylon.lensFlareSystem.js.map
  82067. var BABYLON;
  82068. (function (BABYLON) {
  82069. /**
  82070. * This is a holder class for the physics joint created by the physics plugin.
  82071. * It holds a set of functions to control the underlying joint.
  82072. */
  82073. var PhysicsJoint = /** @class */ (function () {
  82074. function PhysicsJoint(type, jointData) {
  82075. this.type = type;
  82076. this.jointData = jointData;
  82077. jointData.nativeParams = jointData.nativeParams || {};
  82078. }
  82079. Object.defineProperty(PhysicsJoint.prototype, "physicsJoint", {
  82080. get: function () {
  82081. return this._physicsJoint;
  82082. },
  82083. set: function (newJoint) {
  82084. if (this._physicsJoint) {
  82085. //remove from the wolrd
  82086. }
  82087. this._physicsJoint = newJoint;
  82088. },
  82089. enumerable: true,
  82090. configurable: true
  82091. });
  82092. Object.defineProperty(PhysicsJoint.prototype, "physicsPlugin", {
  82093. set: function (physicsPlugin) {
  82094. this._physicsPlugin = physicsPlugin;
  82095. },
  82096. enumerable: true,
  82097. configurable: true
  82098. });
  82099. /**
  82100. * Execute a function that is physics-plugin specific.
  82101. * @param {Function} func the function that will be executed.
  82102. * It accepts two parameters: the physics world and the physics joint.
  82103. */
  82104. PhysicsJoint.prototype.executeNativeFunction = function (func) {
  82105. func(this._physicsPlugin.world, this._physicsJoint);
  82106. };
  82107. //TODO check if the native joints are the same
  82108. //Joint Types
  82109. PhysicsJoint.DistanceJoint = 0;
  82110. PhysicsJoint.HingeJoint = 1;
  82111. PhysicsJoint.BallAndSocketJoint = 2;
  82112. PhysicsJoint.WheelJoint = 3;
  82113. PhysicsJoint.SliderJoint = 4;
  82114. //OIMO
  82115. PhysicsJoint.PrismaticJoint = 5;
  82116. //ENERGY FTW! (compare with this - http://ode-wiki.org/wiki/index.php?title=Manual:_Joint_Types_and_Functions)
  82117. PhysicsJoint.UniversalJoint = 6;
  82118. PhysicsJoint.Hinge2Joint = PhysicsJoint.WheelJoint;
  82119. //Cannon
  82120. //Similar to a Ball-Joint. Different in params
  82121. PhysicsJoint.PointToPointJoint = 8;
  82122. //Cannon only at the moment
  82123. PhysicsJoint.SpringJoint = 9;
  82124. PhysicsJoint.LockJoint = 10;
  82125. return PhysicsJoint;
  82126. }());
  82127. BABYLON.PhysicsJoint = PhysicsJoint;
  82128. /**
  82129. * A class representing a physics distance joint.
  82130. */
  82131. var DistanceJoint = /** @class */ (function (_super) {
  82132. __extends(DistanceJoint, _super);
  82133. function DistanceJoint(jointData) {
  82134. return _super.call(this, PhysicsJoint.DistanceJoint, jointData) || this;
  82135. }
  82136. /**
  82137. * Update the predefined distance.
  82138. */
  82139. DistanceJoint.prototype.updateDistance = function (maxDistance, minDistance) {
  82140. this._physicsPlugin.updateDistanceJoint(this, maxDistance, minDistance);
  82141. };
  82142. return DistanceJoint;
  82143. }(PhysicsJoint));
  82144. BABYLON.DistanceJoint = DistanceJoint;
  82145. var MotorEnabledJoint = /** @class */ (function (_super) {
  82146. __extends(MotorEnabledJoint, _super);
  82147. function MotorEnabledJoint(type, jointData) {
  82148. return _super.call(this, type, jointData) || this;
  82149. }
  82150. /**
  82151. * Set the motor values.
  82152. * Attention, this function is plugin specific. Engines won't react 100% the same.
  82153. * @param {number} force the force to apply
  82154. * @param {number} maxForce max force for this motor.
  82155. */
  82156. MotorEnabledJoint.prototype.setMotor = function (force, maxForce) {
  82157. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  82158. };
  82159. /**
  82160. * Set the motor's limits.
  82161. * Attention, this function is plugin specific. Engines won't react 100% the same.
  82162. */
  82163. MotorEnabledJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  82164. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  82165. };
  82166. return MotorEnabledJoint;
  82167. }(PhysicsJoint));
  82168. BABYLON.MotorEnabledJoint = MotorEnabledJoint;
  82169. /**
  82170. * This class represents a single hinge physics joint
  82171. */
  82172. var HingeJoint = /** @class */ (function (_super) {
  82173. __extends(HingeJoint, _super);
  82174. function HingeJoint(jointData) {
  82175. return _super.call(this, PhysicsJoint.HingeJoint, jointData) || this;
  82176. }
  82177. /**
  82178. * Set the motor values.
  82179. * Attention, this function is plugin specific. Engines won't react 100% the same.
  82180. * @param {number} force the force to apply
  82181. * @param {number} maxForce max force for this motor.
  82182. */
  82183. HingeJoint.prototype.setMotor = function (force, maxForce) {
  82184. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  82185. };
  82186. /**
  82187. * Set the motor's limits.
  82188. * Attention, this function is plugin specific. Engines won't react 100% the same.
  82189. */
  82190. HingeJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  82191. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  82192. };
  82193. return HingeJoint;
  82194. }(MotorEnabledJoint));
  82195. BABYLON.HingeJoint = HingeJoint;
  82196. /**
  82197. * This class represents a dual hinge physics joint (same as wheel joint)
  82198. */
  82199. var Hinge2Joint = /** @class */ (function (_super) {
  82200. __extends(Hinge2Joint, _super);
  82201. function Hinge2Joint(jointData) {
  82202. return _super.call(this, PhysicsJoint.Hinge2Joint, jointData) || this;
  82203. }
  82204. /**
  82205. * Set the motor values.
  82206. * Attention, this function is plugin specific. Engines won't react 100% the same.
  82207. * @param {number} force the force to apply
  82208. * @param {number} maxForce max force for this motor.
  82209. * @param {motorIndex} the motor's index, 0 or 1.
  82210. */
  82211. Hinge2Joint.prototype.setMotor = function (force, maxForce, motorIndex) {
  82212. if (motorIndex === void 0) { motorIndex = 0; }
  82213. this._physicsPlugin.setMotor(this, force || 0, maxForce, motorIndex);
  82214. };
  82215. /**
  82216. * Set the motor limits.
  82217. * Attention, this function is plugin specific. Engines won't react 100% the same.
  82218. * @param {number} upperLimit the upper limit
  82219. * @param {number} lowerLimit lower limit
  82220. * @param {motorIndex} the motor's index, 0 or 1.
  82221. */
  82222. Hinge2Joint.prototype.setLimit = function (upperLimit, lowerLimit, motorIndex) {
  82223. if (motorIndex === void 0) { motorIndex = 0; }
  82224. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit, motorIndex);
  82225. };
  82226. return Hinge2Joint;
  82227. }(MotorEnabledJoint));
  82228. BABYLON.Hinge2Joint = Hinge2Joint;
  82229. })(BABYLON || (BABYLON = {}));
  82230. //# sourceMappingURL=babylon.physicsJoint.js.map
  82231. var BABYLON;
  82232. (function (BABYLON) {
  82233. var PhysicsImpostor = /** @class */ (function () {
  82234. function PhysicsImpostor(object, type, _options, _scene) {
  82235. if (_options === void 0) { _options = { mass: 0 }; }
  82236. var _this = this;
  82237. this.object = object;
  82238. this.type = type;
  82239. this._options = _options;
  82240. this._scene = _scene;
  82241. this._bodyUpdateRequired = false;
  82242. this._onBeforePhysicsStepCallbacks = new Array();
  82243. this._onAfterPhysicsStepCallbacks = new Array();
  82244. this._onPhysicsCollideCallbacks = [];
  82245. this._deltaPosition = BABYLON.Vector3.Zero();
  82246. this._isDisposed = false;
  82247. //temp variables for parent rotation calculations
  82248. //private _mats: Array<Matrix> = [new Matrix(), new Matrix()];
  82249. this._tmpQuat = new BABYLON.Quaternion();
  82250. this._tmpQuat2 = new BABYLON.Quaternion();
  82251. /**
  82252. * this function is executed by the physics engine.
  82253. */
  82254. this.beforeStep = function () {
  82255. if (!_this._physicsEngine) {
  82256. return;
  82257. }
  82258. _this.object.translate(_this._deltaPosition, -1);
  82259. _this._deltaRotationConjugated && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotationConjugated, _this.object.rotationQuaternion);
  82260. _this.object.computeWorldMatrix(false);
  82261. if (_this.object.parent && _this.object.rotationQuaternion) {
  82262. _this.getParentsRotation();
  82263. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this._tmpQuat);
  82264. }
  82265. else {
  82266. _this._tmpQuat.copyFrom(_this.object.rotationQuaternion || new BABYLON.Quaternion());
  82267. }
  82268. if (!_this._options.disableBidirectionalTransformation) {
  82269. _this.object.rotationQuaternion && _this._physicsEngine.getPhysicsPlugin().setPhysicsBodyTransformation(_this, /*bInfo.boundingBox.centerWorld*/ _this.object.getAbsolutePivotPoint(), _this._tmpQuat);
  82270. }
  82271. _this._onBeforePhysicsStepCallbacks.forEach(function (func) {
  82272. func(_this);
  82273. });
  82274. };
  82275. /**
  82276. * this function is executed by the physics engine.
  82277. */
  82278. this.afterStep = function () {
  82279. if (!_this._physicsEngine) {
  82280. return;
  82281. }
  82282. _this._onAfterPhysicsStepCallbacks.forEach(function (func) {
  82283. func(_this);
  82284. });
  82285. _this._physicsEngine.getPhysicsPlugin().setTransformationFromPhysicsBody(_this);
  82286. // object has now its world rotation. needs to be converted to local.
  82287. if (_this.object.parent && _this.object.rotationQuaternion) {
  82288. _this.getParentsRotation();
  82289. _this._tmpQuat.conjugateInPlace();
  82290. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this.object.rotationQuaternion);
  82291. }
  82292. // take the position set and make it the absolute position of this object.
  82293. _this.object.setAbsolutePosition(_this.object.position);
  82294. _this._deltaRotation && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotation, _this.object.rotationQuaternion);
  82295. _this.object.translate(_this._deltaPosition, 1);
  82296. };
  82297. /**
  82298. * Legacy collision detection event support
  82299. */
  82300. this.onCollideEvent = null;
  82301. //event and body object due to cannon's event-based architecture.
  82302. this.onCollide = function (e) {
  82303. if (!_this._onPhysicsCollideCallbacks.length && !_this.onCollideEvent) {
  82304. return;
  82305. }
  82306. if (!_this._physicsEngine) {
  82307. return;
  82308. }
  82309. var otherImpostor = _this._physicsEngine.getImpostorWithPhysicsBody(e.body);
  82310. if (otherImpostor) {
  82311. // Legacy collision detection event support
  82312. if (_this.onCollideEvent) {
  82313. _this.onCollideEvent(_this, otherImpostor);
  82314. }
  82315. _this._onPhysicsCollideCallbacks.filter(function (obj) {
  82316. return obj.otherImpostors.indexOf(otherImpostor) !== -1;
  82317. }).forEach(function (obj) {
  82318. obj.callback(_this, otherImpostor);
  82319. });
  82320. }
  82321. };
  82322. //sanity check!
  82323. if (!this.object) {
  82324. BABYLON.Tools.Error("No object was provided. A physics object is obligatory");
  82325. return;
  82326. }
  82327. //legacy support for old syntax.
  82328. if (!this._scene && object.getScene) {
  82329. this._scene = object.getScene();
  82330. }
  82331. if (!this._scene) {
  82332. return;
  82333. }
  82334. this._physicsEngine = this._scene.getPhysicsEngine();
  82335. if (!this._physicsEngine) {
  82336. BABYLON.Tools.Error("Physics not enabled. Please use scene.enablePhysics(...) before creating impostors.");
  82337. }
  82338. else {
  82339. //set the object's quaternion, if not set
  82340. if (!this.object.rotationQuaternion) {
  82341. if (this.object.rotation) {
  82342. this.object.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.object.rotation.y, this.object.rotation.x, this.object.rotation.z);
  82343. }
  82344. else {
  82345. this.object.rotationQuaternion = new BABYLON.Quaternion();
  82346. }
  82347. }
  82348. //default options params
  82349. this._options.mass = (_options.mass === void 0) ? 0 : _options.mass;
  82350. this._options.friction = (_options.friction === void 0) ? 0.2 : _options.friction;
  82351. this._options.restitution = (_options.restitution === void 0) ? 0.2 : _options.restitution;
  82352. this._joints = [];
  82353. //If the mesh has a parent, don't initialize the physicsBody. Instead wait for the parent to do that.
  82354. if (!this.object.parent || this._options.ignoreParent) {
  82355. this._init();
  82356. }
  82357. else if (this.object.parent.physicsImpostor) {
  82358. BABYLON.Tools.Warn("You must affect impostors to children before affecting impostor to parent.");
  82359. }
  82360. }
  82361. }
  82362. Object.defineProperty(PhysicsImpostor.prototype, "isDisposed", {
  82363. get: function () {
  82364. return this._isDisposed;
  82365. },
  82366. enumerable: true,
  82367. configurable: true
  82368. });
  82369. Object.defineProperty(PhysicsImpostor.prototype, "mass", {
  82370. get: function () {
  82371. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyMass(this) : 0;
  82372. },
  82373. set: function (value) {
  82374. this.setMass(value);
  82375. },
  82376. enumerable: true,
  82377. configurable: true
  82378. });
  82379. Object.defineProperty(PhysicsImpostor.prototype, "friction", {
  82380. get: function () {
  82381. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyFriction(this) : 0;
  82382. },
  82383. set: function (value) {
  82384. if (!this._physicsEngine) {
  82385. return;
  82386. }
  82387. this._physicsEngine.getPhysicsPlugin().setBodyFriction(this, value);
  82388. },
  82389. enumerable: true,
  82390. configurable: true
  82391. });
  82392. Object.defineProperty(PhysicsImpostor.prototype, "restitution", {
  82393. get: function () {
  82394. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyRestitution(this) : 0;
  82395. },
  82396. set: function (value) {
  82397. if (!this._physicsEngine) {
  82398. return;
  82399. }
  82400. this._physicsEngine.getPhysicsPlugin().setBodyRestitution(this, value);
  82401. },
  82402. enumerable: true,
  82403. configurable: true
  82404. });
  82405. /**
  82406. * This function will completly initialize this impostor.
  82407. * It will create a new body - but only if this mesh has no parent.
  82408. * If it has, this impostor will not be used other than to define the impostor
  82409. * of the child mesh.
  82410. */
  82411. PhysicsImpostor.prototype._init = function () {
  82412. if (!this._physicsEngine) {
  82413. return;
  82414. }
  82415. this._physicsEngine.removeImpostor(this);
  82416. this.physicsBody = null;
  82417. this._parent = this._parent || this._getPhysicsParent();
  82418. if (!this._isDisposed && (!this.parent || this._options.ignoreParent)) {
  82419. this._physicsEngine.addImpostor(this);
  82420. }
  82421. };
  82422. PhysicsImpostor.prototype._getPhysicsParent = function () {
  82423. if (this.object.parent instanceof BABYLON.AbstractMesh) {
  82424. var parentMesh = this.object.parent;
  82425. return parentMesh.physicsImpostor;
  82426. }
  82427. return null;
  82428. };
  82429. /**
  82430. * Should a new body be generated.
  82431. */
  82432. PhysicsImpostor.prototype.isBodyInitRequired = function () {
  82433. return this._bodyUpdateRequired || (!this._physicsBody && !this._parent);
  82434. };
  82435. PhysicsImpostor.prototype.setScalingUpdated = function (updated) {
  82436. this.forceUpdate();
  82437. };
  82438. /**
  82439. * Force a regeneration of this or the parent's impostor's body.
  82440. * Use under cautious - This will remove all joints already implemented.
  82441. */
  82442. PhysicsImpostor.prototype.forceUpdate = function () {
  82443. this._init();
  82444. if (this.parent && !this._options.ignoreParent) {
  82445. this.parent.forceUpdate();
  82446. }
  82447. };
  82448. Object.defineProperty(PhysicsImpostor.prototype, "physicsBody", {
  82449. /*public get mesh(): AbstractMesh {
  82450. return this._mesh;
  82451. }*/
  82452. /**
  82453. * Gets the body that holds this impostor. Either its own, or its parent.
  82454. */
  82455. get: function () {
  82456. return (this._parent && !this._options.ignoreParent) ? this._parent.physicsBody : this._physicsBody;
  82457. },
  82458. /**
  82459. * Set the physics body. Used mainly by the physics engine/plugin
  82460. */
  82461. set: function (physicsBody) {
  82462. if (this._physicsBody && this._physicsEngine) {
  82463. this._physicsEngine.getPhysicsPlugin().removePhysicsBody(this);
  82464. }
  82465. this._physicsBody = physicsBody;
  82466. this.resetUpdateFlags();
  82467. },
  82468. enumerable: true,
  82469. configurable: true
  82470. });
  82471. Object.defineProperty(PhysicsImpostor.prototype, "parent", {
  82472. get: function () {
  82473. return !this._options.ignoreParent && this._parent ? this._parent : null;
  82474. },
  82475. set: function (value) {
  82476. this._parent = value;
  82477. },
  82478. enumerable: true,
  82479. configurable: true
  82480. });
  82481. PhysicsImpostor.prototype.resetUpdateFlags = function () {
  82482. this._bodyUpdateRequired = false;
  82483. };
  82484. PhysicsImpostor.prototype.getObjectExtendSize = function () {
  82485. if (this.object.getBoundingInfo) {
  82486. var q = this.object.rotationQuaternion;
  82487. //reset rotation
  82488. this.object.rotationQuaternion = PhysicsImpostor.IDENTITY_QUATERNION;
  82489. //calculate the world matrix with no rotation
  82490. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  82491. var boundingInfo = this.object.getBoundingInfo();
  82492. var size = boundingInfo.boundingBox.extendSizeWorld.scale(2);
  82493. //bring back the rotation
  82494. this.object.rotationQuaternion = q;
  82495. //calculate the world matrix with the new rotation
  82496. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  82497. return size;
  82498. }
  82499. else {
  82500. return PhysicsImpostor.DEFAULT_OBJECT_SIZE;
  82501. }
  82502. };
  82503. PhysicsImpostor.prototype.getObjectCenter = function () {
  82504. if (this.object.getBoundingInfo) {
  82505. var boundingInfo = this.object.getBoundingInfo();
  82506. return boundingInfo.boundingBox.centerWorld;
  82507. }
  82508. else {
  82509. return this.object.position;
  82510. }
  82511. };
  82512. /**
  82513. * Get a specific parametes from the options parameter.
  82514. */
  82515. PhysicsImpostor.prototype.getParam = function (paramName) {
  82516. return this._options[paramName];
  82517. };
  82518. /**
  82519. * Sets a specific parameter in the options given to the physics plugin
  82520. */
  82521. PhysicsImpostor.prototype.setParam = function (paramName, value) {
  82522. this._options[paramName] = value;
  82523. this._bodyUpdateRequired = true;
  82524. };
  82525. /**
  82526. * Specifically change the body's mass option. Won't recreate the physics body object
  82527. */
  82528. PhysicsImpostor.prototype.setMass = function (mass) {
  82529. if (this.getParam("mass") !== mass) {
  82530. this.setParam("mass", mass);
  82531. }
  82532. if (this._physicsEngine) {
  82533. this._physicsEngine.getPhysicsPlugin().setBodyMass(this, mass);
  82534. }
  82535. };
  82536. PhysicsImpostor.prototype.getLinearVelocity = function () {
  82537. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getLinearVelocity(this) : BABYLON.Vector3.Zero();
  82538. };
  82539. PhysicsImpostor.prototype.setLinearVelocity = function (velocity) {
  82540. if (this._physicsEngine) {
  82541. this._physicsEngine.getPhysicsPlugin().setLinearVelocity(this, velocity);
  82542. }
  82543. };
  82544. PhysicsImpostor.prototype.getAngularVelocity = function () {
  82545. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getAngularVelocity(this) : BABYLON.Vector3.Zero();
  82546. };
  82547. PhysicsImpostor.prototype.setAngularVelocity = function (velocity) {
  82548. if (this._physicsEngine) {
  82549. this._physicsEngine.getPhysicsPlugin().setAngularVelocity(this, velocity);
  82550. }
  82551. };
  82552. /**
  82553. * Execute a function with the physics plugin native code.
  82554. * Provide a function the will have two variables - the world object and the physics body object.
  82555. */
  82556. PhysicsImpostor.prototype.executeNativeFunction = function (func) {
  82557. if (this._physicsEngine) {
  82558. func(this._physicsEngine.getPhysicsPlugin().world, this.physicsBody);
  82559. }
  82560. };
  82561. /**
  82562. * Register a function that will be executed before the physics world is stepping forward.
  82563. */
  82564. PhysicsImpostor.prototype.registerBeforePhysicsStep = function (func) {
  82565. this._onBeforePhysicsStepCallbacks.push(func);
  82566. };
  82567. PhysicsImpostor.prototype.unregisterBeforePhysicsStep = function (func) {
  82568. var index = this._onBeforePhysicsStepCallbacks.indexOf(func);
  82569. if (index > -1) {
  82570. this._onBeforePhysicsStepCallbacks.splice(index, 1);
  82571. }
  82572. else {
  82573. BABYLON.Tools.Warn("Function to remove was not found");
  82574. }
  82575. };
  82576. /**
  82577. * Register a function that will be executed after the physics step
  82578. */
  82579. PhysicsImpostor.prototype.registerAfterPhysicsStep = function (func) {
  82580. this._onAfterPhysicsStepCallbacks.push(func);
  82581. };
  82582. PhysicsImpostor.prototype.unregisterAfterPhysicsStep = function (func) {
  82583. var index = this._onAfterPhysicsStepCallbacks.indexOf(func);
  82584. if (index > -1) {
  82585. this._onAfterPhysicsStepCallbacks.splice(index, 1);
  82586. }
  82587. else {
  82588. BABYLON.Tools.Warn("Function to remove was not found");
  82589. }
  82590. };
  82591. /**
  82592. * register a function that will be executed when this impostor collides against a different body.
  82593. */
  82594. PhysicsImpostor.prototype.registerOnPhysicsCollide = function (collideAgainst, func) {
  82595. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  82596. this._onPhysicsCollideCallbacks.push({ callback: func, otherImpostors: collidedAgainstList });
  82597. };
  82598. PhysicsImpostor.prototype.unregisterOnPhysicsCollide = function (collideAgainst, func) {
  82599. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  82600. var index = -1;
  82601. var found = this._onPhysicsCollideCallbacks.some(function (cbDef, idx) {
  82602. if (cbDef.callback === func && cbDef.otherImpostors.length === collidedAgainstList.length) {
  82603. // chcek the arrays match
  82604. var sameList = cbDef.otherImpostors.every(function (impostor) {
  82605. return collidedAgainstList.indexOf(impostor) > -1;
  82606. });
  82607. if (sameList) {
  82608. index = idx;
  82609. }
  82610. return sameList;
  82611. }
  82612. return false;
  82613. });
  82614. if (found) {
  82615. this._onPhysicsCollideCallbacks.splice(index, 1);
  82616. }
  82617. else {
  82618. BABYLON.Tools.Warn("Function to remove was not found");
  82619. }
  82620. };
  82621. PhysicsImpostor.prototype.getParentsRotation = function () {
  82622. var parent = this.object.parent;
  82623. this._tmpQuat.copyFromFloats(0, 0, 0, 1);
  82624. while (parent) {
  82625. if (parent.rotationQuaternion) {
  82626. this._tmpQuat2.copyFrom(parent.rotationQuaternion);
  82627. }
  82628. else {
  82629. BABYLON.Quaternion.RotationYawPitchRollToRef(parent.rotation.y, parent.rotation.x, parent.rotation.z, this._tmpQuat2);
  82630. }
  82631. this._tmpQuat.multiplyToRef(this._tmpQuat2, this._tmpQuat);
  82632. parent = parent.parent;
  82633. }
  82634. return this._tmpQuat;
  82635. };
  82636. /**
  82637. * Apply a force
  82638. */
  82639. PhysicsImpostor.prototype.applyForce = function (force, contactPoint) {
  82640. if (this._physicsEngine) {
  82641. this._physicsEngine.getPhysicsPlugin().applyForce(this, force, contactPoint);
  82642. }
  82643. return this;
  82644. };
  82645. /**
  82646. * Apply an impulse
  82647. */
  82648. PhysicsImpostor.prototype.applyImpulse = function (force, contactPoint) {
  82649. if (this._physicsEngine) {
  82650. this._physicsEngine.getPhysicsPlugin().applyImpulse(this, force, contactPoint);
  82651. }
  82652. return this;
  82653. };
  82654. /**
  82655. * A help function to create a joint.
  82656. */
  82657. PhysicsImpostor.prototype.createJoint = function (otherImpostor, jointType, jointData) {
  82658. var joint = new BABYLON.PhysicsJoint(jointType, jointData);
  82659. this.addJoint(otherImpostor, joint);
  82660. return this;
  82661. };
  82662. /**
  82663. * Add a joint to this impostor with a different impostor.
  82664. */
  82665. PhysicsImpostor.prototype.addJoint = function (otherImpostor, joint) {
  82666. this._joints.push({
  82667. otherImpostor: otherImpostor,
  82668. joint: joint
  82669. });
  82670. if (this._physicsEngine) {
  82671. this._physicsEngine.addJoint(this, otherImpostor, joint);
  82672. }
  82673. return this;
  82674. };
  82675. /**
  82676. * Will keep this body still, in a sleep mode.
  82677. */
  82678. PhysicsImpostor.prototype.sleep = function () {
  82679. if (this._physicsEngine) {
  82680. this._physicsEngine.getPhysicsPlugin().sleepBody(this);
  82681. }
  82682. return this;
  82683. };
  82684. /**
  82685. * Wake the body up.
  82686. */
  82687. PhysicsImpostor.prototype.wakeUp = function () {
  82688. if (this._physicsEngine) {
  82689. this._physicsEngine.getPhysicsPlugin().wakeUpBody(this);
  82690. }
  82691. return this;
  82692. };
  82693. PhysicsImpostor.prototype.clone = function (newObject) {
  82694. if (!newObject)
  82695. return null;
  82696. return new PhysicsImpostor(newObject, this.type, this._options, this._scene);
  82697. };
  82698. PhysicsImpostor.prototype.dispose = function ( /*disposeChildren: boolean = true*/) {
  82699. var _this = this;
  82700. //no dispose if no physics engine is available.
  82701. if (!this._physicsEngine) {
  82702. return;
  82703. }
  82704. this._joints.forEach(function (j) {
  82705. if (_this._physicsEngine) {
  82706. _this._physicsEngine.removeJoint(_this, j.otherImpostor, j.joint);
  82707. }
  82708. });
  82709. //dispose the physics body
  82710. this._physicsEngine.removeImpostor(this);
  82711. if (this.parent) {
  82712. this.parent.forceUpdate();
  82713. }
  82714. else {
  82715. /*this._object.getChildMeshes().forEach(function(mesh) {
  82716. if (mesh.physicsImpostor) {
  82717. if (disposeChildren) {
  82718. mesh.physicsImpostor.dispose();
  82719. mesh.physicsImpostor = null;
  82720. }
  82721. }
  82722. })*/
  82723. }
  82724. this._isDisposed = true;
  82725. };
  82726. PhysicsImpostor.prototype.setDeltaPosition = function (position) {
  82727. this._deltaPosition.copyFrom(position);
  82728. };
  82729. PhysicsImpostor.prototype.setDeltaRotation = function (rotation) {
  82730. if (!this._deltaRotation) {
  82731. this._deltaRotation = new BABYLON.Quaternion();
  82732. }
  82733. this._deltaRotation.copyFrom(rotation);
  82734. this._deltaRotationConjugated = this._deltaRotation.conjugate();
  82735. };
  82736. PhysicsImpostor.prototype.getBoxSizeToRef = function (result) {
  82737. if (this._physicsEngine) {
  82738. this._physicsEngine.getPhysicsPlugin().getBoxSizeToRef(this, result);
  82739. }
  82740. return this;
  82741. };
  82742. PhysicsImpostor.prototype.getRadius = function () {
  82743. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getRadius(this) : 0;
  82744. };
  82745. /**
  82746. * Sync a bone with this impostor
  82747. * @param bone The bone to sync to the impostor.
  82748. * @param boneMesh The mesh that the bone is influencing.
  82749. * @param jointPivot The pivot of the joint / bone in local space.
  82750. * @param distToJoint Optional distance from the impostor to the joint.
  82751. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  82752. */
  82753. PhysicsImpostor.prototype.syncBoneWithImpostor = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation) {
  82754. var tempVec = PhysicsImpostor._tmpVecs[0];
  82755. var mesh = this.object;
  82756. if (mesh.rotationQuaternion) {
  82757. if (adjustRotation) {
  82758. var tempQuat = PhysicsImpostor._tmpQuat;
  82759. mesh.rotationQuaternion.multiplyToRef(adjustRotation, tempQuat);
  82760. bone.setRotationQuaternion(tempQuat, BABYLON.Space.WORLD, boneMesh);
  82761. }
  82762. else {
  82763. bone.setRotationQuaternion(mesh.rotationQuaternion, BABYLON.Space.WORLD, boneMesh);
  82764. }
  82765. }
  82766. tempVec.x = 0;
  82767. tempVec.y = 0;
  82768. tempVec.z = 0;
  82769. if (jointPivot) {
  82770. tempVec.x = jointPivot.x;
  82771. tempVec.y = jointPivot.y;
  82772. tempVec.z = jointPivot.z;
  82773. bone.getDirectionToRef(tempVec, boneMesh, tempVec);
  82774. if (distToJoint === undefined || distToJoint === null) {
  82775. distToJoint = jointPivot.length();
  82776. }
  82777. tempVec.x *= distToJoint;
  82778. tempVec.y *= distToJoint;
  82779. tempVec.z *= distToJoint;
  82780. }
  82781. if (bone.getParent()) {
  82782. tempVec.addInPlace(mesh.getAbsolutePosition());
  82783. bone.setAbsolutePosition(tempVec, boneMesh);
  82784. }
  82785. else {
  82786. boneMesh.setAbsolutePosition(mesh.getAbsolutePosition());
  82787. boneMesh.position.x -= tempVec.x;
  82788. boneMesh.position.y -= tempVec.y;
  82789. boneMesh.position.z -= tempVec.z;
  82790. }
  82791. };
  82792. /**
  82793. * Sync impostor to a bone
  82794. * @param bone The bone that the impostor will be synced to.
  82795. * @param boneMesh The mesh that the bone is influencing.
  82796. * @param jointPivot The pivot of the joint / bone in local space.
  82797. * @param distToJoint Optional distance from the impostor to the joint.
  82798. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  82799. * @param boneAxis Optional vector3 axis the bone is aligned with
  82800. */
  82801. PhysicsImpostor.prototype.syncImpostorWithBone = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation, boneAxis) {
  82802. var mesh = this.object;
  82803. if (mesh.rotationQuaternion) {
  82804. if (adjustRotation) {
  82805. var tempQuat = PhysicsImpostor._tmpQuat;
  82806. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, tempQuat);
  82807. tempQuat.multiplyToRef(adjustRotation, mesh.rotationQuaternion);
  82808. }
  82809. else {
  82810. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, mesh.rotationQuaternion);
  82811. }
  82812. }
  82813. var pos = PhysicsImpostor._tmpVecs[0];
  82814. var boneDir = PhysicsImpostor._tmpVecs[1];
  82815. if (!boneAxis) {
  82816. boneAxis = PhysicsImpostor._tmpVecs[2];
  82817. boneAxis.x = 0;
  82818. boneAxis.y = 1;
  82819. boneAxis.z = 0;
  82820. }
  82821. bone.getDirectionToRef(boneAxis, boneMesh, boneDir);
  82822. bone.getAbsolutePositionToRef(boneMesh, pos);
  82823. if ((distToJoint === undefined || distToJoint === null) && jointPivot) {
  82824. distToJoint = jointPivot.length();
  82825. }
  82826. if (distToJoint !== undefined && distToJoint !== null) {
  82827. pos.x += boneDir.x * distToJoint;
  82828. pos.y += boneDir.y * distToJoint;
  82829. pos.z += boneDir.z * distToJoint;
  82830. }
  82831. mesh.setAbsolutePosition(pos);
  82832. };
  82833. PhysicsImpostor.DEFAULT_OBJECT_SIZE = new BABYLON.Vector3(1, 1, 1);
  82834. PhysicsImpostor.IDENTITY_QUATERNION = BABYLON.Quaternion.Identity();
  82835. PhysicsImpostor._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  82836. PhysicsImpostor._tmpQuat = BABYLON.Quaternion.Identity();
  82837. //Impostor types
  82838. PhysicsImpostor.NoImpostor = 0;
  82839. PhysicsImpostor.SphereImpostor = 1;
  82840. PhysicsImpostor.BoxImpostor = 2;
  82841. PhysicsImpostor.PlaneImpostor = 3;
  82842. PhysicsImpostor.MeshImpostor = 4;
  82843. PhysicsImpostor.CylinderImpostor = 7;
  82844. PhysicsImpostor.ParticleImpostor = 8;
  82845. PhysicsImpostor.HeightmapImpostor = 9;
  82846. return PhysicsImpostor;
  82847. }());
  82848. BABYLON.PhysicsImpostor = PhysicsImpostor;
  82849. })(BABYLON || (BABYLON = {}));
  82850. //# sourceMappingURL=babylon.physicsImpostor.js.map
  82851. var BABYLON;
  82852. (function (BABYLON) {
  82853. var PhysicsEngine = /** @class */ (function () {
  82854. function PhysicsEngine(gravity, _physicsPlugin) {
  82855. if (_physicsPlugin === void 0) { _physicsPlugin = new BABYLON.CannonJSPlugin(); }
  82856. this._physicsPlugin = _physicsPlugin;
  82857. //new methods and parameters
  82858. this._impostors = [];
  82859. this._joints = [];
  82860. if (!this._physicsPlugin.isSupported()) {
  82861. throw new Error("Physics Engine " + this._physicsPlugin.name + " cannot be found. "
  82862. + "Please make sure it is included.");
  82863. }
  82864. gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);
  82865. this.setGravity(gravity);
  82866. this.setTimeStep();
  82867. }
  82868. PhysicsEngine.prototype.setGravity = function (gravity) {
  82869. this.gravity = gravity;
  82870. this._physicsPlugin.setGravity(this.gravity);
  82871. };
  82872. /**
  82873. * Set the time step of the physics engine.
  82874. * default is 1/60.
  82875. * To slow it down, enter 1/600 for example.
  82876. * To speed it up, 1/30
  82877. * @param {number} newTimeStep the new timestep to apply to this world.
  82878. */
  82879. PhysicsEngine.prototype.setTimeStep = function (newTimeStep) {
  82880. if (newTimeStep === void 0) { newTimeStep = 1 / 60; }
  82881. this._physicsPlugin.setTimeStep(newTimeStep);
  82882. };
  82883. /**
  82884. * Get the time step of the physics engine.
  82885. */
  82886. PhysicsEngine.prototype.getTimeStep = function () {
  82887. return this._physicsPlugin.getTimeStep();
  82888. };
  82889. PhysicsEngine.prototype.dispose = function () {
  82890. this._impostors.forEach(function (impostor) {
  82891. impostor.dispose();
  82892. });
  82893. this._physicsPlugin.dispose();
  82894. };
  82895. PhysicsEngine.prototype.getPhysicsPluginName = function () {
  82896. return this._physicsPlugin.name;
  82897. };
  82898. /**
  82899. * Adding a new impostor for the impostor tracking.
  82900. * This will be done by the impostor itself.
  82901. * @param {PhysicsImpostor} impostor the impostor to add
  82902. */
  82903. PhysicsEngine.prototype.addImpostor = function (impostor) {
  82904. impostor.uniqueId = this._impostors.push(impostor);
  82905. //if no parent, generate the body
  82906. if (!impostor.parent) {
  82907. this._physicsPlugin.generatePhysicsBody(impostor);
  82908. }
  82909. };
  82910. /**
  82911. * Remove an impostor from the engine.
  82912. * This impostor and its mesh will not longer be updated by the physics engine.
  82913. * @param {PhysicsImpostor} impostor the impostor to remove
  82914. */
  82915. PhysicsEngine.prototype.removeImpostor = function (impostor) {
  82916. var index = this._impostors.indexOf(impostor);
  82917. if (index > -1) {
  82918. var removed = this._impostors.splice(index, 1);
  82919. //Is it needed?
  82920. if (removed.length) {
  82921. //this will also remove it from the world.
  82922. removed[0].physicsBody = null;
  82923. }
  82924. }
  82925. };
  82926. /**
  82927. * Add a joint to the physics engine
  82928. * @param {PhysicsImpostor} mainImpostor the main impostor to which the joint is added.
  82929. * @param {PhysicsImpostor} connectedImpostor the impostor that is connected to the main impostor using this joint
  82930. * @param {PhysicsJoint} the joint that will connect both impostors.
  82931. */
  82932. PhysicsEngine.prototype.addJoint = function (mainImpostor, connectedImpostor, joint) {
  82933. var impostorJoint = {
  82934. mainImpostor: mainImpostor,
  82935. connectedImpostor: connectedImpostor,
  82936. joint: joint
  82937. };
  82938. joint.physicsPlugin = this._physicsPlugin;
  82939. this._joints.push(impostorJoint);
  82940. this._physicsPlugin.generateJoint(impostorJoint);
  82941. };
  82942. PhysicsEngine.prototype.removeJoint = function (mainImpostor, connectedImpostor, joint) {
  82943. var matchingJoints = this._joints.filter(function (impostorJoint) {
  82944. return (impostorJoint.connectedImpostor === connectedImpostor
  82945. && impostorJoint.joint === joint
  82946. && impostorJoint.mainImpostor === mainImpostor);
  82947. });
  82948. if (matchingJoints.length) {
  82949. this._physicsPlugin.removeJoint(matchingJoints[0]);
  82950. //TODO remove it from the list as well
  82951. }
  82952. };
  82953. /**
  82954. * Called by the scene. no need to call it.
  82955. */
  82956. PhysicsEngine.prototype._step = function (delta) {
  82957. var _this = this;
  82958. //check if any mesh has no body / requires an update
  82959. this._impostors.forEach(function (impostor) {
  82960. if (impostor.isBodyInitRequired()) {
  82961. _this._physicsPlugin.generatePhysicsBody(impostor);
  82962. }
  82963. });
  82964. if (delta > 0.1) {
  82965. delta = 0.1;
  82966. }
  82967. else if (delta <= 0) {
  82968. delta = 1.0 / 60.0;
  82969. }
  82970. this._physicsPlugin.executeStep(delta, this._impostors);
  82971. };
  82972. PhysicsEngine.prototype.getPhysicsPlugin = function () {
  82973. return this._physicsPlugin;
  82974. };
  82975. PhysicsEngine.prototype.getImpostors = function () {
  82976. return this._impostors;
  82977. };
  82978. PhysicsEngine.prototype.getImpostorForPhysicsObject = function (object) {
  82979. for (var i = 0; i < this._impostors.length; ++i) {
  82980. if (this._impostors[i].object === object) {
  82981. return this._impostors[i];
  82982. }
  82983. }
  82984. return null;
  82985. };
  82986. PhysicsEngine.prototype.getImpostorWithPhysicsBody = function (body) {
  82987. for (var i = 0; i < this._impostors.length; ++i) {
  82988. if (this._impostors[i].physicsBody === body) {
  82989. return this._impostors[i];
  82990. }
  82991. }
  82992. return null;
  82993. };
  82994. // Statics
  82995. PhysicsEngine.Epsilon = 0.001;
  82996. return PhysicsEngine;
  82997. }());
  82998. BABYLON.PhysicsEngine = PhysicsEngine;
  82999. })(BABYLON || (BABYLON = {}));
  83000. //# sourceMappingURL=babylon.physicsEngine.js.map
  83001. var BABYLON;
  83002. (function (BABYLON) {
  83003. var PhysicsHelper = /** @class */ (function () {
  83004. function PhysicsHelper(scene) {
  83005. this._scene = scene;
  83006. this._physicsEngine = this._scene.getPhysicsEngine();
  83007. if (!this._physicsEngine) {
  83008. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you can use the methods.');
  83009. }
  83010. }
  83011. /**
  83012. * @param {Vector3} origin the origin of the explosion
  83013. * @param {number} radius the explosion radius
  83014. * @param {number} strength the explosion strength
  83015. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  83016. */
  83017. PhysicsHelper.prototype.applyRadialExplosionImpulse = function (origin, radius, strength, falloff) {
  83018. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  83019. if (!this._physicsEngine) {
  83020. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call this method.');
  83021. return null;
  83022. }
  83023. var impostors = this._physicsEngine.getImpostors();
  83024. if (impostors.length === 0) {
  83025. return null;
  83026. }
  83027. var event = new PhysicsRadialExplosionEvent(this._scene);
  83028. impostors.forEach(function (impostor) {
  83029. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  83030. if (!impostorForceAndContactPoint) {
  83031. return;
  83032. }
  83033. impostor.applyImpulse(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  83034. });
  83035. event.dispose(false);
  83036. return event;
  83037. };
  83038. /**
  83039. * @param {Vector3} origin the origin of the explosion
  83040. * @param {number} radius the explosion radius
  83041. * @param {number} strength the explosion strength
  83042. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  83043. */
  83044. PhysicsHelper.prototype.applyRadialExplosionForce = function (origin, radius, strength, falloff) {
  83045. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  83046. if (!this._physicsEngine) {
  83047. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  83048. return null;
  83049. }
  83050. var impostors = this._physicsEngine.getImpostors();
  83051. if (impostors.length === 0) {
  83052. return null;
  83053. }
  83054. var event = new PhysicsRadialExplosionEvent(this._scene);
  83055. impostors.forEach(function (impostor) {
  83056. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  83057. if (!impostorForceAndContactPoint) {
  83058. return;
  83059. }
  83060. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  83061. });
  83062. event.dispose(false);
  83063. return event;
  83064. };
  83065. /**
  83066. * @param {Vector3} origin the origin of the explosion
  83067. * @param {number} radius the explosion radius
  83068. * @param {number} strength the explosion strength
  83069. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  83070. */
  83071. PhysicsHelper.prototype.gravitationalField = function (origin, radius, strength, falloff) {
  83072. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  83073. if (!this._physicsEngine) {
  83074. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  83075. return null;
  83076. }
  83077. var impostors = this._physicsEngine.getImpostors();
  83078. if (impostors.length === 0) {
  83079. return null;
  83080. }
  83081. var event = new PhysicsGravitationalFieldEvent(this, this._scene, origin, radius, strength, falloff);
  83082. event.dispose(false);
  83083. return event;
  83084. };
  83085. /**
  83086. * @param {Vector3} origin the origin of the updraft
  83087. * @param {number} radius the radius of the updraft
  83088. * @param {number} strength the strength of the updraft
  83089. * @param {number} height the height of the updraft
  83090. * @param {PhysicsUpdraftMode} updraftMode possible options: Center & Perpendicular. Defaults to Center
  83091. */
  83092. PhysicsHelper.prototype.updraft = function (origin, radius, strength, height, updraftMode) {
  83093. if (updraftMode === void 0) { updraftMode = PhysicsUpdraftMode.Center; }
  83094. if (!this._physicsEngine) {
  83095. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  83096. return null;
  83097. }
  83098. if (this._physicsEngine.getImpostors().length === 0) {
  83099. return null;
  83100. }
  83101. var event = new PhysicsUpdraftEvent(this._scene, origin, radius, strength, height, updraftMode);
  83102. event.dispose(false);
  83103. return event;
  83104. };
  83105. /**
  83106. * @param {Vector3} origin the of the vortex
  83107. * @param {number} radius the radius of the vortex
  83108. * @param {number} strength the strength of the vortex
  83109. * @param {number} height the height of the vortex
  83110. */
  83111. PhysicsHelper.prototype.vortex = function (origin, radius, strength, height) {
  83112. if (!this._physicsEngine) {
  83113. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  83114. return null;
  83115. }
  83116. if (this._physicsEngine.getImpostors().length === 0) {
  83117. return null;
  83118. }
  83119. var event = new PhysicsVortexEvent(this._scene, origin, radius, strength, height);
  83120. event.dispose(false);
  83121. return event;
  83122. };
  83123. return PhysicsHelper;
  83124. }());
  83125. BABYLON.PhysicsHelper = PhysicsHelper;
  83126. /***** Radial explosion *****/
  83127. var PhysicsRadialExplosionEvent = /** @class */ (function () {
  83128. function PhysicsRadialExplosionEvent(scene) {
  83129. this._sphereOptions = { segments: 32, diameter: 1 }; // TODO: make configurable
  83130. this._rays = [];
  83131. this._dataFetched = false; // check if the data has been fetched. If not, do cleanup
  83132. this._scene = scene;
  83133. }
  83134. /**
  83135. * Returns the data related to the radial explosion event (sphere & rays).
  83136. * @returns {PhysicsRadialExplosionEventData}
  83137. */
  83138. PhysicsRadialExplosionEvent.prototype.getData = function () {
  83139. this._dataFetched = true;
  83140. return {
  83141. sphere: this._sphere,
  83142. rays: this._rays,
  83143. };
  83144. };
  83145. /**
  83146. * Returns the force and contact point of the impostor or false, if the impostor is not affected by the force/impulse.
  83147. * @param impostor
  83148. * @param {Vector3} origin the origin of the explosion
  83149. * @param {number} radius the explosion radius
  83150. * @param {number} strength the explosion strength
  83151. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear
  83152. * @returns {Nullable<PhysicsForceAndContactPoint>}
  83153. */
  83154. PhysicsRadialExplosionEvent.prototype.getImpostorForceAndContactPoint = function (impostor, origin, radius, strength, falloff) {
  83155. if (impostor.mass === 0) {
  83156. return null;
  83157. }
  83158. if (!this._intersectsWithSphere(impostor, origin, radius)) {
  83159. return null;
  83160. }
  83161. if (impostor.object.getClassName() !== 'Mesh' && impostor.object.getClassName() !== 'InstancedMesh') {
  83162. return null;
  83163. }
  83164. var impostorObjectCenter = impostor.getObjectCenter();
  83165. var direction = impostorObjectCenter.subtract(origin);
  83166. var ray = new BABYLON.Ray(origin, direction, radius);
  83167. this._rays.push(ray);
  83168. var hit = ray.intersectsMesh(impostor.object);
  83169. var contactPoint = hit.pickedPoint;
  83170. if (!contactPoint) {
  83171. return null;
  83172. }
  83173. var distanceFromOrigin = BABYLON.Vector3.Distance(origin, contactPoint);
  83174. if (distanceFromOrigin > radius) {
  83175. return null;
  83176. }
  83177. var multiplier = falloff === PhysicsRadialImpulseFalloff.Constant
  83178. ? strength
  83179. : strength * (1 - (distanceFromOrigin / radius));
  83180. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  83181. return { force: force, contactPoint: contactPoint };
  83182. };
  83183. /**
  83184. * Disposes the sphere.
  83185. * @param {bolean} force
  83186. */
  83187. PhysicsRadialExplosionEvent.prototype.dispose = function (force) {
  83188. var _this = this;
  83189. if (force === void 0) { force = true; }
  83190. if (force) {
  83191. this._sphere.dispose();
  83192. }
  83193. else {
  83194. setTimeout(function () {
  83195. if (!_this._dataFetched) {
  83196. _this._sphere.dispose();
  83197. }
  83198. }, 0);
  83199. }
  83200. };
  83201. /*** Helpers ***/
  83202. PhysicsRadialExplosionEvent.prototype._prepareSphere = function () {
  83203. if (!this._sphere) {
  83204. this._sphere = BABYLON.MeshBuilder.CreateSphere("radialExplosionEventSphere", this._sphereOptions, this._scene);
  83205. this._sphere.isVisible = false;
  83206. }
  83207. };
  83208. PhysicsRadialExplosionEvent.prototype._intersectsWithSphere = function (impostor, origin, radius) {
  83209. var impostorObject = impostor.object;
  83210. this._prepareSphere();
  83211. this._sphere.position = origin;
  83212. this._sphere.scaling = new BABYLON.Vector3(radius * 2, radius * 2, radius * 2);
  83213. this._sphere._updateBoundingInfo();
  83214. this._sphere.computeWorldMatrix(true);
  83215. return this._sphere.intersectsMesh(impostorObject, true);
  83216. };
  83217. return PhysicsRadialExplosionEvent;
  83218. }());
  83219. BABYLON.PhysicsRadialExplosionEvent = PhysicsRadialExplosionEvent;
  83220. /***** Gravitational Field *****/
  83221. var PhysicsGravitationalFieldEvent = /** @class */ (function () {
  83222. function PhysicsGravitationalFieldEvent(physicsHelper, scene, origin, radius, strength, falloff) {
  83223. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  83224. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  83225. this._physicsHelper = physicsHelper;
  83226. this._scene = scene;
  83227. this._origin = origin;
  83228. this._radius = radius;
  83229. this._strength = strength;
  83230. this._falloff = falloff;
  83231. this._tickCallback = this._tick.bind(this);
  83232. }
  83233. /**
  83234. * Returns the data related to the gravitational field event (sphere).
  83235. * @returns {PhysicsGravitationalFieldEventData}
  83236. */
  83237. PhysicsGravitationalFieldEvent.prototype.getData = function () {
  83238. this._dataFetched = true;
  83239. return {
  83240. sphere: this._sphere,
  83241. };
  83242. };
  83243. /**
  83244. * Enables the gravitational field.
  83245. */
  83246. PhysicsGravitationalFieldEvent.prototype.enable = function () {
  83247. this._tickCallback.call(this);
  83248. this._scene.registerBeforeRender(this._tickCallback);
  83249. };
  83250. /**
  83251. * Disables the gravitational field.
  83252. */
  83253. PhysicsGravitationalFieldEvent.prototype.disable = function () {
  83254. this._scene.unregisterBeforeRender(this._tickCallback);
  83255. };
  83256. /**
  83257. * Disposes the sphere.
  83258. * @param {bolean} force
  83259. */
  83260. PhysicsGravitationalFieldEvent.prototype.dispose = function (force) {
  83261. var _this = this;
  83262. if (force === void 0) { force = true; }
  83263. if (force) {
  83264. this._sphere.dispose();
  83265. }
  83266. else {
  83267. setTimeout(function () {
  83268. if (!_this._dataFetched) {
  83269. _this._sphere.dispose();
  83270. }
  83271. }, 0);
  83272. }
  83273. };
  83274. PhysicsGravitationalFieldEvent.prototype._tick = function () {
  83275. // Since the params won't change, we fetch the event only once
  83276. if (this._sphere) {
  83277. this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  83278. }
  83279. else {
  83280. var radialExplosionEvent = this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  83281. if (radialExplosionEvent) {
  83282. this._sphere = radialExplosionEvent.getData().sphere.clone('radialExplosionEventSphereClone');
  83283. }
  83284. }
  83285. };
  83286. return PhysicsGravitationalFieldEvent;
  83287. }());
  83288. BABYLON.PhysicsGravitationalFieldEvent = PhysicsGravitationalFieldEvent;
  83289. /***** Updraft *****/
  83290. var PhysicsUpdraftEvent = /** @class */ (function () {
  83291. function PhysicsUpdraftEvent(_scene, _origin, _radius, _strength, _height, _updraftMode) {
  83292. this._scene = _scene;
  83293. this._origin = _origin;
  83294. this._radius = _radius;
  83295. this._strength = _strength;
  83296. this._height = _height;
  83297. this._updraftMode = _updraftMode;
  83298. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  83299. this._originDirection = BABYLON.Vector3.Zero(); // used if the updraftMode is perpendicular
  83300. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  83301. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  83302. this._physicsEngine = this._scene.getPhysicsEngine();
  83303. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  83304. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  83305. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  83306. this._originDirection = this._origin.subtract(this._originTop).normalize();
  83307. }
  83308. this._tickCallback = this._tick.bind(this);
  83309. }
  83310. /**
  83311. * Returns the data related to the updraft event (cylinder).
  83312. * @returns {PhysicsUpdraftEventData}
  83313. */
  83314. PhysicsUpdraftEvent.prototype.getData = function () {
  83315. this._dataFetched = true;
  83316. return {
  83317. cylinder: this._cylinder,
  83318. };
  83319. };
  83320. /**
  83321. * Enables the updraft.
  83322. */
  83323. PhysicsUpdraftEvent.prototype.enable = function () {
  83324. this._tickCallback.call(this);
  83325. this._scene.registerBeforeRender(this._tickCallback);
  83326. };
  83327. /**
  83328. * Disables the cortex.
  83329. */
  83330. PhysicsUpdraftEvent.prototype.disable = function () {
  83331. this._scene.unregisterBeforeRender(this._tickCallback);
  83332. };
  83333. /**
  83334. * Disposes the sphere.
  83335. * @param {bolean} force
  83336. */
  83337. PhysicsUpdraftEvent.prototype.dispose = function (force) {
  83338. var _this = this;
  83339. if (force === void 0) { force = true; }
  83340. if (force) {
  83341. this._cylinder.dispose();
  83342. }
  83343. else {
  83344. setTimeout(function () {
  83345. if (!_this._dataFetched) {
  83346. _this._cylinder.dispose();
  83347. }
  83348. }, 0);
  83349. }
  83350. };
  83351. PhysicsUpdraftEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  83352. if (impostor.mass === 0) {
  83353. return null;
  83354. }
  83355. if (!this._intersectsWithCylinder(impostor)) {
  83356. return null;
  83357. }
  83358. var impostorObjectCenter = impostor.getObjectCenter();
  83359. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  83360. var direction = this._originDirection;
  83361. }
  83362. else {
  83363. var direction = impostorObjectCenter.subtract(this._originTop);
  83364. }
  83365. var multiplier = this._strength * -1;
  83366. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  83367. return { force: force, contactPoint: impostorObjectCenter };
  83368. };
  83369. PhysicsUpdraftEvent.prototype._tick = function () {
  83370. var _this = this;
  83371. this._physicsEngine.getImpostors().forEach(function (impostor) {
  83372. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  83373. if (!impostorForceAndContactPoint) {
  83374. return;
  83375. }
  83376. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  83377. });
  83378. };
  83379. /*** Helpers ***/
  83380. PhysicsUpdraftEvent.prototype._prepareCylinder = function () {
  83381. if (!this._cylinder) {
  83382. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("updraftEventCylinder", {
  83383. height: this._height,
  83384. diameter: this._radius * 2,
  83385. }, this._scene);
  83386. this._cylinder.isVisible = false;
  83387. }
  83388. };
  83389. PhysicsUpdraftEvent.prototype._intersectsWithCylinder = function (impostor) {
  83390. var impostorObject = impostor.object;
  83391. this._prepareCylinder();
  83392. this._cylinder.position = this._cylinderPosition;
  83393. return this._cylinder.intersectsMesh(impostorObject, true);
  83394. };
  83395. return PhysicsUpdraftEvent;
  83396. }());
  83397. BABYLON.PhysicsUpdraftEvent = PhysicsUpdraftEvent;
  83398. /***** Vortex *****/
  83399. var PhysicsVortexEvent = /** @class */ (function () {
  83400. function PhysicsVortexEvent(_scene, _origin, _radius, _strength, _height) {
  83401. this._scene = _scene;
  83402. this._origin = _origin;
  83403. this._radius = _radius;
  83404. this._strength = _strength;
  83405. this._height = _height;
  83406. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  83407. this._centripetalForceThreshold = 0.7; // at which distance, relative to the radius the centripetal forces should kick in
  83408. this._updraftMultiplier = 0.02;
  83409. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  83410. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  83411. this._physicsEngine = this._scene.getPhysicsEngine();
  83412. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  83413. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  83414. this._tickCallback = this._tick.bind(this);
  83415. }
  83416. /**
  83417. * Returns the data related to the vortex event (cylinder).
  83418. * @returns {PhysicsVortexEventData}
  83419. */
  83420. PhysicsVortexEvent.prototype.getData = function () {
  83421. this._dataFetched = true;
  83422. return {
  83423. cylinder: this._cylinder,
  83424. };
  83425. };
  83426. /**
  83427. * Enables the vortex.
  83428. */
  83429. PhysicsVortexEvent.prototype.enable = function () {
  83430. this._tickCallback.call(this);
  83431. this._scene.registerBeforeRender(this._tickCallback);
  83432. };
  83433. /**
  83434. * Disables the cortex.
  83435. */
  83436. PhysicsVortexEvent.prototype.disable = function () {
  83437. this._scene.unregisterBeforeRender(this._tickCallback);
  83438. };
  83439. /**
  83440. * Disposes the sphere.
  83441. * @param {bolean} force
  83442. */
  83443. PhysicsVortexEvent.prototype.dispose = function (force) {
  83444. var _this = this;
  83445. if (force === void 0) { force = true; }
  83446. if (force) {
  83447. this._cylinder.dispose();
  83448. }
  83449. else {
  83450. setTimeout(function () {
  83451. if (!_this._dataFetched) {
  83452. _this._cylinder.dispose();
  83453. }
  83454. }, 0);
  83455. }
  83456. };
  83457. PhysicsVortexEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  83458. if (impostor.mass === 0) {
  83459. return null;
  83460. }
  83461. if (!this._intersectsWithCylinder(impostor)) {
  83462. return null;
  83463. }
  83464. if (impostor.object.getClassName() !== 'Mesh' && impostor.object.getClassName() !== 'InstancedMesh') {
  83465. return null;
  83466. }
  83467. var impostorObjectCenter = impostor.getObjectCenter();
  83468. 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)
  83469. var originToImpostorDirection = impostorObjectCenter.subtract(originOnPlane);
  83470. var ray = new BABYLON.Ray(originOnPlane, originToImpostorDirection, this._radius);
  83471. var hit = ray.intersectsMesh(impostor.object);
  83472. var contactPoint = hit.pickedPoint;
  83473. if (!contactPoint) {
  83474. return null;
  83475. }
  83476. var absoluteDistanceFromOrigin = hit.distance / this._radius;
  83477. var perpendicularDirection = BABYLON.Vector3.Cross(originOnPlane, impostorObjectCenter).normalize();
  83478. var directionToOrigin = contactPoint.normalize();
  83479. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  83480. directionToOrigin = directionToOrigin.negate();
  83481. }
  83482. // TODO: find a more physically based solution
  83483. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  83484. var forceX = directionToOrigin.x * this._strength / 8;
  83485. var forceY = directionToOrigin.y * this._updraftMultiplier;
  83486. var forceZ = directionToOrigin.z * this._strength / 8;
  83487. }
  83488. else {
  83489. var forceX = (perpendicularDirection.x + directionToOrigin.x) / 2;
  83490. var forceY = this._originTop.y * this._updraftMultiplier;
  83491. var forceZ = (perpendicularDirection.z + directionToOrigin.z) / 2;
  83492. }
  83493. var force = new BABYLON.Vector3(forceX, forceY, forceZ);
  83494. force = force.multiplyByFloats(this._strength, this._strength, this._strength);
  83495. return { force: force, contactPoint: impostorObjectCenter };
  83496. };
  83497. PhysicsVortexEvent.prototype._tick = function () {
  83498. var _this = this;
  83499. this._physicsEngine.getImpostors().forEach(function (impostor) {
  83500. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  83501. if (!impostorForceAndContactPoint) {
  83502. return;
  83503. }
  83504. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  83505. });
  83506. };
  83507. /*** Helpers ***/
  83508. PhysicsVortexEvent.prototype._prepareCylinder = function () {
  83509. if (!this._cylinder) {
  83510. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("vortexEventCylinder", {
  83511. height: this._height,
  83512. diameter: this._radius * 2,
  83513. }, this._scene);
  83514. this._cylinder.isVisible = false;
  83515. }
  83516. };
  83517. PhysicsVortexEvent.prototype._intersectsWithCylinder = function (impostor) {
  83518. var impostorObject = impostor.object;
  83519. this._prepareCylinder();
  83520. this._cylinder.position = this._cylinderPosition;
  83521. return this._cylinder.intersectsMesh(impostorObject, true);
  83522. };
  83523. return PhysicsVortexEvent;
  83524. }());
  83525. BABYLON.PhysicsVortexEvent = PhysicsVortexEvent;
  83526. /***** Enums *****/
  83527. /**
  83528. * The strenght of the force in correspondence to the distance of the affected object
  83529. */
  83530. var PhysicsRadialImpulseFalloff;
  83531. (function (PhysicsRadialImpulseFalloff) {
  83532. /** Defines that impulse is constant in strength across it's whole radius */
  83533. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Constant"] = 0] = "Constant";
  83534. /** DEfines that impulse gets weaker if it's further from the origin */
  83535. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Linear"] = 1] = "Linear";
  83536. })(PhysicsRadialImpulseFalloff = BABYLON.PhysicsRadialImpulseFalloff || (BABYLON.PhysicsRadialImpulseFalloff = {}));
  83537. /**
  83538. * The strenght of the force in correspondence to the distance of the affected object
  83539. */
  83540. var PhysicsUpdraftMode;
  83541. (function (PhysicsUpdraftMode) {
  83542. /** Defines that the upstream forces will pull towards the top center of the cylinder */
  83543. PhysicsUpdraftMode[PhysicsUpdraftMode["Center"] = 0] = "Center";
  83544. /** Defines that once a impostor is inside the cylinder, it will shoot out perpendicular from the ground of the cylinder */
  83545. PhysicsUpdraftMode[PhysicsUpdraftMode["Perpendicular"] = 1] = "Perpendicular";
  83546. })(PhysicsUpdraftMode = BABYLON.PhysicsUpdraftMode || (BABYLON.PhysicsUpdraftMode = {}));
  83547. })(BABYLON || (BABYLON = {}));
  83548. //# sourceMappingURL=babylon.physicsHelper.js.map
  83549. var BABYLON;
  83550. (function (BABYLON) {
  83551. var CannonJSPlugin = /** @class */ (function () {
  83552. function CannonJSPlugin(_useDeltaForWorldStep, iterations) {
  83553. if (_useDeltaForWorldStep === void 0) { _useDeltaForWorldStep = true; }
  83554. if (iterations === void 0) { iterations = 10; }
  83555. this._useDeltaForWorldStep = _useDeltaForWorldStep;
  83556. this.name = "CannonJSPlugin";
  83557. this._physicsMaterials = new Array();
  83558. this._fixedTimeStep = 1 / 60;
  83559. //See https://github.com/schteppe/CANNON.js/blob/gh-pages/demos/collisionFilter.html
  83560. this.BJSCANNON = CANNON;
  83561. this._minus90X = new BABYLON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  83562. this._plus90X = new BABYLON.Quaternion(0.7071067811865475, 0, 0, 0.7071067811865475);
  83563. this._tmpPosition = BABYLON.Vector3.Zero();
  83564. this._tmpDeltaPosition = BABYLON.Vector3.Zero();
  83565. this._tmpUnityRotation = new BABYLON.Quaternion();
  83566. if (!this.isSupported()) {
  83567. BABYLON.Tools.Error("CannonJS is not available. Please make sure you included the js file.");
  83568. return;
  83569. }
  83570. this._extendNamespace();
  83571. this.world = new this.BJSCANNON.World();
  83572. this.world.broadphase = new this.BJSCANNON.NaiveBroadphase();
  83573. this.world.solver.iterations = iterations;
  83574. }
  83575. CannonJSPlugin.prototype.setGravity = function (gravity) {
  83576. this.world.gravity.copy(gravity);
  83577. };
  83578. CannonJSPlugin.prototype.setTimeStep = function (timeStep) {
  83579. this._fixedTimeStep = timeStep;
  83580. };
  83581. CannonJSPlugin.prototype.getTimeStep = function () {
  83582. return this._fixedTimeStep;
  83583. };
  83584. CannonJSPlugin.prototype.executeStep = function (delta, impostors) {
  83585. this.world.step(this._fixedTimeStep, this._useDeltaForWorldStep ? delta : 0, 3);
  83586. };
  83587. CannonJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  83588. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  83589. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  83590. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  83591. };
  83592. CannonJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  83593. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  83594. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  83595. impostor.physicsBody.applyForce(impulse, worldPoint);
  83596. };
  83597. CannonJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  83598. //parent-child relationship. Does this impostor has a parent impostor?
  83599. if (impostor.parent) {
  83600. if (impostor.physicsBody) {
  83601. this.removePhysicsBody(impostor);
  83602. //TODO is that needed?
  83603. impostor.forceUpdate();
  83604. }
  83605. return;
  83606. }
  83607. //should a new body be created for this impostor?
  83608. if (impostor.isBodyInitRequired()) {
  83609. var shape = this._createShape(impostor);
  83610. //unregister events, if body is being changed
  83611. var oldBody = impostor.physicsBody;
  83612. if (oldBody) {
  83613. this.removePhysicsBody(impostor);
  83614. }
  83615. //create the body and material
  83616. var material = this._addMaterial("mat-" + impostor.uniqueId, impostor.getParam("friction"), impostor.getParam("restitution"));
  83617. var bodyCreationObject = {
  83618. mass: impostor.getParam("mass"),
  83619. material: material
  83620. };
  83621. // A simple extend, in case native options were used.
  83622. var nativeOptions = impostor.getParam("nativeOptions");
  83623. for (var key in nativeOptions) {
  83624. if (nativeOptions.hasOwnProperty(key)) {
  83625. bodyCreationObject[key] = nativeOptions[key];
  83626. }
  83627. }
  83628. impostor.physicsBody = new this.BJSCANNON.Body(bodyCreationObject);
  83629. impostor.physicsBody.addEventListener("collide", impostor.onCollide);
  83630. this.world.addEventListener("preStep", impostor.beforeStep);
  83631. this.world.addEventListener("postStep", impostor.afterStep);
  83632. impostor.physicsBody.addShape(shape);
  83633. this.world.add(impostor.physicsBody);
  83634. //try to keep the body moving in the right direction by taking old properties.
  83635. //Should be tested!
  83636. if (oldBody) {
  83637. ['force', 'torque', 'velocity', 'angularVelocity'].forEach(function (param) {
  83638. impostor.physicsBody[param].copy(oldBody[param]);
  83639. });
  83640. }
  83641. this._processChildMeshes(impostor);
  83642. }
  83643. //now update the body's transformation
  83644. this._updatePhysicsBodyTransformation(impostor);
  83645. };
  83646. CannonJSPlugin.prototype._processChildMeshes = function (mainImpostor) {
  83647. var _this = this;
  83648. var meshChildren = mainImpostor.object.getChildMeshes ? mainImpostor.object.getChildMeshes(true) : [];
  83649. var currentRotation = mainImpostor.object.rotationQuaternion;
  83650. if (meshChildren.length) {
  83651. var processMesh = function (localPosition, mesh) {
  83652. if (!currentRotation || !mesh.rotationQuaternion) {
  83653. return;
  83654. }
  83655. var childImpostor = mesh.getPhysicsImpostor();
  83656. if (childImpostor) {
  83657. var parent = childImpostor.parent;
  83658. if (parent !== mainImpostor) {
  83659. var pPosition = mesh.getAbsolutePosition().subtract(mainImpostor.object.getAbsolutePosition());
  83660. var localRotation = mesh.rotationQuaternion.multiply(BABYLON.Quaternion.Inverse(currentRotation));
  83661. if (childImpostor.physicsBody) {
  83662. _this.removePhysicsBody(childImpostor);
  83663. childImpostor.physicsBody = null;
  83664. }
  83665. childImpostor.parent = mainImpostor;
  83666. childImpostor.resetUpdateFlags();
  83667. 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));
  83668. //Add the mass of the children.
  83669. mainImpostor.physicsBody.mass += childImpostor.getParam("mass");
  83670. }
  83671. }
  83672. currentRotation.multiplyInPlace(mesh.rotationQuaternion);
  83673. mesh.getChildMeshes(true).filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(_this, mesh.getAbsolutePosition()));
  83674. };
  83675. meshChildren.filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(this, mainImpostor.object.getAbsolutePosition()));
  83676. }
  83677. };
  83678. CannonJSPlugin.prototype.removePhysicsBody = function (impostor) {
  83679. impostor.physicsBody.removeEventListener("collide", impostor.onCollide);
  83680. this.world.removeEventListener("preStep", impostor.beforeStep);
  83681. this.world.removeEventListener("postStep", impostor.afterStep);
  83682. this.world.remove(impostor.physicsBody);
  83683. };
  83684. CannonJSPlugin.prototype.generateJoint = function (impostorJoint) {
  83685. var mainBody = impostorJoint.mainImpostor.physicsBody;
  83686. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  83687. if (!mainBody || !connectedBody) {
  83688. return;
  83689. }
  83690. var constraint;
  83691. var jointData = impostorJoint.joint.jointData;
  83692. //TODO - https://github.com/schteppe/this.BJSCANNON.js/blob/gh-pages/demos/collisionFilter.html
  83693. var constraintData = {
  83694. pivotA: jointData.mainPivot ? new this.BJSCANNON.Vec3().copy(jointData.mainPivot) : null,
  83695. pivotB: jointData.connectedPivot ? new this.BJSCANNON.Vec3().copy(jointData.connectedPivot) : null,
  83696. axisA: jointData.mainAxis ? new this.BJSCANNON.Vec3().copy(jointData.mainAxis) : null,
  83697. axisB: jointData.connectedAxis ? new this.BJSCANNON.Vec3().copy(jointData.connectedAxis) : null,
  83698. maxForce: jointData.nativeParams.maxForce,
  83699. collideConnected: !!jointData.collision
  83700. };
  83701. switch (impostorJoint.joint.type) {
  83702. case BABYLON.PhysicsJoint.HingeJoint:
  83703. case BABYLON.PhysicsJoint.Hinge2Joint:
  83704. constraint = new this.BJSCANNON.HingeConstraint(mainBody, connectedBody, constraintData);
  83705. break;
  83706. case BABYLON.PhysicsJoint.DistanceJoint:
  83707. constraint = new this.BJSCANNON.DistanceConstraint(mainBody, connectedBody, jointData.maxDistance || 2);
  83708. break;
  83709. case BABYLON.PhysicsJoint.SpringJoint:
  83710. var springData = jointData;
  83711. constraint = new this.BJSCANNON.Spring(mainBody, connectedBody, {
  83712. restLength: springData.length,
  83713. stiffness: springData.stiffness,
  83714. damping: springData.damping,
  83715. localAnchorA: constraintData.pivotA,
  83716. localAnchorB: constraintData.pivotB
  83717. });
  83718. break;
  83719. case BABYLON.PhysicsJoint.LockJoint:
  83720. constraint = new this.BJSCANNON.LockConstraint(mainBody, connectedBody, constraintData);
  83721. break;
  83722. case BABYLON.PhysicsJoint.PointToPointJoint:
  83723. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  83724. default:
  83725. constraint = new this.BJSCANNON.PointToPointConstraint(mainBody, constraintData.pivotA, connectedBody, constraintData.pivotA, constraintData.maxForce);
  83726. break;
  83727. }
  83728. //set the collideConnected flag after the creation, since DistanceJoint ignores it.
  83729. constraint.collideConnected = !!jointData.collision;
  83730. impostorJoint.joint.physicsJoint = constraint;
  83731. //don't add spring as constraint, as it is not one.
  83732. if (impostorJoint.joint.type !== BABYLON.PhysicsJoint.SpringJoint) {
  83733. this.world.addConstraint(constraint);
  83734. }
  83735. else {
  83736. impostorJoint.mainImpostor.registerAfterPhysicsStep(function () {
  83737. constraint.applyForce();
  83738. });
  83739. }
  83740. };
  83741. CannonJSPlugin.prototype.removeJoint = function (impostorJoint) {
  83742. this.world.removeConstraint(impostorJoint.joint.physicsJoint);
  83743. };
  83744. CannonJSPlugin.prototype._addMaterial = function (name, friction, restitution) {
  83745. var index;
  83746. var mat;
  83747. for (index = 0; index < this._physicsMaterials.length; index++) {
  83748. mat = this._physicsMaterials[index];
  83749. if (mat.friction === friction && mat.restitution === restitution) {
  83750. return mat;
  83751. }
  83752. }
  83753. var currentMat = new this.BJSCANNON.Material(name);
  83754. currentMat.friction = friction;
  83755. currentMat.restitution = restitution;
  83756. this._physicsMaterials.push(currentMat);
  83757. return currentMat;
  83758. };
  83759. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  83760. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  83761. };
  83762. CannonJSPlugin.prototype._createShape = function (impostor) {
  83763. var object = impostor.object;
  83764. var returnValue;
  83765. var extendSize = impostor.getObjectExtendSize();
  83766. switch (impostor.type) {
  83767. case BABYLON.PhysicsImpostor.SphereImpostor:
  83768. var radiusX = extendSize.x;
  83769. var radiusY = extendSize.y;
  83770. var radiusZ = extendSize.z;
  83771. returnValue = new this.BJSCANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);
  83772. break;
  83773. //TMP also for cylinder - TODO Cannon supports cylinder natively.
  83774. case BABYLON.PhysicsImpostor.CylinderImpostor:
  83775. returnValue = new this.BJSCANNON.Cylinder(this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.y), 16);
  83776. break;
  83777. case BABYLON.PhysicsImpostor.BoxImpostor:
  83778. var box = extendSize.scale(0.5);
  83779. returnValue = new this.BJSCANNON.Box(new this.BJSCANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z)));
  83780. break;
  83781. case BABYLON.PhysicsImpostor.PlaneImpostor:
  83782. BABYLON.Tools.Warn("Attention, PlaneImposter might not behave as you expect. Consider using BoxImposter instead");
  83783. returnValue = new this.BJSCANNON.Plane();
  83784. break;
  83785. case BABYLON.PhysicsImpostor.MeshImpostor:
  83786. // should transform the vertex data to world coordinates!!
  83787. var rawVerts = object.getVerticesData ? object.getVerticesData(BABYLON.VertexBuffer.PositionKind) : [];
  83788. var rawFaces = object.getIndices ? object.getIndices() : [];
  83789. if (!rawVerts)
  83790. return;
  83791. // get only scale! so the object could transform correctly.
  83792. var oldPosition = object.position.clone();
  83793. var oldRotation = object.rotation && object.rotation.clone();
  83794. var oldQuaternion = object.rotationQuaternion && object.rotationQuaternion.clone();
  83795. object.position.copyFromFloats(0, 0, 0);
  83796. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  83797. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  83798. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  83799. var transform = object.computeWorldMatrix(true);
  83800. // convert rawVerts to object space
  83801. var temp = new Array();
  83802. var index;
  83803. for (index = 0; index < rawVerts.length; index += 3) {
  83804. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(rawVerts, index), transform).toArray(temp, index);
  83805. }
  83806. BABYLON.Tools.Warn("MeshImpostor only collides against spheres.");
  83807. returnValue = new this.BJSCANNON.Trimesh(temp, rawFaces);
  83808. //now set back the transformation!
  83809. object.position.copyFrom(oldPosition);
  83810. oldRotation && object.rotation && object.rotation.copyFrom(oldRotation);
  83811. oldQuaternion && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion);
  83812. break;
  83813. case BABYLON.PhysicsImpostor.HeightmapImpostor:
  83814. var oldPosition2 = object.position.clone();
  83815. var oldRotation2 = object.rotation && object.rotation.clone();
  83816. var oldQuaternion2 = object.rotationQuaternion && object.rotationQuaternion.clone();
  83817. object.position.copyFromFloats(0, 0, 0);
  83818. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  83819. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  83820. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  83821. object.rotationQuaternion && object.rotationQuaternion.multiplyInPlace(this._minus90X);
  83822. returnValue = this._createHeightmap(object);
  83823. object.position.copyFrom(oldPosition2);
  83824. oldRotation2 && object.rotation && object.rotation.copyFrom(oldRotation2);
  83825. oldQuaternion2 && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion2);
  83826. object.computeWorldMatrix(true);
  83827. break;
  83828. case BABYLON.PhysicsImpostor.ParticleImpostor:
  83829. returnValue = new this.BJSCANNON.Particle();
  83830. break;
  83831. }
  83832. return returnValue;
  83833. };
  83834. CannonJSPlugin.prototype._createHeightmap = function (object, pointDepth) {
  83835. var pos = (object.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  83836. var transform = object.computeWorldMatrix(true);
  83837. // convert rawVerts to object space
  83838. var temp = new Array();
  83839. var index;
  83840. for (index = 0; index < pos.length; index += 3) {
  83841. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(pos, index), transform).toArray(temp, index);
  83842. }
  83843. pos = temp;
  83844. var matrix = new Array();
  83845. //For now pointDepth will not be used and will be automatically calculated.
  83846. //Future reference - try and find the best place to add a reference to the pointDepth variable.
  83847. var arraySize = pointDepth || ~~(Math.sqrt(pos.length / 3) - 1);
  83848. var boundingInfo = object.getBoundingInfo();
  83849. var dim = Math.min(boundingInfo.boundingBox.extendSizeWorld.x, boundingInfo.boundingBox.extendSizeWorld.y);
  83850. var minY = boundingInfo.boundingBox.extendSizeWorld.z;
  83851. var elementSize = dim * 2 / arraySize;
  83852. for (var i = 0; i < pos.length; i = i + 3) {
  83853. var x = Math.round((pos[i + 0]) / elementSize + arraySize / 2);
  83854. var z = Math.round(((pos[i + 1]) / elementSize - arraySize / 2) * -1);
  83855. var y = -pos[i + 2] + minY;
  83856. if (!matrix[x]) {
  83857. matrix[x] = [];
  83858. }
  83859. if (!matrix[x][z]) {
  83860. matrix[x][z] = y;
  83861. }
  83862. matrix[x][z] = Math.max(y, matrix[x][z]);
  83863. }
  83864. for (var x = 0; x <= arraySize; ++x) {
  83865. if (!matrix[x]) {
  83866. var loc = 1;
  83867. while (!matrix[(x + loc) % arraySize]) {
  83868. loc++;
  83869. }
  83870. matrix[x] = matrix[(x + loc) % arraySize].slice();
  83871. //console.log("missing x", x);
  83872. }
  83873. for (var z = 0; z <= arraySize; ++z) {
  83874. if (!matrix[x][z]) {
  83875. var loc = 1;
  83876. var newValue;
  83877. while (newValue === undefined) {
  83878. newValue = matrix[x][(z + loc++) % arraySize];
  83879. }
  83880. matrix[x][z] = newValue;
  83881. }
  83882. }
  83883. }
  83884. var shape = new this.BJSCANNON.Heightfield(matrix, {
  83885. elementSize: elementSize
  83886. });
  83887. //For future reference, needed for body transformation
  83888. shape.minY = minY;
  83889. return shape;
  83890. };
  83891. CannonJSPlugin.prototype._updatePhysicsBodyTransformation = function (impostor) {
  83892. var object = impostor.object;
  83893. //make sure it is updated...
  83894. object.computeWorldMatrix && object.computeWorldMatrix(true);
  83895. // The delta between the mesh position and the mesh bounding box center
  83896. var bInfo = object.getBoundingInfo();
  83897. if (!bInfo)
  83898. return;
  83899. var center = impostor.getObjectCenter();
  83900. //m.getAbsolutePosition().subtract(m.getBoundingInfo().boundingBox.centerWorld)
  83901. this._tmpDeltaPosition.copyFrom(object.getAbsolutePivotPoint().subtract(center));
  83902. this._tmpDeltaPosition.divideInPlace(impostor.object.scaling);
  83903. this._tmpPosition.copyFrom(center);
  83904. var quaternion = object.rotationQuaternion;
  83905. if (!quaternion) {
  83906. return;
  83907. }
  83908. //is shape is a plane or a heightmap, it must be rotated 90 degs in the X axis.
  83909. if (impostor.type === BABYLON.PhysicsImpostor.PlaneImpostor || impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor || impostor.type === BABYLON.PhysicsImpostor.CylinderImpostor) {
  83910. //-90 DEG in X, precalculated
  83911. quaternion = quaternion.multiply(this._minus90X);
  83912. //Invert! (Precalculated, 90 deg in X)
  83913. //No need to clone. this will never change.
  83914. impostor.setDeltaRotation(this._plus90X);
  83915. }
  83916. //If it is a heightfield, if should be centered.
  83917. if (impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor) {
  83918. var mesh = object;
  83919. var boundingInfo = mesh.getBoundingInfo();
  83920. //calculate the correct body position:
  83921. var rotationQuaternion = mesh.rotationQuaternion;
  83922. mesh.rotationQuaternion = this._tmpUnityRotation;
  83923. mesh.computeWorldMatrix(true);
  83924. //get original center with no rotation
  83925. var c = center.clone();
  83926. var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
  83927. //calculate the new center using a pivot (since this.BJSCANNON.js doesn't center height maps)
  83928. var p = BABYLON.Matrix.Translation(boundingInfo.boundingBox.extendSizeWorld.x, 0, -boundingInfo.boundingBox.extendSizeWorld.z);
  83929. mesh.setPreTransformMatrix(p);
  83930. mesh.computeWorldMatrix(true);
  83931. //calculate the translation
  83932. var translation = boundingInfo.boundingBox.centerWorld.subtract(center).subtract(mesh.position).negate();
  83933. this._tmpPosition.copyFromFloats(translation.x, translation.y - boundingInfo.boundingBox.extendSizeWorld.y, translation.z);
  83934. //add it inverted to the delta
  83935. this._tmpDeltaPosition.copyFrom(boundingInfo.boundingBox.centerWorld.subtract(c));
  83936. this._tmpDeltaPosition.y += boundingInfo.boundingBox.extendSizeWorld.y;
  83937. //rotation is back
  83938. mesh.rotationQuaternion = rotationQuaternion;
  83939. mesh.setPreTransformMatrix(oldPivot);
  83940. mesh.computeWorldMatrix(true);
  83941. }
  83942. else if (impostor.type === BABYLON.PhysicsImpostor.MeshImpostor) {
  83943. this._tmpDeltaPosition.copyFromFloats(0, 0, 0);
  83944. //this._tmpPosition.copyFrom(object.position);
  83945. }
  83946. impostor.setDeltaPosition(this._tmpDeltaPosition);
  83947. //Now update the impostor object
  83948. impostor.physicsBody.position.copy(this._tmpPosition);
  83949. impostor.physicsBody.quaternion.copy(quaternion);
  83950. };
  83951. CannonJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  83952. impostor.object.position.copyFrom(impostor.physicsBody.position);
  83953. if (impostor.object.rotationQuaternion) {
  83954. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.quaternion);
  83955. }
  83956. };
  83957. CannonJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  83958. impostor.physicsBody.position.copy(newPosition);
  83959. impostor.physicsBody.quaternion.copy(newRotation);
  83960. };
  83961. CannonJSPlugin.prototype.isSupported = function () {
  83962. return this.BJSCANNON !== undefined;
  83963. };
  83964. CannonJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  83965. impostor.physicsBody.velocity.copy(velocity);
  83966. };
  83967. CannonJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  83968. impostor.physicsBody.angularVelocity.copy(velocity);
  83969. };
  83970. CannonJSPlugin.prototype.getLinearVelocity = function (impostor) {
  83971. var v = impostor.physicsBody.velocity;
  83972. if (!v) {
  83973. return null;
  83974. }
  83975. return new BABYLON.Vector3(v.x, v.y, v.z);
  83976. };
  83977. CannonJSPlugin.prototype.getAngularVelocity = function (impostor) {
  83978. var v = impostor.physicsBody.angularVelocity;
  83979. if (!v) {
  83980. return null;
  83981. }
  83982. return new BABYLON.Vector3(v.x, v.y, v.z);
  83983. };
  83984. CannonJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  83985. impostor.physicsBody.mass = mass;
  83986. impostor.physicsBody.updateMassProperties();
  83987. };
  83988. CannonJSPlugin.prototype.getBodyMass = function (impostor) {
  83989. return impostor.physicsBody.mass;
  83990. };
  83991. CannonJSPlugin.prototype.getBodyFriction = function (impostor) {
  83992. return impostor.physicsBody.material.friction;
  83993. };
  83994. CannonJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  83995. impostor.physicsBody.material.friction = friction;
  83996. };
  83997. CannonJSPlugin.prototype.getBodyRestitution = function (impostor) {
  83998. return impostor.physicsBody.material.restitution;
  83999. };
  84000. CannonJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  84001. impostor.physicsBody.material.restitution = restitution;
  84002. };
  84003. CannonJSPlugin.prototype.sleepBody = function (impostor) {
  84004. impostor.physicsBody.sleep();
  84005. };
  84006. CannonJSPlugin.prototype.wakeUpBody = function (impostor) {
  84007. impostor.physicsBody.wakeUp();
  84008. };
  84009. CannonJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  84010. joint.physicsJoint.distance = maxDistance;
  84011. };
  84012. // private enableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  84013. // if (!motorIndex) {
  84014. // joint.physicsJoint.enableMotor();
  84015. // }
  84016. // }
  84017. // private disableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  84018. // if (!motorIndex) {
  84019. // joint.physicsJoint.disableMotor();
  84020. // }
  84021. // }
  84022. CannonJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  84023. if (!motorIndex) {
  84024. joint.physicsJoint.enableMotor();
  84025. joint.physicsJoint.setMotorSpeed(speed);
  84026. if (maxForce) {
  84027. this.setLimit(joint, maxForce);
  84028. }
  84029. }
  84030. };
  84031. CannonJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit) {
  84032. joint.physicsJoint.motorEquation.maxForce = upperLimit;
  84033. joint.physicsJoint.motorEquation.minForce = lowerLimit === void 0 ? -upperLimit : lowerLimit;
  84034. };
  84035. CannonJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  84036. var body = impostor.physicsBody;
  84037. mesh.position.x = body.position.x;
  84038. mesh.position.y = body.position.y;
  84039. mesh.position.z = body.position.z;
  84040. if (mesh.rotationQuaternion) {
  84041. mesh.rotationQuaternion.x = body.quaternion.x;
  84042. mesh.rotationQuaternion.y = body.quaternion.y;
  84043. mesh.rotationQuaternion.z = body.quaternion.z;
  84044. mesh.rotationQuaternion.w = body.quaternion.w;
  84045. }
  84046. };
  84047. CannonJSPlugin.prototype.getRadius = function (impostor) {
  84048. var shape = impostor.physicsBody.shapes[0];
  84049. return shape.boundingSphereRadius;
  84050. };
  84051. CannonJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  84052. var shape = impostor.physicsBody.shapes[0];
  84053. result.x = shape.halfExtents.x * 2;
  84054. result.y = shape.halfExtents.y * 2;
  84055. result.z = shape.halfExtents.z * 2;
  84056. };
  84057. CannonJSPlugin.prototype.dispose = function () {
  84058. };
  84059. CannonJSPlugin.prototype._extendNamespace = function () {
  84060. //this will force cannon to execute at least one step when using interpolation
  84061. var step_tmp1 = new this.BJSCANNON.Vec3();
  84062. var Engine = this.BJSCANNON;
  84063. this.BJSCANNON.World.prototype.step = function (dt, timeSinceLastCalled, maxSubSteps) {
  84064. maxSubSteps = maxSubSteps || 10;
  84065. timeSinceLastCalled = timeSinceLastCalled || 0;
  84066. if (timeSinceLastCalled === 0) {
  84067. this.internalStep(dt);
  84068. this.time += dt;
  84069. }
  84070. else {
  84071. var internalSteps = Math.floor((this.time + timeSinceLastCalled) / dt) - Math.floor(this.time / dt);
  84072. internalSteps = Math.min(internalSteps, maxSubSteps) || 1;
  84073. var t0 = performance.now();
  84074. for (var i = 0; i !== internalSteps; i++) {
  84075. this.internalStep(dt);
  84076. if (performance.now() - t0 > dt * 1000) {
  84077. break;
  84078. }
  84079. }
  84080. this.time += timeSinceLastCalled;
  84081. var h = this.time % dt;
  84082. var h_div_dt = h / dt;
  84083. var interpvelo = step_tmp1;
  84084. var bodies = this.bodies;
  84085. for (var j = 0; j !== bodies.length; j++) {
  84086. var b = bodies[j];
  84087. if (b.type !== Engine.Body.STATIC && b.sleepState !== Engine.Body.SLEEPING) {
  84088. b.position.vsub(b.previousPosition, interpvelo);
  84089. interpvelo.scale(h_div_dt, interpvelo);
  84090. b.position.vadd(interpvelo, b.interpolatedPosition);
  84091. }
  84092. else {
  84093. b.interpolatedPosition.copy(b.position);
  84094. b.interpolatedQuaternion.copy(b.quaternion);
  84095. }
  84096. }
  84097. }
  84098. };
  84099. };
  84100. return CannonJSPlugin;
  84101. }());
  84102. BABYLON.CannonJSPlugin = CannonJSPlugin;
  84103. })(BABYLON || (BABYLON = {}));
  84104. //# sourceMappingURL=babylon.cannonJSPlugin.js.map
  84105. var BABYLON;
  84106. (function (BABYLON) {
  84107. var OimoJSPlugin = /** @class */ (function () {
  84108. function OimoJSPlugin(iterations) {
  84109. this.name = "OimoJSPlugin";
  84110. this._tmpImpostorsArray = [];
  84111. this._tmpPositionVector = BABYLON.Vector3.Zero();
  84112. this.BJSOIMO = OIMO;
  84113. this.world = new this.BJSOIMO.World({
  84114. iterations: iterations
  84115. });
  84116. this.world.clear();
  84117. }
  84118. OimoJSPlugin.prototype.setGravity = function (gravity) {
  84119. this.world.gravity.copy(gravity);
  84120. };
  84121. OimoJSPlugin.prototype.setTimeStep = function (timeStep) {
  84122. this.world.timeStep = timeStep;
  84123. };
  84124. OimoJSPlugin.prototype.getTimeStep = function () {
  84125. return this.world.timeStep;
  84126. };
  84127. OimoJSPlugin.prototype.executeStep = function (delta, impostors) {
  84128. var _this = this;
  84129. impostors.forEach(function (impostor) {
  84130. impostor.beforeStep();
  84131. });
  84132. this.world.step();
  84133. impostors.forEach(function (impostor) {
  84134. impostor.afterStep();
  84135. //update the ordered impostors array
  84136. _this._tmpImpostorsArray[impostor.uniqueId] = impostor;
  84137. });
  84138. //check for collisions
  84139. var contact = this.world.contacts;
  84140. while (contact !== null) {
  84141. if (contact.touching && !contact.body1.sleeping && !contact.body2.sleeping) {
  84142. contact = contact.next;
  84143. continue;
  84144. }
  84145. //is this body colliding with any other? get the impostor
  84146. var mainImpostor = this._tmpImpostorsArray[+contact.body1.name];
  84147. var collidingImpostor = this._tmpImpostorsArray[+contact.body2.name];
  84148. if (!mainImpostor || !collidingImpostor) {
  84149. contact = contact.next;
  84150. continue;
  84151. }
  84152. mainImpostor.onCollide({ body: collidingImpostor.physicsBody });
  84153. collidingImpostor.onCollide({ body: mainImpostor.physicsBody });
  84154. contact = contact.next;
  84155. }
  84156. };
  84157. OimoJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  84158. var mass = impostor.physicsBody.mass;
  84159. impostor.physicsBody.applyImpulse(contactPoint.scale(this.world.invScale), force.scale(this.world.invScale * mass));
  84160. };
  84161. OimoJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  84162. BABYLON.Tools.Warn("Oimo doesn't support applying force. Using impule instead.");
  84163. this.applyImpulse(impostor, force, contactPoint);
  84164. };
  84165. OimoJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  84166. var _this = this;
  84167. //parent-child relationship. Does this impostor has a parent impostor?
  84168. if (impostor.parent) {
  84169. if (impostor.physicsBody) {
  84170. this.removePhysicsBody(impostor);
  84171. //TODO is that needed?
  84172. impostor.forceUpdate();
  84173. }
  84174. return;
  84175. }
  84176. if (impostor.isBodyInitRequired()) {
  84177. var bodyConfig = {
  84178. name: impostor.uniqueId,
  84179. //Oimo must have mass, also for static objects.
  84180. config: [impostor.getParam("mass") || 1, impostor.getParam("friction"), impostor.getParam("restitution")],
  84181. size: [],
  84182. type: [],
  84183. pos: [],
  84184. posShape: [],
  84185. rot: [],
  84186. rotShape: [],
  84187. move: impostor.getParam("mass") !== 0,
  84188. density: impostor.getParam("mass"),
  84189. friction: impostor.getParam("friction"),
  84190. restitution: impostor.getParam("restitution"),
  84191. //Supporting older versions of Oimo
  84192. world: this.world
  84193. };
  84194. var impostors = [impostor];
  84195. var addToArray = function (parent) {
  84196. if (!parent.getChildMeshes)
  84197. return;
  84198. parent.getChildMeshes().forEach(function (m) {
  84199. if (m.physicsImpostor) {
  84200. impostors.push(m.physicsImpostor);
  84201. //m.physicsImpostor._init();
  84202. }
  84203. });
  84204. };
  84205. addToArray(impostor.object);
  84206. var checkWithEpsilon_1 = function (value) {
  84207. return Math.max(value, BABYLON.PhysicsEngine.Epsilon);
  84208. };
  84209. impostors.forEach(function (i) {
  84210. if (!i.object.rotationQuaternion) {
  84211. return;
  84212. }
  84213. //get the correct bounding box
  84214. var oldQuaternion = i.object.rotationQuaternion;
  84215. var rot = oldQuaternion.toEulerAngles();
  84216. var extendSize = i.getObjectExtendSize();
  84217. var radToDeg = 57.295779513082320876;
  84218. if (i === impostor) {
  84219. var center = impostor.getObjectCenter();
  84220. impostor.object.getAbsolutePivotPoint().subtractToRef(center, _this._tmpPositionVector);
  84221. _this._tmpPositionVector.divideInPlace(impostor.object.scaling);
  84222. //Can also use Array.prototype.push.apply
  84223. bodyConfig.pos.push(center.x);
  84224. bodyConfig.pos.push(center.y);
  84225. bodyConfig.pos.push(center.z);
  84226. bodyConfig.posShape.push(0, 0, 0);
  84227. //tmp solution
  84228. bodyConfig.rot.push(rot.x * radToDeg);
  84229. bodyConfig.rot.push(rot.y * radToDeg);
  84230. bodyConfig.rot.push(rot.z * radToDeg);
  84231. bodyConfig.rotShape.push(0, 0, 0);
  84232. }
  84233. else {
  84234. var localPosition = i.object.getAbsolutePosition().subtract(impostor.object.getAbsolutePosition());
  84235. bodyConfig.posShape.push(localPosition.x);
  84236. bodyConfig.posShape.push(localPosition.y);
  84237. bodyConfig.posShape.push(localPosition.z);
  84238. bodyConfig.pos.push(0, 0, 0);
  84239. //tmp solution until https://github.com/lo-th/OIMO.js/pull/37 is merged
  84240. bodyConfig.rot.push(0);
  84241. bodyConfig.rot.push(0);
  84242. bodyConfig.rot.push(0);
  84243. bodyConfig.rotShape.push(rot.x * radToDeg);
  84244. bodyConfig.rotShape.push(rot.y * radToDeg);
  84245. bodyConfig.rotShape.push(rot.z * radToDeg);
  84246. }
  84247. // register mesh
  84248. switch (i.type) {
  84249. case BABYLON.PhysicsImpostor.ParticleImpostor:
  84250. BABYLON.Tools.Warn("No Particle support in OIMO.js. using SphereImpostor instead");
  84251. case BABYLON.PhysicsImpostor.SphereImpostor:
  84252. var radiusX = extendSize.x;
  84253. var radiusY = extendSize.y;
  84254. var radiusZ = extendSize.z;
  84255. var size = Math.max(checkWithEpsilon_1(radiusX), checkWithEpsilon_1(radiusY), checkWithEpsilon_1(radiusZ)) / 2;
  84256. bodyConfig.type.push('sphere');
  84257. //due to the way oimo works with compounds, add 3 times
  84258. bodyConfig.size.push(size);
  84259. bodyConfig.size.push(size);
  84260. bodyConfig.size.push(size);
  84261. break;
  84262. case BABYLON.PhysicsImpostor.CylinderImpostor:
  84263. var sizeX = checkWithEpsilon_1(extendSize.x) / 2;
  84264. var sizeY = checkWithEpsilon_1(extendSize.y);
  84265. bodyConfig.type.push('cylinder');
  84266. bodyConfig.size.push(sizeX);
  84267. bodyConfig.size.push(sizeY);
  84268. //due to the way oimo works with compounds, add one more value.
  84269. bodyConfig.size.push(sizeY);
  84270. break;
  84271. case BABYLON.PhysicsImpostor.PlaneImpostor:
  84272. case BABYLON.PhysicsImpostor.BoxImpostor:
  84273. default:
  84274. var sizeX = checkWithEpsilon_1(extendSize.x);
  84275. var sizeY = checkWithEpsilon_1(extendSize.y);
  84276. var sizeZ = checkWithEpsilon_1(extendSize.z);
  84277. bodyConfig.type.push('box');
  84278. //if (i === impostor) {
  84279. bodyConfig.size.push(sizeX);
  84280. bodyConfig.size.push(sizeY);
  84281. bodyConfig.size.push(sizeZ);
  84282. //} else {
  84283. // bodyConfig.size.push(0,0,0);
  84284. //}
  84285. break;
  84286. }
  84287. //actually not needed, but hey...
  84288. i.object.rotationQuaternion = oldQuaternion;
  84289. });
  84290. impostor.physicsBody = this.world.add(bodyConfig);
  84291. }
  84292. else {
  84293. this._tmpPositionVector.copyFromFloats(0, 0, 0);
  84294. }
  84295. impostor.setDeltaPosition(this._tmpPositionVector);
  84296. //this._tmpPositionVector.addInPlace(impostor.mesh.getBoundingInfo().boundingBox.center);
  84297. //this.setPhysicsBodyTransformation(impostor, this._tmpPositionVector, impostor.mesh.rotationQuaternion);
  84298. };
  84299. OimoJSPlugin.prototype.removePhysicsBody = function (impostor) {
  84300. //impostor.physicsBody.dispose();
  84301. //Same as : (older oimo versions)
  84302. this.world.removeRigidBody(impostor.physicsBody);
  84303. };
  84304. OimoJSPlugin.prototype.generateJoint = function (impostorJoint) {
  84305. var mainBody = impostorJoint.mainImpostor.physicsBody;
  84306. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  84307. if (!mainBody || !connectedBody) {
  84308. return;
  84309. }
  84310. var jointData = impostorJoint.joint.jointData;
  84311. var options = jointData.nativeParams || {};
  84312. var type;
  84313. var nativeJointData = {
  84314. body1: mainBody,
  84315. body2: connectedBody,
  84316. axe1: options.axe1 || (jointData.mainAxis ? jointData.mainAxis.asArray() : null),
  84317. axe2: options.axe2 || (jointData.connectedAxis ? jointData.connectedAxis.asArray() : null),
  84318. pos1: options.pos1 || (jointData.mainPivot ? jointData.mainPivot.asArray() : null),
  84319. pos2: options.pos2 || (jointData.connectedPivot ? jointData.connectedPivot.asArray() : null),
  84320. min: options.min,
  84321. max: options.max,
  84322. collision: options.collision || jointData.collision,
  84323. spring: options.spring,
  84324. //supporting older version of Oimo
  84325. world: this.world
  84326. };
  84327. switch (impostorJoint.joint.type) {
  84328. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  84329. type = "jointBall";
  84330. break;
  84331. case BABYLON.PhysicsJoint.SpringJoint:
  84332. BABYLON.Tools.Warn("OIMO.js doesn't support Spring Constraint. Simulating using DistanceJoint instead");
  84333. var springData = jointData;
  84334. nativeJointData.min = springData.length || nativeJointData.min;
  84335. //Max should also be set, just make sure it is at least min
  84336. nativeJointData.max = Math.max(nativeJointData.min, nativeJointData.max);
  84337. case BABYLON.PhysicsJoint.DistanceJoint:
  84338. type = "jointDistance";
  84339. nativeJointData.max = jointData.maxDistance;
  84340. break;
  84341. case BABYLON.PhysicsJoint.PrismaticJoint:
  84342. type = "jointPrisme";
  84343. break;
  84344. case BABYLON.PhysicsJoint.SliderJoint:
  84345. type = "jointSlide";
  84346. break;
  84347. case BABYLON.PhysicsJoint.WheelJoint:
  84348. type = "jointWheel";
  84349. break;
  84350. case BABYLON.PhysicsJoint.HingeJoint:
  84351. default:
  84352. type = "jointHinge";
  84353. break;
  84354. }
  84355. nativeJointData.type = type;
  84356. impostorJoint.joint.physicsJoint = this.world.add(nativeJointData);
  84357. };
  84358. OimoJSPlugin.prototype.removeJoint = function (impostorJoint) {
  84359. //Bug in Oimo prevents us from disposing a joint in the playground
  84360. //joint.joint.physicsJoint.dispose();
  84361. //So we will bruteforce it!
  84362. try {
  84363. this.world.removeJoint(impostorJoint.joint.physicsJoint);
  84364. }
  84365. catch (e) {
  84366. BABYLON.Tools.Warn(e);
  84367. }
  84368. };
  84369. OimoJSPlugin.prototype.isSupported = function () {
  84370. return this.BJSOIMO !== undefined;
  84371. };
  84372. OimoJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  84373. if (!impostor.physicsBody.sleeping) {
  84374. //TODO check that
  84375. /*if (impostor.physicsBody.shapes.next) {
  84376. var parentShape = this._getLastShape(impostor.physicsBody);
  84377. impostor.object.position.copyFrom(parentShape.position);
  84378. console.log(parentShape.position);
  84379. } else {*/
  84380. impostor.object.position.copyFrom(impostor.physicsBody.getPosition());
  84381. //}
  84382. if (impostor.object.rotationQuaternion) {
  84383. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.getQuaternion());
  84384. }
  84385. }
  84386. };
  84387. OimoJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  84388. var body = impostor.physicsBody;
  84389. body.position.copy(newPosition);
  84390. body.orientation.copy(newRotation);
  84391. body.syncShapes();
  84392. body.awake();
  84393. };
  84394. /*private _getLastShape(body: any): any {
  84395. var lastShape = body.shapes;
  84396. while (lastShape.next) {
  84397. lastShape = lastShape.next;
  84398. }
  84399. return lastShape;
  84400. }*/
  84401. OimoJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  84402. impostor.physicsBody.linearVelocity.init(velocity.x, velocity.y, velocity.z);
  84403. };
  84404. OimoJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  84405. impostor.physicsBody.angularVelocity.init(velocity.x, velocity.y, velocity.z);
  84406. };
  84407. OimoJSPlugin.prototype.getLinearVelocity = function (impostor) {
  84408. var v = impostor.physicsBody.linearVelocity;
  84409. if (!v) {
  84410. return null;
  84411. }
  84412. return new BABYLON.Vector3(v.x, v.y, v.z);
  84413. };
  84414. OimoJSPlugin.prototype.getAngularVelocity = function (impostor) {
  84415. var v = impostor.physicsBody.angularVelocity;
  84416. if (!v) {
  84417. return null;
  84418. }
  84419. return new BABYLON.Vector3(v.x, v.y, v.z);
  84420. };
  84421. OimoJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  84422. var staticBody = mass === 0;
  84423. //this will actually set the body's density and not its mass.
  84424. //But this is how oimo treats the mass variable.
  84425. impostor.physicsBody.shapes.density = staticBody ? 1 : mass;
  84426. impostor.physicsBody.setupMass(staticBody ? 0x2 : 0x1);
  84427. };
  84428. OimoJSPlugin.prototype.getBodyMass = function (impostor) {
  84429. return impostor.physicsBody.shapes.density;
  84430. };
  84431. OimoJSPlugin.prototype.getBodyFriction = function (impostor) {
  84432. return impostor.physicsBody.shapes.friction;
  84433. };
  84434. OimoJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  84435. impostor.physicsBody.shapes.friction = friction;
  84436. };
  84437. OimoJSPlugin.prototype.getBodyRestitution = function (impostor) {
  84438. return impostor.physicsBody.shapes.restitution;
  84439. };
  84440. OimoJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  84441. impostor.physicsBody.shapes.restitution = restitution;
  84442. };
  84443. OimoJSPlugin.prototype.sleepBody = function (impostor) {
  84444. impostor.physicsBody.sleep();
  84445. };
  84446. OimoJSPlugin.prototype.wakeUpBody = function (impostor) {
  84447. impostor.physicsBody.awake();
  84448. };
  84449. OimoJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  84450. joint.physicsJoint.limitMotor.upperLimit = maxDistance;
  84451. if (minDistance !== void 0) {
  84452. joint.physicsJoint.limitMotor.lowerLimit = minDistance;
  84453. }
  84454. };
  84455. OimoJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  84456. //TODO separate rotational and transational motors.
  84457. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  84458. if (motor) {
  84459. motor.setMotor(speed, maxForce);
  84460. }
  84461. };
  84462. OimoJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit, motorIndex) {
  84463. //TODO separate rotational and transational motors.
  84464. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  84465. if (motor) {
  84466. motor.setLimit(upperLimit, lowerLimit === void 0 ? -upperLimit : lowerLimit);
  84467. }
  84468. };
  84469. OimoJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  84470. var body = impostor.physicsBody;
  84471. mesh.position.x = body.position.x;
  84472. mesh.position.y = body.position.y;
  84473. mesh.position.z = body.position.z;
  84474. if (mesh.rotationQuaternion) {
  84475. mesh.rotationQuaternion.x = body.orientation.x;
  84476. mesh.rotationQuaternion.y = body.orientation.y;
  84477. mesh.rotationQuaternion.z = body.orientation.z;
  84478. mesh.rotationQuaternion.w = body.orientation.s;
  84479. }
  84480. };
  84481. OimoJSPlugin.prototype.getRadius = function (impostor) {
  84482. return impostor.physicsBody.shapes.radius;
  84483. };
  84484. OimoJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  84485. var shape = impostor.physicsBody.shapes;
  84486. result.x = shape.halfWidth * 2;
  84487. result.y = shape.halfHeight * 2;
  84488. result.z = shape.halfDepth * 2;
  84489. };
  84490. OimoJSPlugin.prototype.dispose = function () {
  84491. this.world.clear();
  84492. };
  84493. return OimoJSPlugin;
  84494. }());
  84495. BABYLON.OimoJSPlugin = OimoJSPlugin;
  84496. })(BABYLON || (BABYLON = {}));
  84497. //# sourceMappingURL=babylon.oimoJSPlugin.js.map
  84498. var BABYLON;
  84499. (function (BABYLON) {
  84500. /*
  84501. * Based on jsTGALoader - Javascript loader for TGA file
  84502. * By Vincent Thibault
  84503. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  84504. */
  84505. var TGATools = /** @class */ (function () {
  84506. function TGATools() {
  84507. }
  84508. TGATools.GetTGAHeader = function (data) {
  84509. var offset = 0;
  84510. var header = {
  84511. id_length: data[offset++],
  84512. colormap_type: data[offset++],
  84513. image_type: data[offset++],
  84514. colormap_index: data[offset++] | data[offset++] << 8,
  84515. colormap_length: data[offset++] | data[offset++] << 8,
  84516. colormap_size: data[offset++],
  84517. origin: [
  84518. data[offset++] | data[offset++] << 8,
  84519. data[offset++] | data[offset++] << 8
  84520. ],
  84521. width: data[offset++] | data[offset++] << 8,
  84522. height: data[offset++] | data[offset++] << 8,
  84523. pixel_size: data[offset++],
  84524. flags: data[offset++]
  84525. };
  84526. return header;
  84527. };
  84528. TGATools.UploadContent = function (gl, data) {
  84529. // Not enough data to contain header ?
  84530. if (data.length < 19) {
  84531. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  84532. return;
  84533. }
  84534. // Read Header
  84535. var offset = 18;
  84536. var header = TGATools.GetTGAHeader(data);
  84537. // Assume it's a valid Targa file.
  84538. if (header.id_length + offset > data.length) {
  84539. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  84540. return;
  84541. }
  84542. // Skip not needed data
  84543. offset += header.id_length;
  84544. var use_rle = false;
  84545. var use_pal = false;
  84546. var use_grey = false;
  84547. // Get some informations.
  84548. switch (header.image_type) {
  84549. case TGATools._TYPE_RLE_INDEXED:
  84550. use_rle = true;
  84551. case TGATools._TYPE_INDEXED:
  84552. use_pal = true;
  84553. break;
  84554. case TGATools._TYPE_RLE_RGB:
  84555. use_rle = true;
  84556. case TGATools._TYPE_RGB:
  84557. // use_rgb = true;
  84558. break;
  84559. case TGATools._TYPE_RLE_GREY:
  84560. use_rle = true;
  84561. case TGATools._TYPE_GREY:
  84562. use_grey = true;
  84563. break;
  84564. }
  84565. var pixel_data;
  84566. // var numAlphaBits = header.flags & 0xf;
  84567. var pixel_size = header.pixel_size >> 3;
  84568. var pixel_total = header.width * header.height * pixel_size;
  84569. // Read palettes
  84570. var palettes;
  84571. if (use_pal) {
  84572. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  84573. }
  84574. // Read LRE
  84575. if (use_rle) {
  84576. pixel_data = new Uint8Array(pixel_total);
  84577. var c, count, i;
  84578. var localOffset = 0;
  84579. var pixels = new Uint8Array(pixel_size);
  84580. while (offset < pixel_total && localOffset < pixel_total) {
  84581. c = data[offset++];
  84582. count = (c & 0x7f) + 1;
  84583. // RLE pixels
  84584. if (c & 0x80) {
  84585. // Bind pixel tmp array
  84586. for (i = 0; i < pixel_size; ++i) {
  84587. pixels[i] = data[offset++];
  84588. }
  84589. // Copy pixel array
  84590. for (i = 0; i < count; ++i) {
  84591. pixel_data.set(pixels, localOffset + i * pixel_size);
  84592. }
  84593. localOffset += pixel_size * count;
  84594. }
  84595. // Raw pixels
  84596. else {
  84597. count *= pixel_size;
  84598. for (i = 0; i < count; ++i) {
  84599. pixel_data[localOffset + i] = data[offset++];
  84600. }
  84601. localOffset += count;
  84602. }
  84603. }
  84604. }
  84605. // RAW Pixels
  84606. else {
  84607. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  84608. }
  84609. // Load to texture
  84610. var x_start, y_start, x_step, y_step, y_end, x_end;
  84611. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  84612. default:
  84613. case TGATools._ORIGIN_UL:
  84614. x_start = 0;
  84615. x_step = 1;
  84616. x_end = header.width;
  84617. y_start = 0;
  84618. y_step = 1;
  84619. y_end = header.height;
  84620. break;
  84621. case TGATools._ORIGIN_BL:
  84622. x_start = 0;
  84623. x_step = 1;
  84624. x_end = header.width;
  84625. y_start = header.height - 1;
  84626. y_step = -1;
  84627. y_end = -1;
  84628. break;
  84629. case TGATools._ORIGIN_UR:
  84630. x_start = header.width - 1;
  84631. x_step = -1;
  84632. x_end = -1;
  84633. y_start = 0;
  84634. y_step = 1;
  84635. y_end = header.height;
  84636. break;
  84637. case TGATools._ORIGIN_BR:
  84638. x_start = header.width - 1;
  84639. x_step = -1;
  84640. x_end = -1;
  84641. y_start = header.height - 1;
  84642. y_step = -1;
  84643. y_end = -1;
  84644. break;
  84645. }
  84646. // Load the specify method
  84647. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  84648. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  84649. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  84650. };
  84651. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  84652. var image = pixel_data, colormap = palettes;
  84653. var width = header.width, height = header.height;
  84654. var color, i = 0, x, y;
  84655. var imageData = new Uint8Array(width * height * 4);
  84656. for (y = y_start; y !== y_end; y += y_step) {
  84657. for (x = x_start; x !== x_end; x += x_step, i++) {
  84658. color = image[i];
  84659. imageData[(x + width * y) * 4 + 3] = 255;
  84660. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  84661. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  84662. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  84663. }
  84664. }
  84665. return imageData;
  84666. };
  84667. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  84668. var image = pixel_data;
  84669. var width = header.width, height = header.height;
  84670. var color, i = 0, x, y;
  84671. var imageData = new Uint8Array(width * height * 4);
  84672. for (y = y_start; y !== y_end; y += y_step) {
  84673. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  84674. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  84675. var r = (((color & 0x7C00) >> 10) * 255) / 0x1F | 0;
  84676. var g = (((color & 0x03E0) >> 5) * 255) / 0x1F | 0;
  84677. var b = ((color & 0x001F) * 255) / 0x1F | 0;
  84678. imageData[(x + width * y) * 4 + 0] = r;
  84679. imageData[(x + width * y) * 4 + 1] = g;
  84680. imageData[(x + width * y) * 4 + 2] = b;
  84681. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  84682. }
  84683. }
  84684. return imageData;
  84685. };
  84686. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  84687. var image = pixel_data;
  84688. var width = header.width, height = header.height;
  84689. var i = 0, x, y;
  84690. var imageData = new Uint8Array(width * height * 4);
  84691. for (y = y_start; y !== y_end; y += y_step) {
  84692. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  84693. imageData[(x + width * y) * 4 + 3] = 255;
  84694. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  84695. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  84696. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  84697. }
  84698. }
  84699. return imageData;
  84700. };
  84701. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  84702. var image = pixel_data;
  84703. var width = header.width, height = header.height;
  84704. var i = 0, x, y;
  84705. var imageData = new Uint8Array(width * height * 4);
  84706. for (y = y_start; y !== y_end; y += y_step) {
  84707. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  84708. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  84709. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  84710. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  84711. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  84712. }
  84713. }
  84714. return imageData;
  84715. };
  84716. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  84717. var image = pixel_data;
  84718. var width = header.width, height = header.height;
  84719. var color, i = 0, x, y;
  84720. var imageData = new Uint8Array(width * height * 4);
  84721. for (y = y_start; y !== y_end; y += y_step) {
  84722. for (x = x_start; x !== x_end; x += x_step, i++) {
  84723. color = image[i];
  84724. imageData[(x + width * y) * 4 + 0] = color;
  84725. imageData[(x + width * y) * 4 + 1] = color;
  84726. imageData[(x + width * y) * 4 + 2] = color;
  84727. imageData[(x + width * y) * 4 + 3] = 255;
  84728. }
  84729. }
  84730. return imageData;
  84731. };
  84732. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  84733. var image = pixel_data;
  84734. var width = header.width, height = header.height;
  84735. var i = 0, x, y;
  84736. var imageData = new Uint8Array(width * height * 4);
  84737. for (y = y_start; y !== y_end; y += y_step) {
  84738. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  84739. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  84740. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  84741. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  84742. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  84743. }
  84744. }
  84745. return imageData;
  84746. };
  84747. //private static _TYPE_NO_DATA = 0;
  84748. TGATools._TYPE_INDEXED = 1;
  84749. TGATools._TYPE_RGB = 2;
  84750. TGATools._TYPE_GREY = 3;
  84751. TGATools._TYPE_RLE_INDEXED = 9;
  84752. TGATools._TYPE_RLE_RGB = 10;
  84753. TGATools._TYPE_RLE_GREY = 11;
  84754. TGATools._ORIGIN_MASK = 0x30;
  84755. TGATools._ORIGIN_SHIFT = 0x04;
  84756. TGATools._ORIGIN_BL = 0x00;
  84757. TGATools._ORIGIN_BR = 0x01;
  84758. TGATools._ORIGIN_UL = 0x02;
  84759. TGATools._ORIGIN_UR = 0x03;
  84760. return TGATools;
  84761. }());
  84762. BABYLON.TGATools = TGATools;
  84763. })(BABYLON || (BABYLON = {}));
  84764. //# sourceMappingURL=babylon.tga.js.map
  84765. var BABYLON;
  84766. (function (BABYLON) {
  84767. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  84768. // All values and structures referenced from:
  84769. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  84770. var DDS_MAGIC = 0x20534444;
  84771. var
  84772. //DDSD_CAPS = 0x1,
  84773. //DDSD_HEIGHT = 0x2,
  84774. //DDSD_WIDTH = 0x4,
  84775. //DDSD_PITCH = 0x8,
  84776. //DDSD_PIXELFORMAT = 0x1000,
  84777. DDSD_MIPMAPCOUNT = 0x20000;
  84778. //DDSD_LINEARSIZE = 0x80000,
  84779. //DDSD_DEPTH = 0x800000;
  84780. // var DDSCAPS_COMPLEX = 0x8,
  84781. // DDSCAPS_MIPMAP = 0x400000,
  84782. // DDSCAPS_TEXTURE = 0x1000;
  84783. var DDSCAPS2_CUBEMAP = 0x200;
  84784. // DDSCAPS2_CUBEMAP_POSITIVEX = 0x400,
  84785. // DDSCAPS2_CUBEMAP_NEGATIVEX = 0x800,
  84786. // DDSCAPS2_CUBEMAP_POSITIVEY = 0x1000,
  84787. // DDSCAPS2_CUBEMAP_NEGATIVEY = 0x2000,
  84788. // DDSCAPS2_CUBEMAP_POSITIVEZ = 0x4000,
  84789. // DDSCAPS2_CUBEMAP_NEGATIVEZ = 0x8000,
  84790. // DDSCAPS2_VOLUME = 0x200000;
  84791. var
  84792. //DDPF_ALPHAPIXELS = 0x1,
  84793. //DDPF_ALPHA = 0x2,
  84794. DDPF_FOURCC = 0x4, DDPF_RGB = 0x40,
  84795. //DDPF_YUV = 0x200,
  84796. DDPF_LUMINANCE = 0x20000;
  84797. function FourCCToInt32(value) {
  84798. return value.charCodeAt(0) +
  84799. (value.charCodeAt(1) << 8) +
  84800. (value.charCodeAt(2) << 16) +
  84801. (value.charCodeAt(3) << 24);
  84802. }
  84803. function Int32ToFourCC(value) {
  84804. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  84805. }
  84806. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  84807. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  84808. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  84809. var FOURCC_DX10 = FourCCToInt32("DX10");
  84810. var FOURCC_D3DFMT_R16G16B16A16F = 113;
  84811. var FOURCC_D3DFMT_R32G32B32A32F = 116;
  84812. var DXGI_FORMAT_R16G16B16A16_FLOAT = 10;
  84813. var DXGI_FORMAT_B8G8R8X8_UNORM = 88;
  84814. var headerLengthInt = 31; // The header length in 32 bit ints
  84815. // Offsets into the header array
  84816. var off_magic = 0;
  84817. var off_size = 1;
  84818. var off_flags = 2;
  84819. var off_height = 3;
  84820. var off_width = 4;
  84821. var off_mipmapCount = 7;
  84822. var off_pfFlags = 20;
  84823. var off_pfFourCC = 21;
  84824. var off_RGBbpp = 22;
  84825. var off_RMask = 23;
  84826. var off_GMask = 24;
  84827. var off_BMask = 25;
  84828. var off_AMask = 26;
  84829. // var off_caps1 = 27;
  84830. var off_caps2 = 28;
  84831. // var off_caps3 = 29;
  84832. // var off_caps4 = 30;
  84833. var off_dxgiFormat = 32;
  84834. ;
  84835. var DDSTools = /** @class */ (function () {
  84836. function DDSTools() {
  84837. }
  84838. DDSTools.GetDDSInfo = function (arrayBuffer) {
  84839. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  84840. var extendedHeader = new Int32Array(arrayBuffer, 0, headerLengthInt + 4);
  84841. var mipmapCount = 1;
  84842. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  84843. mipmapCount = Math.max(1, header[off_mipmapCount]);
  84844. }
  84845. var fourCC = header[off_pfFourCC];
  84846. var dxgiFormat = (fourCC === FOURCC_DX10) ? extendedHeader[off_dxgiFormat] : 0;
  84847. var textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  84848. switch (fourCC) {
  84849. case FOURCC_D3DFMT_R16G16B16A16F:
  84850. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  84851. break;
  84852. case FOURCC_D3DFMT_R32G32B32A32F:
  84853. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  84854. break;
  84855. case FOURCC_DX10:
  84856. if (dxgiFormat === DXGI_FORMAT_R16G16B16A16_FLOAT) {
  84857. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  84858. break;
  84859. }
  84860. }
  84861. return {
  84862. width: header[off_width],
  84863. height: header[off_height],
  84864. mipmapCount: mipmapCount,
  84865. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  84866. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  84867. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  84868. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP,
  84869. isCompressed: (fourCC === FOURCC_DXT1 || fourCC === FOURCC_DXT3 || fourCC === FOURCC_DXT5),
  84870. dxgiFormat: dxgiFormat,
  84871. textureType: textureType
  84872. };
  84873. };
  84874. DDSTools._ToHalfFloat = function (value) {
  84875. if (!DDSTools._FloatView) {
  84876. DDSTools._FloatView = new Float32Array(1);
  84877. DDSTools._Int32View = new Int32Array(DDSTools._FloatView.buffer);
  84878. }
  84879. DDSTools._FloatView[0] = value;
  84880. var x = DDSTools._Int32View[0];
  84881. var bits = (x >> 16) & 0x8000; /* Get the sign */
  84882. var m = (x >> 12) & 0x07ff; /* Keep one extra bit for rounding */
  84883. var e = (x >> 23) & 0xff; /* Using int is faster here */
  84884. /* If zero, or denormal, or exponent underflows too much for a denormal
  84885. * half, return signed zero. */
  84886. if (e < 103) {
  84887. return bits;
  84888. }
  84889. /* If NaN, return NaN. If Inf or exponent overflow, return Inf. */
  84890. if (e > 142) {
  84891. bits |= 0x7c00;
  84892. /* If exponent was 0xff and one mantissa bit was set, it means NaN,
  84893. * not Inf, so make sure we set one mantissa bit too. */
  84894. bits |= ((e == 255) ? 0 : 1) && (x & 0x007fffff);
  84895. return bits;
  84896. }
  84897. /* If exponent underflows but not too much, return a denormal */
  84898. if (e < 113) {
  84899. m |= 0x0800;
  84900. /* Extra rounding may overflow and set mantissa to 0 and exponent
  84901. * to 1, which is OK. */
  84902. bits |= (m >> (114 - e)) + ((m >> (113 - e)) & 1);
  84903. return bits;
  84904. }
  84905. bits |= ((e - 112) << 10) | (m >> 1);
  84906. bits += m & 1;
  84907. return bits;
  84908. };
  84909. DDSTools._FromHalfFloat = function (value) {
  84910. var s = (value & 0x8000) >> 15;
  84911. var e = (value & 0x7C00) >> 10;
  84912. var f = value & 0x03FF;
  84913. if (e === 0) {
  84914. return (s ? -1 : 1) * Math.pow(2, -14) * (f / Math.pow(2, 10));
  84915. }
  84916. else if (e == 0x1F) {
  84917. return f ? NaN : ((s ? -1 : 1) * Infinity);
  84918. }
  84919. return (s ? -1 : 1) * Math.pow(2, e - 15) * (1 + (f / Math.pow(2, 10)));
  84920. };
  84921. DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  84922. var destArray = new Float32Array(dataLength);
  84923. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  84924. var index = 0;
  84925. for (var y = 0; y < height; y++) {
  84926. for (var x = 0; x < width; x++) {
  84927. var srcPos = (x + y * width) * 4;
  84928. destArray[index] = DDSTools._FromHalfFloat(srcData[srcPos]);
  84929. destArray[index + 1] = DDSTools._FromHalfFloat(srcData[srcPos + 1]);
  84930. destArray[index + 2] = DDSTools._FromHalfFloat(srcData[srcPos + 2]);
  84931. if (DDSTools.StoreLODInAlphaChannel) {
  84932. destArray[index + 3] = lod;
  84933. }
  84934. else {
  84935. destArray[index + 3] = DDSTools._FromHalfFloat(srcData[srcPos + 3]);
  84936. }
  84937. index += 4;
  84938. }
  84939. }
  84940. return destArray;
  84941. };
  84942. DDSTools._GetHalfFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  84943. if (DDSTools.StoreLODInAlphaChannel) {
  84944. var destArray = new Uint16Array(dataLength);
  84945. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  84946. var index = 0;
  84947. for (var y = 0; y < height; y++) {
  84948. for (var x = 0; x < width; x++) {
  84949. var srcPos = (x + y * width) * 4;
  84950. destArray[index] = srcData[srcPos];
  84951. destArray[index + 1] = srcData[srcPos + 1];
  84952. destArray[index + 2] = srcData[srcPos + 2];
  84953. destArray[index + 3] = DDSTools._ToHalfFloat(lod);
  84954. index += 4;
  84955. }
  84956. }
  84957. return destArray;
  84958. }
  84959. return new Uint16Array(arrayBuffer, dataOffset, dataLength);
  84960. };
  84961. DDSTools._GetFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  84962. if (DDSTools.StoreLODInAlphaChannel) {
  84963. var destArray = new Float32Array(dataLength);
  84964. var srcData = new Float32Array(arrayBuffer, dataOffset);
  84965. var index = 0;
  84966. for (var y = 0; y < height; y++) {
  84967. for (var x = 0; x < width; x++) {
  84968. var srcPos = (x + y * width) * 4;
  84969. destArray[index] = srcData[srcPos];
  84970. destArray[index + 1] = srcData[srcPos + 1];
  84971. destArray[index + 2] = srcData[srcPos + 2];
  84972. destArray[index + 3] = lod;
  84973. index += 4;
  84974. }
  84975. }
  84976. return destArray;
  84977. }
  84978. return new Float32Array(arrayBuffer, dataOffset, dataLength);
  84979. };
  84980. DDSTools._GetFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  84981. var destArray = new Uint8Array(dataLength);
  84982. var srcData = new Float32Array(arrayBuffer, dataOffset);
  84983. var index = 0;
  84984. for (var y = 0; y < height; y++) {
  84985. for (var x = 0; x < width; x++) {
  84986. var srcPos = (x + y * width) * 4;
  84987. destArray[index] = BABYLON.Scalar.Clamp(srcData[srcPos]) * 255;
  84988. destArray[index + 1] = BABYLON.Scalar.Clamp(srcData[srcPos + 1]) * 255;
  84989. destArray[index + 2] = BABYLON.Scalar.Clamp(srcData[srcPos + 2]) * 255;
  84990. if (DDSTools.StoreLODInAlphaChannel) {
  84991. destArray[index + 3] = lod;
  84992. }
  84993. else {
  84994. destArray[index + 3] = BABYLON.Scalar.Clamp(srcData[srcPos + 3]) * 255;
  84995. }
  84996. index += 4;
  84997. }
  84998. }
  84999. return destArray;
  85000. };
  85001. DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  85002. var destArray = new Uint8Array(dataLength);
  85003. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  85004. var index = 0;
  85005. for (var y = 0; y < height; y++) {
  85006. for (var x = 0; x < width; x++) {
  85007. var srcPos = (x + y * width) * 4;
  85008. destArray[index] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos])) * 255;
  85009. destArray[index + 1] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 1])) * 255;
  85010. destArray[index + 2] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 2])) * 255;
  85011. if (DDSTools.StoreLODInAlphaChannel) {
  85012. destArray[index + 3] = lod;
  85013. }
  85014. else {
  85015. destArray[index + 3] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 3])) * 255;
  85016. }
  85017. index += 4;
  85018. }
  85019. }
  85020. return destArray;
  85021. };
  85022. DDSTools._GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset) {
  85023. var byteArray = new Uint8Array(dataLength);
  85024. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  85025. var index = 0;
  85026. for (var y = 0; y < height; y++) {
  85027. for (var x = 0; x < width; x++) {
  85028. var srcPos = (x + y * width) * 4;
  85029. byteArray[index] = srcData[srcPos + rOffset];
  85030. byteArray[index + 1] = srcData[srcPos + gOffset];
  85031. byteArray[index + 2] = srcData[srcPos + bOffset];
  85032. byteArray[index + 3] = srcData[srcPos + aOffset];
  85033. index += 4;
  85034. }
  85035. }
  85036. return byteArray;
  85037. };
  85038. DDSTools._ExtractLongWordOrder = function (value) {
  85039. if (value === 0 || value === 255 || value === -16777216) {
  85040. return 0;
  85041. }
  85042. return 1 + DDSTools._ExtractLongWordOrder(value >> 8);
  85043. };
  85044. DDSTools._GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset) {
  85045. var byteArray = new Uint8Array(dataLength);
  85046. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  85047. var index = 0;
  85048. for (var y = 0; y < height; y++) {
  85049. for (var x = 0; x < width; x++) {
  85050. var srcPos = (x + y * width) * 3;
  85051. byteArray[index] = srcData[srcPos + rOffset];
  85052. byteArray[index + 1] = srcData[srcPos + gOffset];
  85053. byteArray[index + 2] = srcData[srcPos + bOffset];
  85054. index += 3;
  85055. }
  85056. }
  85057. return byteArray;
  85058. };
  85059. DDSTools._GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  85060. var byteArray = new Uint8Array(dataLength);
  85061. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  85062. var index = 0;
  85063. for (var y = 0; y < height; y++) {
  85064. for (var x = 0; x < width; x++) {
  85065. var srcPos = (x + y * width);
  85066. byteArray[index] = srcData[srcPos];
  85067. index++;
  85068. }
  85069. }
  85070. return byteArray;
  85071. };
  85072. DDSTools.UploadDDSLevels = function (engine, gl, arrayBuffer, info, loadMipmaps, faces, lodIndex, currentFace) {
  85073. if (lodIndex === void 0) { lodIndex = -1; }
  85074. var sphericalPolynomialFaces = null;
  85075. if (info.sphericalPolynomial) {
  85076. sphericalPolynomialFaces = new Array();
  85077. }
  85078. var ext = engine.getCaps().s3tc;
  85079. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  85080. var fourCC, width, height, dataLength = 0, dataOffset;
  85081. var byteArray, mipmapCount, mip;
  85082. var internalFormat = 0;
  85083. var format = 0;
  85084. var blockBytes = 1;
  85085. if (header[off_magic] !== DDS_MAGIC) {
  85086. BABYLON.Tools.Error("Invalid magic number in DDS header");
  85087. return;
  85088. }
  85089. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  85090. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  85091. return;
  85092. }
  85093. if (info.isCompressed && !ext) {
  85094. BABYLON.Tools.Error("Compressed textures are not supported on this platform.");
  85095. return;
  85096. }
  85097. var bpp = header[off_RGBbpp];
  85098. dataOffset = header[off_size] + 4;
  85099. var computeFormats = false;
  85100. if (info.isFourCC) {
  85101. fourCC = header[off_pfFourCC];
  85102. switch (fourCC) {
  85103. case FOURCC_DXT1:
  85104. blockBytes = 8;
  85105. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  85106. break;
  85107. case FOURCC_DXT3:
  85108. blockBytes = 16;
  85109. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  85110. break;
  85111. case FOURCC_DXT5:
  85112. blockBytes = 16;
  85113. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  85114. break;
  85115. case FOURCC_D3DFMT_R16G16B16A16F:
  85116. computeFormats = true;
  85117. break;
  85118. case FOURCC_D3DFMT_R32G32B32A32F:
  85119. computeFormats = true;
  85120. break;
  85121. case FOURCC_DX10:
  85122. // There is an additionnal header so dataOffset need to be changed
  85123. dataOffset += 5 * 4; // 5 uints
  85124. var supported = false;
  85125. switch (info.dxgiFormat) {
  85126. case DXGI_FORMAT_R16G16B16A16_FLOAT:
  85127. computeFormats = true;
  85128. supported = true;
  85129. break;
  85130. case DXGI_FORMAT_B8G8R8X8_UNORM:
  85131. info.isRGB = true;
  85132. info.isFourCC = false;
  85133. bpp = 32;
  85134. supported = true;
  85135. break;
  85136. }
  85137. if (supported) {
  85138. break;
  85139. }
  85140. default:
  85141. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  85142. return;
  85143. }
  85144. }
  85145. var rOffset = DDSTools._ExtractLongWordOrder(header[off_RMask]);
  85146. var gOffset = DDSTools._ExtractLongWordOrder(header[off_GMask]);
  85147. var bOffset = DDSTools._ExtractLongWordOrder(header[off_BMask]);
  85148. var aOffset = DDSTools._ExtractLongWordOrder(header[off_AMask]);
  85149. if (computeFormats) {
  85150. format = engine._getWebGLTextureType(info.textureType);
  85151. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  85152. }
  85153. mipmapCount = 1;
  85154. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  85155. mipmapCount = Math.max(1, header[off_mipmapCount]);
  85156. }
  85157. for (var face = 0; face < faces; face++) {
  85158. var sampler = faces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face + (currentFace ? currentFace : 0));
  85159. width = header[off_width];
  85160. height = header[off_height];
  85161. for (mip = 0; mip < mipmapCount; ++mip) {
  85162. if (lodIndex === -1 || lodIndex === mip) {
  85163. // In case of fixed LOD, if the lod has just been uploaded, early exit.
  85164. var i = (lodIndex === -1) ? mip : 0;
  85165. if (!info.isCompressed && info.isFourCC) {
  85166. dataLength = width * height * 4;
  85167. var floatArray = null;
  85168. if (engine._badOS || engine._badDesktopOS || (!engine.getCaps().textureHalfFloat && !engine.getCaps().textureFloat)) { // Required because iOS has many issues with float and half float generation
  85169. if (bpp === 128) {
  85170. floatArray = DDSTools._GetFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  85171. if (sphericalPolynomialFaces && i == 0) {
  85172. sphericalPolynomialFaces.push(DDSTools._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i));
  85173. }
  85174. }
  85175. else if (bpp === 64) {
  85176. floatArray = DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  85177. if (sphericalPolynomialFaces && i == 0) {
  85178. sphericalPolynomialFaces.push(DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i));
  85179. }
  85180. }
  85181. info.textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  85182. format = engine._getWebGLTextureType(info.textureType);
  85183. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  85184. }
  85185. else {
  85186. if (bpp === 128) {
  85187. floatArray = DDSTools._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  85188. if (sphericalPolynomialFaces && i == 0) {
  85189. sphericalPolynomialFaces.push(floatArray);
  85190. }
  85191. }
  85192. else if (bpp === 64 && !engine.getCaps().textureHalfFloat) {
  85193. floatArray = DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  85194. if (sphericalPolynomialFaces && i == 0) {
  85195. sphericalPolynomialFaces.push(floatArray);
  85196. }
  85197. info.textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  85198. format = engine._getWebGLTextureType(info.textureType);
  85199. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  85200. }
  85201. else { // 64
  85202. floatArray = DDSTools._GetHalfFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  85203. if (sphericalPolynomialFaces && i == 0) {
  85204. sphericalPolynomialFaces.push(DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i));
  85205. }
  85206. }
  85207. }
  85208. if (floatArray) {
  85209. engine._uploadDataToTexture(sampler, i, internalFormat, width, height, gl.RGBA, format, floatArray);
  85210. }
  85211. }
  85212. else if (info.isRGB) {
  85213. if (bpp === 24) {
  85214. dataLength = width * height * 3;
  85215. byteArray = DDSTools._GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset);
  85216. engine._uploadDataToTexture(sampler, i, gl.RGB, width, height, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  85217. }
  85218. else { // 32
  85219. dataLength = width * height * 4;
  85220. byteArray = DDSTools._GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset);
  85221. engine._uploadDataToTexture(sampler, i, gl.RGBA, width, height, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  85222. }
  85223. }
  85224. else if (info.isLuminance) {
  85225. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  85226. var unpaddedRowSize = width;
  85227. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  85228. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  85229. byteArray = DDSTools._GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  85230. engine._uploadDataToTexture(sampler, i, gl.LUMINANCE, width, height, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  85231. }
  85232. else {
  85233. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  85234. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  85235. engine._uploadCompressedDataToTexture(sampler, i, internalFormat, width, height, byteArray);
  85236. }
  85237. }
  85238. dataOffset += bpp ? (width * height * (bpp / 8)) : dataLength;
  85239. width *= 0.5;
  85240. height *= 0.5;
  85241. width = Math.max(1.0, width);
  85242. height = Math.max(1.0, height);
  85243. }
  85244. if (currentFace !== undefined) {
  85245. // Loading a single face
  85246. break;
  85247. }
  85248. }
  85249. if (sphericalPolynomialFaces && sphericalPolynomialFaces.length > 0) {
  85250. info.sphericalPolynomial = BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial({
  85251. size: header[off_width],
  85252. right: sphericalPolynomialFaces[0],
  85253. left: sphericalPolynomialFaces[1],
  85254. up: sphericalPolynomialFaces[2],
  85255. down: sphericalPolynomialFaces[3],
  85256. front: sphericalPolynomialFaces[4],
  85257. back: sphericalPolynomialFaces[5],
  85258. format: BABYLON.Engine.TEXTUREFORMAT_RGBA,
  85259. type: BABYLON.Engine.TEXTURETYPE_FLOAT,
  85260. gammaSpace: false,
  85261. });
  85262. }
  85263. else {
  85264. info.sphericalPolynomial = undefined;
  85265. }
  85266. };
  85267. DDSTools.StoreLODInAlphaChannel = false;
  85268. return DDSTools;
  85269. }());
  85270. BABYLON.DDSTools = DDSTools;
  85271. })(BABYLON || (BABYLON = {}));
  85272. //# sourceMappingURL=babylon.dds.js.map
  85273. var BABYLON;
  85274. (function (BABYLON) {
  85275. /**
  85276. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  85277. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  85278. */
  85279. var KhronosTextureContainer = /** @class */ (function () {
  85280. /**
  85281. * @param {ArrayBuffer} arrayBuffer- contents of the KTX container file
  85282. * @param {number} facesExpected- should be either 1 or 6, based whether a cube texture or or
  85283. * @param {boolean} threeDExpected- provision for indicating that data should be a 3D texture, not implemented
  85284. * @param {boolean} textureArrayExpected- provision for indicating that data should be a texture array, not implemented
  85285. */
  85286. function KhronosTextureContainer(arrayBuffer, facesExpected, threeDExpected, textureArrayExpected) {
  85287. this.arrayBuffer = arrayBuffer;
  85288. // Test that it is a ktx formatted file, based on the first 12 bytes, character representation is:
  85289. // '�', 'K', 'T', 'X', ' ', '1', '1', '�', '\r', '\n', '\x1A', '\n'
  85290. // 0xAB, 0x4B, 0x54, 0x58, 0x20, 0x31, 0x31, 0xBB, 0x0D, 0x0A, 0x1A, 0x0A
  85291. var identifier = new Uint8Array(this.arrayBuffer, 0, 12);
  85292. if (identifier[0] !== 0xAB || identifier[1] !== 0x4B || identifier[2] !== 0x54 || identifier[3] !== 0x58 || identifier[4] !== 0x20 || identifier[5] !== 0x31 ||
  85293. identifier[6] !== 0x31 || identifier[7] !== 0xBB || identifier[8] !== 0x0D || identifier[9] !== 0x0A || identifier[10] !== 0x1A || identifier[11] !== 0x0A) {
  85294. BABYLON.Tools.Error("texture missing KTX identifier");
  85295. return;
  85296. }
  85297. // load the reset of the header in native 32 bit int
  85298. var header = new Int32Array(this.arrayBuffer, 12, 13);
  85299. // determine of the remaining header values are recorded in the opposite endianness & require conversion
  85300. var oppositeEndianess = header[0] === 0x01020304;
  85301. // read all the header elements in order they exist in the file, without modification (sans endainness)
  85302. this.glType = oppositeEndianess ? this.switchEndainness(header[1]) : header[1]; // must be 0 for compressed textures
  85303. this.glTypeSize = oppositeEndianess ? this.switchEndainness(header[2]) : header[2]; // must be 1 for compressed textures
  85304. this.glFormat = oppositeEndianess ? this.switchEndainness(header[3]) : header[3]; // must be 0 for compressed textures
  85305. this.glInternalFormat = oppositeEndianess ? this.switchEndainness(header[4]) : header[4]; // the value of arg passed to gl.compressedTexImage2D(,,x,,,,)
  85306. this.glBaseInternalFormat = oppositeEndianess ? this.switchEndainness(header[5]) : header[5]; // specify GL_RGB, GL_RGBA, GL_ALPHA, etc (un-compressed only)
  85307. this.pixelWidth = oppositeEndianess ? this.switchEndainness(header[6]) : header[6]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,x,,,)
  85308. this.pixelHeight = oppositeEndianess ? this.switchEndainness(header[7]) : header[7]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,,x,,)
  85309. this.pixelDepth = oppositeEndianess ? this.switchEndainness(header[8]) : header[8]; // level 0 value of arg passed to gl.compressedTexImage3D(,,,,,x,,)
  85310. this.numberOfArrayElements = oppositeEndianess ? this.switchEndainness(header[9]) : header[9]; // used for texture arrays
  85311. this.numberOfFaces = oppositeEndianess ? this.switchEndainness(header[10]) : header[10]; // used for cubemap textures, should either be 1 or 6
  85312. this.numberOfMipmapLevels = oppositeEndianess ? this.switchEndainness(header[11]) : header[11]; // number of levels; disregard possibility of 0 for compressed textures
  85313. this.bytesOfKeyValueData = oppositeEndianess ? this.switchEndainness(header[12]) : header[12]; // the amount of space after the header for meta-data
  85314. // Make sure we have a compressed type. Not only reduces work, but probably better to let dev know they are not compressing.
  85315. if (this.glType !== 0) {
  85316. BABYLON.Tools.Error("only compressed formats currently supported");
  85317. return;
  85318. }
  85319. else {
  85320. // value of zero is an indication to generate mipmaps @ runtime. Not usually allowed for compressed, so disregard.
  85321. this.numberOfMipmapLevels = Math.max(1, this.numberOfMipmapLevels);
  85322. }
  85323. if (this.pixelHeight === 0 || this.pixelDepth !== 0) {
  85324. BABYLON.Tools.Error("only 2D textures currently supported");
  85325. return;
  85326. }
  85327. if (this.numberOfArrayElements !== 0) {
  85328. BABYLON.Tools.Error("texture arrays not currently supported");
  85329. return;
  85330. }
  85331. if (this.numberOfFaces !== facesExpected) {
  85332. BABYLON.Tools.Error("number of faces expected" + facesExpected + ", but found " + this.numberOfFaces);
  85333. return;
  85334. }
  85335. // we now have a completely validated file, so could use existence of loadType as success
  85336. // would need to make this more elaborate & adjust checks above to support more than one load type
  85337. this.loadType = KhronosTextureContainer.COMPRESSED_2D;
  85338. }
  85339. // not as fast hardware based, but will probably never need to use
  85340. KhronosTextureContainer.prototype.switchEndainness = function (val) {
  85341. return ((val & 0xFF) << 24)
  85342. | ((val & 0xFF00) << 8)
  85343. | ((val >> 8) & 0xFF00)
  85344. | ((val >> 24) & 0xFF);
  85345. };
  85346. /**
  85347. * It is assumed that the texture has already been created & is currently bound
  85348. */
  85349. KhronosTextureContainer.prototype.uploadLevels = function (gl, loadMipmaps) {
  85350. switch (this.loadType) {
  85351. case KhronosTextureContainer.COMPRESSED_2D:
  85352. this._upload2DCompressedLevels(gl, loadMipmaps);
  85353. break;
  85354. case KhronosTextureContainer.TEX_2D:
  85355. case KhronosTextureContainer.COMPRESSED_3D:
  85356. case KhronosTextureContainer.TEX_3D:
  85357. }
  85358. };
  85359. KhronosTextureContainer.prototype._upload2DCompressedLevels = function (gl, loadMipmaps) {
  85360. // initialize width & height for level 1
  85361. var dataOffset = KhronosTextureContainer.HEADER_LEN + this.bytesOfKeyValueData;
  85362. var width = this.pixelWidth;
  85363. var height = this.pixelHeight;
  85364. var mipmapCount = loadMipmaps ? this.numberOfMipmapLevels : 1;
  85365. for (var level = 0; level < mipmapCount; level++) {
  85366. var imageSize = new Int32Array(this.arrayBuffer, dataOffset, 1)[0]; // size per face, since not supporting array cubemaps
  85367. for (var face = 0; face < this.numberOfFaces; face++) {
  85368. var sampler = this.numberOfFaces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  85369. var byteArray = new Uint8Array(this.arrayBuffer, dataOffset + 4, imageSize);
  85370. gl.compressedTexImage2D(sampler, level, this.glInternalFormat, width, height, 0, byteArray);
  85371. dataOffset += imageSize + 4; // size of the image + 4 for the imageSize field
  85372. dataOffset += 3 - ((imageSize + 3) % 4); // add padding for odd sized image
  85373. }
  85374. width = Math.max(1.0, width * 0.5);
  85375. height = Math.max(1.0, height * 0.5);
  85376. }
  85377. };
  85378. KhronosTextureContainer.HEADER_LEN = 12 + (13 * 4); // identifier + header elements (not including key value meta-data pairs)
  85379. // load types
  85380. KhronosTextureContainer.COMPRESSED_2D = 0; // uses a gl.compressedTexImage2D()
  85381. KhronosTextureContainer.COMPRESSED_3D = 1; // uses a gl.compressedTexImage3D()
  85382. KhronosTextureContainer.TEX_2D = 2; // uses a gl.texImage2D()
  85383. KhronosTextureContainer.TEX_3D = 3; // uses a gl.texImage3D()
  85384. return KhronosTextureContainer;
  85385. }());
  85386. BABYLON.KhronosTextureContainer = KhronosTextureContainer;
  85387. })(BABYLON || (BABYLON = {}));
  85388. //# sourceMappingURL=babylon.khronosTextureContainer.js.map
  85389. var BABYLON;
  85390. (function (BABYLON) {
  85391. var Debug;
  85392. (function (Debug) {
  85393. /**
  85394. * Class used to render a debug view of a given skeleton
  85395. * @see http://www.babylonjs-playground.com/#1BZJVJ#8
  85396. */
  85397. var SkeletonViewer = /** @class */ (function () {
  85398. /**
  85399. * Creates a new SkeletonViewer
  85400. * @param skeleton defines the skeleton to render
  85401. * @param mesh defines the mesh attached to the skeleton
  85402. * @param scene defines the hosting scene
  85403. * @param autoUpdateBonesMatrices defines a boolean indicating if bones matrices must be forced to update before rendering (true by default)
  85404. * @param renderingGroupId defines the rendering group id to use with the viewer
  85405. */
  85406. function SkeletonViewer(
  85407. /** defines the skeleton to render */
  85408. skeleton,
  85409. /** defines the mesh attached to the skeleton */
  85410. mesh, scene,
  85411. /** defines a boolean indicating if bones matrices must be forced to update before rendering (true by default) */
  85412. autoUpdateBonesMatrices,
  85413. /** defines the rendering group id to use with the viewer */
  85414. renderingGroupId) {
  85415. if (autoUpdateBonesMatrices === void 0) { autoUpdateBonesMatrices = true; }
  85416. if (renderingGroupId === void 0) { renderingGroupId = 1; }
  85417. this.skeleton = skeleton;
  85418. this.mesh = mesh;
  85419. this.autoUpdateBonesMatrices = autoUpdateBonesMatrices;
  85420. this.renderingGroupId = renderingGroupId;
  85421. /** Gets or sets the color used to render the skeleton */
  85422. this.color = BABYLON.Color3.White();
  85423. this._debugLines = new Array();
  85424. this._isEnabled = false;
  85425. this._scene = scene;
  85426. this.update();
  85427. this._renderFunction = this.update.bind(this);
  85428. }
  85429. Object.defineProperty(SkeletonViewer.prototype, "isEnabled", {
  85430. get: function () {
  85431. return this._isEnabled;
  85432. },
  85433. /** Gets or sets a boolean indicating if the viewer is enabled */
  85434. set: function (value) {
  85435. if (this._isEnabled === value) {
  85436. return;
  85437. }
  85438. this._isEnabled = value;
  85439. if (value) {
  85440. this._scene.registerBeforeRender(this._renderFunction);
  85441. }
  85442. else {
  85443. this._scene.unregisterBeforeRender(this._renderFunction);
  85444. }
  85445. },
  85446. enumerable: true,
  85447. configurable: true
  85448. });
  85449. SkeletonViewer.prototype._getBonePosition = function (position, bone, meshMat, x, y, z) {
  85450. if (x === void 0) { x = 0; }
  85451. if (y === void 0) { y = 0; }
  85452. if (z === void 0) { z = 0; }
  85453. var tmat = BABYLON.Tmp.Matrix[0];
  85454. var parentBone = bone.getParent();
  85455. tmat.copyFrom(bone.getLocalMatrix());
  85456. if (x !== 0 || y !== 0 || z !== 0) {
  85457. var tmat2 = BABYLON.Tmp.Matrix[1];
  85458. BABYLON.Matrix.IdentityToRef(tmat2);
  85459. tmat2.m[12] = x;
  85460. tmat2.m[13] = y;
  85461. tmat2.m[14] = z;
  85462. tmat2.multiplyToRef(tmat, tmat);
  85463. }
  85464. if (parentBone) {
  85465. tmat.multiplyToRef(parentBone.getAbsoluteTransform(), tmat);
  85466. }
  85467. tmat.multiplyToRef(meshMat, tmat);
  85468. position.x = tmat.m[12];
  85469. position.y = tmat.m[13];
  85470. position.z = tmat.m[14];
  85471. };
  85472. SkeletonViewer.prototype._getLinesForBonesWithLength = function (bones, meshMat) {
  85473. var len = bones.length;
  85474. var meshPos = this.mesh.position;
  85475. for (var i = 0; i < len; i++) {
  85476. var bone = bones[i];
  85477. var points = this._debugLines[i];
  85478. if (!points) {
  85479. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  85480. this._debugLines[i] = points;
  85481. }
  85482. this._getBonePosition(points[0], bone, meshMat);
  85483. this._getBonePosition(points[1], bone, meshMat, 0, bone.length, 0);
  85484. points[0].subtractInPlace(meshPos);
  85485. points[1].subtractInPlace(meshPos);
  85486. }
  85487. };
  85488. SkeletonViewer.prototype._getLinesForBonesNoLength = function (bones, meshMat) {
  85489. var len = bones.length;
  85490. var boneNum = 0;
  85491. var meshPos = this.mesh.position;
  85492. for (var i = len - 1; i >= 0; i--) {
  85493. var childBone = bones[i];
  85494. var parentBone = childBone.getParent();
  85495. if (!parentBone) {
  85496. continue;
  85497. }
  85498. var points = this._debugLines[boneNum];
  85499. if (!points) {
  85500. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  85501. this._debugLines[boneNum] = points;
  85502. }
  85503. childBone.getAbsolutePositionToRef(this.mesh, points[0]);
  85504. parentBone.getAbsolutePositionToRef(this.mesh, points[1]);
  85505. points[0].subtractInPlace(meshPos);
  85506. points[1].subtractInPlace(meshPos);
  85507. boneNum++;
  85508. }
  85509. };
  85510. /** Update the viewer to sync with current skeleton state */
  85511. SkeletonViewer.prototype.update = function () {
  85512. if (this.autoUpdateBonesMatrices) {
  85513. this.skeleton.computeAbsoluteTransforms();
  85514. }
  85515. if (this.skeleton.bones[0].length === undefined) {
  85516. this._getLinesForBonesNoLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  85517. }
  85518. else {
  85519. this._getLinesForBonesWithLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  85520. }
  85521. if (!this._debugMesh) {
  85522. this._debugMesh = BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: null }, this._scene);
  85523. this._debugMesh.renderingGroupId = this.renderingGroupId;
  85524. }
  85525. else {
  85526. BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: this._debugMesh }, this._scene);
  85527. }
  85528. this._debugMesh.position.copyFrom(this.mesh.position);
  85529. this._debugMesh.color = this.color;
  85530. };
  85531. /** Release associated resources */
  85532. SkeletonViewer.prototype.dispose = function () {
  85533. if (this._debugMesh) {
  85534. this.isEnabled = false;
  85535. this._debugMesh.dispose();
  85536. this._debugMesh = null;
  85537. }
  85538. };
  85539. return SkeletonViewer;
  85540. }());
  85541. Debug.SkeletonViewer = SkeletonViewer;
  85542. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  85543. })(BABYLON || (BABYLON = {}));
  85544. //# sourceMappingURL=babylon.skeletonViewer.js.map
  85545. /**
  85546. * Module Debug contains the (visual) components to debug a scene correctly
  85547. */
  85548. var BABYLON;
  85549. (function (BABYLON) {
  85550. var Debug;
  85551. (function (Debug) {
  85552. /**
  85553. * The Axes viewer will show 3 axes in a specific point in space
  85554. */
  85555. var AxesViewer = /** @class */ (function () {
  85556. /**
  85557. * Creates a new AxesViewer
  85558. * @param scene defines the hosting scene
  85559. * @param scaleLines defines a number used to scale line length (1 by default)
  85560. */
  85561. function AxesViewer(scene, scaleLines) {
  85562. if (scaleLines === void 0) { scaleLines = 1; }
  85563. this._xline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  85564. this._yline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  85565. this._zline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  85566. /**
  85567. * Gets or sets a number used to scale line length
  85568. */
  85569. this.scaleLines = 1;
  85570. this.scaleLines = scaleLines;
  85571. this._xmesh = BABYLON.Mesh.CreateLines("xline", this._xline, scene, true);
  85572. this._ymesh = BABYLON.Mesh.CreateLines("yline", this._yline, scene, true);
  85573. this._zmesh = BABYLON.Mesh.CreateLines("zline", this._zline, scene, true);
  85574. this._xmesh.renderingGroupId = 2;
  85575. this._ymesh.renderingGroupId = 2;
  85576. this._zmesh.renderingGroupId = 2;
  85577. this._xmesh.material.checkReadyOnlyOnce = true;
  85578. this._xmesh.color = new BABYLON.Color3(1, 0, 0);
  85579. this._ymesh.material.checkReadyOnlyOnce = true;
  85580. this._ymesh.color = new BABYLON.Color3(0, 1, 0);
  85581. this._zmesh.material.checkReadyOnlyOnce = true;
  85582. this._zmesh.color = new BABYLON.Color3(0, 0, 1);
  85583. this.scene = scene;
  85584. }
  85585. /**
  85586. * Force the viewer to update
  85587. * @param position defines the position of the viewer
  85588. * @param xaxis defines the x axis of the viewer
  85589. * @param yaxis defines the y axis of the viewer
  85590. * @param zaxis defines the z axis of the viewer
  85591. */
  85592. AxesViewer.prototype.update = function (position, xaxis, yaxis, zaxis) {
  85593. var scaleLines = this.scaleLines;
  85594. if (this._xmesh) {
  85595. this._xmesh.position.copyFrom(position);
  85596. }
  85597. if (this._ymesh) {
  85598. this._ymesh.position.copyFrom(position);
  85599. }
  85600. if (this._zmesh) {
  85601. this._zmesh.position.copyFrom(position);
  85602. }
  85603. var point2 = this._xline[1];
  85604. point2.x = xaxis.x * scaleLines;
  85605. point2.y = xaxis.y * scaleLines;
  85606. point2.z = xaxis.z * scaleLines;
  85607. BABYLON.Mesh.CreateLines("", this._xline, null, false, this._xmesh);
  85608. point2 = this._yline[1];
  85609. point2.x = yaxis.x * scaleLines;
  85610. point2.y = yaxis.y * scaleLines;
  85611. point2.z = yaxis.z * scaleLines;
  85612. BABYLON.Mesh.CreateLines("", this._yline, null, false, this._ymesh);
  85613. point2 = this._zline[1];
  85614. point2.x = zaxis.x * scaleLines;
  85615. point2.y = zaxis.y * scaleLines;
  85616. point2.z = zaxis.z * scaleLines;
  85617. BABYLON.Mesh.CreateLines("", this._zline, null, false, this._zmesh);
  85618. };
  85619. /** Releases resources */
  85620. AxesViewer.prototype.dispose = function () {
  85621. if (this._xmesh) {
  85622. this._xmesh.dispose();
  85623. }
  85624. if (this._ymesh) {
  85625. this._ymesh.dispose();
  85626. }
  85627. if (this._zmesh) {
  85628. this._zmesh.dispose();
  85629. }
  85630. this._xmesh = null;
  85631. this._ymesh = null;
  85632. this._zmesh = null;
  85633. this.scene = null;
  85634. };
  85635. return AxesViewer;
  85636. }());
  85637. Debug.AxesViewer = AxesViewer;
  85638. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  85639. })(BABYLON || (BABYLON = {}));
  85640. //# sourceMappingURL=babylon.axesViewer.js.map
  85641. var BABYLON;
  85642. (function (BABYLON) {
  85643. var Debug;
  85644. (function (Debug) {
  85645. /**
  85646. * The BoneAxesViewer will attach 3 axes to a specific bone of a specific mesh
  85647. * @see demo here: https://www.babylonjs-playground.com/#0DE8F4#8
  85648. */
  85649. var BoneAxesViewer = /** @class */ (function (_super) {
  85650. __extends(BoneAxesViewer, _super);
  85651. /**
  85652. * Creates a new BoneAxesViewer
  85653. * @param scene defines the hosting scene
  85654. * @param bone defines the target bone
  85655. * @param mesh defines the target mesh
  85656. * @param scaleLines defines a scaling factor for line length (1 by default)
  85657. */
  85658. function BoneAxesViewer(scene, bone, mesh, scaleLines) {
  85659. if (scaleLines === void 0) { scaleLines = 1; }
  85660. var _this = _super.call(this, scene, scaleLines) || this;
  85661. /** Gets current position */
  85662. _this.pos = BABYLON.Vector3.Zero();
  85663. /** Gets direction of X axis */
  85664. _this.xaxis = BABYLON.Vector3.Zero();
  85665. /** Gets direction of Y axis */
  85666. _this.yaxis = BABYLON.Vector3.Zero();
  85667. /** Gets direction of Z axis */
  85668. _this.zaxis = BABYLON.Vector3.Zero();
  85669. _this.mesh = mesh;
  85670. _this.bone = bone;
  85671. return _this;
  85672. }
  85673. /**
  85674. * Force the viewer to update
  85675. */
  85676. BoneAxesViewer.prototype.update = function () {
  85677. if (!this.mesh || !this.bone) {
  85678. return;
  85679. }
  85680. var bone = this.bone;
  85681. bone.getAbsolutePositionToRef(this.mesh, this.pos);
  85682. bone.getDirectionToRef(BABYLON.Axis.X, this.mesh, this.xaxis);
  85683. bone.getDirectionToRef(BABYLON.Axis.Y, this.mesh, this.yaxis);
  85684. bone.getDirectionToRef(BABYLON.Axis.Z, this.mesh, this.zaxis);
  85685. _super.prototype.update.call(this, this.pos, this.xaxis, this.yaxis, this.zaxis);
  85686. };
  85687. /** Releases resources */
  85688. BoneAxesViewer.prototype.dispose = function () {
  85689. if (this.mesh) {
  85690. this.mesh = null;
  85691. this.bone = null;
  85692. _super.prototype.dispose.call(this);
  85693. }
  85694. };
  85695. return BoneAxesViewer;
  85696. }(Debug.AxesViewer));
  85697. Debug.BoneAxesViewer = BoneAxesViewer;
  85698. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  85699. })(BABYLON || (BABYLON = {}));
  85700. //# sourceMappingURL=babylon.boneAxesViewer.js.map
  85701. var BABYLON;
  85702. (function (BABYLON) {
  85703. var RayHelper = /** @class */ (function () {
  85704. function RayHelper(ray) {
  85705. this.ray = ray;
  85706. }
  85707. RayHelper.CreateAndShow = function (ray, scene, color) {
  85708. var helper = new RayHelper(ray);
  85709. helper.show(scene, color);
  85710. return helper;
  85711. };
  85712. RayHelper.prototype.show = function (scene, color) {
  85713. if (!this._renderFunction && this.ray) {
  85714. var ray = this.ray;
  85715. this._renderFunction = this._render.bind(this);
  85716. this._scene = scene;
  85717. this._renderPoints = [ray.origin, ray.origin.add(ray.direction.scale(ray.length))];
  85718. this._renderLine = BABYLON.Mesh.CreateLines("ray", this._renderPoints, scene, true);
  85719. if (this._renderFunction) {
  85720. this._scene.registerBeforeRender(this._renderFunction);
  85721. }
  85722. }
  85723. if (color && this._renderLine) {
  85724. this._renderLine.color.copyFrom(color);
  85725. }
  85726. };
  85727. RayHelper.prototype.hide = function () {
  85728. if (this._renderFunction && this._scene) {
  85729. this._scene.unregisterBeforeRender(this._renderFunction);
  85730. this._scene = null;
  85731. this._renderFunction = null;
  85732. if (this._renderLine) {
  85733. this._renderLine.dispose();
  85734. this._renderLine = null;
  85735. }
  85736. this._renderPoints = [];
  85737. }
  85738. };
  85739. RayHelper.prototype._render = function () {
  85740. var ray = this.ray;
  85741. if (!ray) {
  85742. return;
  85743. }
  85744. var point = this._renderPoints[1];
  85745. var len = Math.min(ray.length, 1000000);
  85746. point.copyFrom(ray.direction);
  85747. point.scaleInPlace(len);
  85748. point.addInPlace(ray.origin);
  85749. BABYLON.Mesh.CreateLines("ray", this._renderPoints, this._scene, true, this._renderLine);
  85750. };
  85751. RayHelper.prototype.attachToMesh = function (mesh, meshSpaceDirection, meshSpaceOrigin, length) {
  85752. this._attachedToMesh = mesh;
  85753. var ray = this.ray;
  85754. if (!ray) {
  85755. return;
  85756. }
  85757. if (!ray.direction) {
  85758. ray.direction = BABYLON.Vector3.Zero();
  85759. }
  85760. if (!ray.origin) {
  85761. ray.origin = BABYLON.Vector3.Zero();
  85762. }
  85763. if (length) {
  85764. ray.length = length;
  85765. }
  85766. if (!meshSpaceOrigin) {
  85767. meshSpaceOrigin = BABYLON.Vector3.Zero();
  85768. }
  85769. if (!meshSpaceDirection) {
  85770. // -1 so that this will work with Mesh.lookAt
  85771. meshSpaceDirection = new BABYLON.Vector3(0, 0, -1);
  85772. }
  85773. if (!this._meshSpaceDirection) {
  85774. this._meshSpaceDirection = meshSpaceDirection.clone();
  85775. this._meshSpaceOrigin = meshSpaceOrigin.clone();
  85776. }
  85777. else {
  85778. this._meshSpaceDirection.copyFrom(meshSpaceDirection);
  85779. this._meshSpaceOrigin.copyFrom(meshSpaceOrigin);
  85780. }
  85781. if (!this._updateToMeshFunction) {
  85782. this._updateToMeshFunction = this._updateToMesh.bind(this);
  85783. this._attachedToMesh.getScene().registerBeforeRender(this._updateToMeshFunction);
  85784. }
  85785. this._updateToMesh();
  85786. };
  85787. RayHelper.prototype.detachFromMesh = function () {
  85788. if (this._attachedToMesh) {
  85789. if (this._updateToMeshFunction) {
  85790. this._attachedToMesh.getScene().unregisterBeforeRender(this._updateToMeshFunction);
  85791. }
  85792. this._attachedToMesh = null;
  85793. this._updateToMeshFunction = null;
  85794. }
  85795. };
  85796. RayHelper.prototype._updateToMesh = function () {
  85797. var ray = this.ray;
  85798. if (!this._attachedToMesh || !ray) {
  85799. return;
  85800. }
  85801. if (this._attachedToMesh._isDisposed) {
  85802. this.detachFromMesh();
  85803. return;
  85804. }
  85805. this._attachedToMesh.getDirectionToRef(this._meshSpaceDirection, ray.direction);
  85806. BABYLON.Vector3.TransformCoordinatesToRef(this._meshSpaceOrigin, this._attachedToMesh.getWorldMatrix(), ray.origin);
  85807. };
  85808. RayHelper.prototype.dispose = function () {
  85809. this.hide();
  85810. this.detachFromMesh();
  85811. this.ray = null;
  85812. };
  85813. return RayHelper;
  85814. }());
  85815. BABYLON.RayHelper = RayHelper;
  85816. })(BABYLON || (BABYLON = {}));
  85817. //# sourceMappingURL=babylon.rayHelper.js.map
  85818. var BABYLON;
  85819. (function (BABYLON) {
  85820. // load the inspector using require, if not present in the global namespace.
  85821. var DebugLayer = /** @class */ (function () {
  85822. function DebugLayer(scene) {
  85823. this.BJSINSPECTOR = typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  85824. this._scene = scene;
  85825. // load inspector using require, if it doesn't exist on the global namespace.
  85826. }
  85827. /** Creates the inspector window. */
  85828. DebugLayer.prototype._createInspector = function (config) {
  85829. if (config === void 0) { config = {}; }
  85830. var popup = config.popup || false;
  85831. var initialTab = config.initialTab || 0;
  85832. var parentElement = config.parentElement || null;
  85833. if (!this._inspector) {
  85834. this.BJSINSPECTOR = this.BJSINSPECTOR || typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  85835. this._inspector = new this.BJSINSPECTOR.Inspector(this._scene, popup, initialTab, parentElement, config.newColors);
  85836. } // else nothing to do,; instance is already existing
  85837. };
  85838. DebugLayer.prototype.isVisible = function () {
  85839. if (!this._inspector) {
  85840. return false;
  85841. }
  85842. return true;
  85843. };
  85844. DebugLayer.prototype.hide = function () {
  85845. if (this._inspector) {
  85846. try {
  85847. this._inspector.dispose();
  85848. }
  85849. catch (e) {
  85850. // If the inspector has been removed directly from the inspector tool
  85851. }
  85852. this._inspector = null;
  85853. }
  85854. };
  85855. DebugLayer.prototype.show = function (config) {
  85856. if (config === void 0) { config = {}; }
  85857. if (typeof this.BJSINSPECTOR == 'undefined') {
  85858. // Load inspector and add it to the DOM
  85859. BABYLON.Tools.LoadScript(DebugLayer.InspectorURL, this._createInspector.bind(this, config));
  85860. }
  85861. else {
  85862. // Otherwise creates the inspector
  85863. this._createInspector(config);
  85864. }
  85865. };
  85866. /**
  85867. * Gets the active tab
  85868. * @return the index of the active tab or -1 if the inspector is hidden
  85869. */
  85870. DebugLayer.prototype.getActiveTab = function () {
  85871. return this._inspector ? this._inspector.getActiveTabIndex() : -1;
  85872. };
  85873. DebugLayer.InspectorURL = 'https://preview.babylonjs.com/inspector/babylon.inspector.bundle.js';
  85874. return DebugLayer;
  85875. }());
  85876. BABYLON.DebugLayer = DebugLayer;
  85877. })(BABYLON || (BABYLON = {}));
  85878. //# sourceMappingURL=babylon.debugLayer.js.map
  85879. var BABYLON;
  85880. (function (BABYLON) {
  85881. var Debug;
  85882. (function (Debug) {
  85883. /**
  85884. * Used to show the physics impostor around the specific mesh
  85885. */
  85886. var PhysicsViewer = /** @class */ (function () {
  85887. /**
  85888. * Creates a new PhysicsViewer
  85889. * @param scene defines the hosting scene
  85890. */
  85891. function PhysicsViewer(scene) {
  85892. /** @hidden */
  85893. this._impostors = [];
  85894. /** @hidden */
  85895. this._meshes = [];
  85896. /** @hidden */
  85897. this._numMeshes = 0;
  85898. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  85899. var physicEngine = this._scene.getPhysicsEngine();
  85900. if (physicEngine) {
  85901. this._physicsEnginePlugin = physicEngine.getPhysicsPlugin();
  85902. }
  85903. }
  85904. /** @hidden */
  85905. PhysicsViewer.prototype._updateDebugMeshes = function () {
  85906. var plugin = this._physicsEnginePlugin;
  85907. for (var i = 0; i < this._numMeshes; i++) {
  85908. var impostor = this._impostors[i];
  85909. if (!impostor) {
  85910. continue;
  85911. }
  85912. if (impostor.isDisposed) {
  85913. this.hideImpostor(this._impostors[i--]);
  85914. }
  85915. else {
  85916. var mesh = this._meshes[i];
  85917. if (mesh && plugin) {
  85918. plugin.syncMeshWithImpostor(mesh, impostor);
  85919. }
  85920. }
  85921. }
  85922. };
  85923. /**
  85924. * Renders a specified physic impostor
  85925. * @param impostor defines the impostor to render
  85926. */
  85927. PhysicsViewer.prototype.showImpostor = function (impostor) {
  85928. if (!this._scene) {
  85929. return;
  85930. }
  85931. for (var i = 0; i < this._numMeshes; i++) {
  85932. if (this._impostors[i] == impostor) {
  85933. return;
  85934. }
  85935. }
  85936. var debugMesh = this._getDebugMesh(impostor, this._scene);
  85937. if (debugMesh) {
  85938. this._impostors[this._numMeshes] = impostor;
  85939. this._meshes[this._numMeshes] = debugMesh;
  85940. if (this._numMeshes === 0) {
  85941. this._renderFunction = this._updateDebugMeshes.bind(this);
  85942. this._scene.registerBeforeRender(this._renderFunction);
  85943. }
  85944. this._numMeshes++;
  85945. }
  85946. };
  85947. /**
  85948. * Hides a specified physic impostor
  85949. * @param impostor defines the impostor to hide
  85950. */
  85951. PhysicsViewer.prototype.hideImpostor = function (impostor) {
  85952. if (!impostor || !this._scene) {
  85953. return;
  85954. }
  85955. var removed = false;
  85956. for (var i = 0; i < this._numMeshes; i++) {
  85957. if (this._impostors[i] == impostor) {
  85958. var mesh = this._meshes[i];
  85959. if (!mesh) {
  85960. continue;
  85961. }
  85962. this._scene.removeMesh(mesh);
  85963. mesh.dispose();
  85964. this._numMeshes--;
  85965. if (this._numMeshes > 0) {
  85966. this._meshes[i] = this._meshes[this._numMeshes];
  85967. this._impostors[i] = this._impostors[this._numMeshes];
  85968. this._meshes[this._numMeshes] = null;
  85969. this._impostors[this._numMeshes] = null;
  85970. }
  85971. else {
  85972. this._meshes[0] = null;
  85973. this._impostors[0] = null;
  85974. }
  85975. removed = true;
  85976. break;
  85977. }
  85978. }
  85979. if (removed && this._numMeshes === 0) {
  85980. this._scene.unregisterBeforeRender(this._renderFunction);
  85981. }
  85982. };
  85983. PhysicsViewer.prototype._getDebugMaterial = function (scene) {
  85984. if (!this._debugMaterial) {
  85985. this._debugMaterial = new BABYLON.StandardMaterial('', scene);
  85986. this._debugMaterial.wireframe = true;
  85987. }
  85988. return this._debugMaterial;
  85989. };
  85990. PhysicsViewer.prototype._getDebugBoxMesh = function (scene) {
  85991. if (!this._debugBoxMesh) {
  85992. this._debugBoxMesh = BABYLON.MeshBuilder.CreateBox('physicsBodyBoxViewMesh', { size: 1 }, scene);
  85993. this._debugBoxMesh.renderingGroupId = 1;
  85994. this._debugBoxMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  85995. this._debugBoxMesh.material = this._getDebugMaterial(scene);
  85996. scene.removeMesh(this._debugBoxMesh);
  85997. }
  85998. return this._debugBoxMesh.createInstance('physicsBodyBoxViewInstance');
  85999. };
  86000. PhysicsViewer.prototype._getDebugSphereMesh = function (scene) {
  86001. if (!this._debugSphereMesh) {
  86002. this._debugSphereMesh = BABYLON.MeshBuilder.CreateSphere('physicsBodySphereViewMesh', { diameter: 1 }, scene);
  86003. this._debugSphereMesh.renderingGroupId = 1;
  86004. this._debugSphereMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  86005. this._debugSphereMesh.material = this._getDebugMaterial(scene);
  86006. scene.removeMesh(this._debugSphereMesh);
  86007. }
  86008. return this._debugSphereMesh.createInstance('physicsBodyBoxViewInstance');
  86009. };
  86010. PhysicsViewer.prototype._getDebugMesh = function (impostor, scene) {
  86011. var mesh = null;
  86012. if (impostor.type == BABYLON.PhysicsImpostor.BoxImpostor) {
  86013. mesh = this._getDebugBoxMesh(scene);
  86014. impostor.getBoxSizeToRef(mesh.scaling);
  86015. }
  86016. else if (impostor.type == BABYLON.PhysicsImpostor.SphereImpostor) {
  86017. mesh = this._getDebugSphereMesh(scene);
  86018. var radius = impostor.getRadius();
  86019. mesh.scaling.x = radius * 2;
  86020. mesh.scaling.y = radius * 2;
  86021. mesh.scaling.z = radius * 2;
  86022. }
  86023. return mesh;
  86024. };
  86025. /** Releases all resources */
  86026. PhysicsViewer.prototype.dispose = function () {
  86027. for (var i = 0; i < this._numMeshes; i++) {
  86028. this.hideImpostor(this._impostors[i]);
  86029. }
  86030. if (this._debugBoxMesh) {
  86031. this._debugBoxMesh.dispose();
  86032. }
  86033. if (this._debugSphereMesh) {
  86034. this._debugSphereMesh.dispose();
  86035. }
  86036. if (this._debugMaterial) {
  86037. this._debugMaterial.dispose();
  86038. }
  86039. this._impostors.length = 0;
  86040. this._scene = null;
  86041. this._physicsEnginePlugin = null;
  86042. };
  86043. return PhysicsViewer;
  86044. }());
  86045. Debug.PhysicsViewer = PhysicsViewer;
  86046. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  86047. })(BABYLON || (BABYLON = {}));
  86048. //# sourceMappingURL=babylon.physicsViewer.js.map
  86049. var BABYLON;
  86050. (function (BABYLON) {
  86051. var BoundingBoxRenderer = /** @class */ (function () {
  86052. function BoundingBoxRenderer(scene) {
  86053. this.frontColor = new BABYLON.Color3(1, 1, 1);
  86054. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  86055. this.showBackLines = true;
  86056. this.renderList = new BABYLON.SmartArray(32);
  86057. this._vertexBuffers = {};
  86058. this._scene = scene;
  86059. }
  86060. BoundingBoxRenderer.prototype._prepareRessources = function () {
  86061. if (this._colorShader) {
  86062. return;
  86063. }
  86064. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this._scene, "color", {
  86065. attributes: [BABYLON.VertexBuffer.PositionKind],
  86066. uniforms: ["world", "viewProjection", "color"]
  86067. });
  86068. var engine = this._scene.getEngine();
  86069. var boxdata = BABYLON.VertexData.CreateBox({ size: 1.0 });
  86070. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  86071. this._createIndexBuffer();
  86072. };
  86073. BoundingBoxRenderer.prototype._createIndexBuffer = function () {
  86074. var engine = this._scene.getEngine();
  86075. 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]);
  86076. };
  86077. BoundingBoxRenderer.prototype._rebuild = function () {
  86078. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  86079. if (vb) {
  86080. vb._rebuild();
  86081. }
  86082. this._createIndexBuffer();
  86083. };
  86084. BoundingBoxRenderer.prototype.reset = function () {
  86085. this.renderList.reset();
  86086. };
  86087. BoundingBoxRenderer.prototype.render = function () {
  86088. if (this.renderList.length === 0) {
  86089. return;
  86090. }
  86091. this._prepareRessources();
  86092. if (!this._colorShader.isReady()) {
  86093. return;
  86094. }
  86095. var engine = this._scene.getEngine();
  86096. engine.setDepthWrite(false);
  86097. this._colorShader._preBind();
  86098. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  86099. var boundingBox = this.renderList.data[boundingBoxIndex];
  86100. var min = boundingBox.minimum;
  86101. var max = boundingBox.maximum;
  86102. var diff = max.subtract(min);
  86103. var median = min.add(diff.scale(0.5));
  86104. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  86105. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  86106. .multiply(boundingBox.getWorldMatrix());
  86107. // VBOs
  86108. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  86109. if (this.showBackLines) {
  86110. // Back
  86111. engine.setDepthFunctionToGreaterOrEqual();
  86112. this._scene.resetCachedMaterial();
  86113. this._colorShader.setColor4("color", this.backColor.toColor4());
  86114. this._colorShader.bind(worldMatrix);
  86115. // Draw order
  86116. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  86117. }
  86118. // Front
  86119. engine.setDepthFunctionToLess();
  86120. this._scene.resetCachedMaterial();
  86121. this._colorShader.setColor4("color", this.frontColor.toColor4());
  86122. this._colorShader.bind(worldMatrix);
  86123. // Draw order
  86124. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  86125. }
  86126. this._colorShader.unbind();
  86127. engine.setDepthFunctionToLessOrEqual();
  86128. engine.setDepthWrite(true);
  86129. };
  86130. BoundingBoxRenderer.prototype.renderOcclusionBoundingBox = function (mesh) {
  86131. this._prepareRessources();
  86132. if (!this._colorShader.isReady() || !mesh._boundingInfo) {
  86133. return;
  86134. }
  86135. var engine = this._scene.getEngine();
  86136. engine.setDepthWrite(false);
  86137. engine.setColorWrite(false);
  86138. this._colorShader._preBind();
  86139. var boundingBox = mesh._boundingInfo.boundingBox;
  86140. var min = boundingBox.minimum;
  86141. var max = boundingBox.maximum;
  86142. var diff = max.subtract(min);
  86143. var median = min.add(diff.scale(0.5));
  86144. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  86145. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  86146. .multiply(boundingBox.getWorldMatrix());
  86147. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  86148. engine.setDepthFunctionToLess();
  86149. this._scene.resetCachedMaterial();
  86150. this._colorShader.bind(worldMatrix);
  86151. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  86152. this._colorShader.unbind();
  86153. engine.setDepthFunctionToLessOrEqual();
  86154. engine.setDepthWrite(true);
  86155. engine.setColorWrite(true);
  86156. };
  86157. BoundingBoxRenderer.prototype.dispose = function () {
  86158. if (!this._colorShader) {
  86159. return;
  86160. }
  86161. this.renderList.dispose();
  86162. this._colorShader.dispose();
  86163. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  86164. if (buffer) {
  86165. buffer.dispose();
  86166. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  86167. }
  86168. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  86169. };
  86170. return BoundingBoxRenderer;
  86171. }());
  86172. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  86173. })(BABYLON || (BABYLON = {}));
  86174. //# sourceMappingURL=babylon.boundingBoxRenderer.js.map
  86175. var BABYLON;
  86176. (function (BABYLON) {
  86177. /**
  86178. * Renders a layer on top of an existing scene
  86179. */
  86180. var UtilityLayerRenderer = /** @class */ (function () {
  86181. /**
  86182. * Instantiates a UtilityLayerRenderer
  86183. * @param originalScene the original scene that will be rendered on top of
  86184. */
  86185. function UtilityLayerRenderer(/** the original scene that will be rendered on top of */ originalScene) {
  86186. var _this = this;
  86187. this.originalScene = originalScene;
  86188. /**
  86189. * If the utility layer should automatically be rendered on top of existing scene
  86190. */
  86191. this.shouldRender = true;
  86192. // Create scene which will be rendered in the foreground and remove it from being referenced by engine to avoid interfering with existing app
  86193. this.utilityLayerScene = new BABYLON.Scene(originalScene.getEngine());
  86194. originalScene.getEngine().scenes.pop();
  86195. // Render directly on top of existing scene without clearing
  86196. this.utilityLayerScene.autoClear = false;
  86197. this._afterRenderObserver = this.originalScene.onAfterRenderObservable.add(function () {
  86198. if (_this.shouldRender) {
  86199. _this.render();
  86200. }
  86201. });
  86202. this._sceneDisposeObserver = this.originalScene.onDisposeObservable.add(function () {
  86203. _this.dispose();
  86204. });
  86205. }
  86206. /**
  86207. * Renders the utility layers scene on top of the original scene
  86208. */
  86209. UtilityLayerRenderer.prototype.render = function () {
  86210. this._updateCamera();
  86211. this.utilityLayerScene.render(false);
  86212. };
  86213. /**
  86214. * Disposes of the renderer
  86215. */
  86216. UtilityLayerRenderer.prototype.dispose = function () {
  86217. if (this._afterRenderObserver) {
  86218. this.originalScene.onAfterRenderObservable.remove(this._afterRenderObserver);
  86219. }
  86220. if (this._sceneDisposeObserver) {
  86221. this.originalScene.onDisposeObservable.remove(this._sceneDisposeObserver);
  86222. }
  86223. this.utilityLayerScene.dispose();
  86224. };
  86225. UtilityLayerRenderer.prototype._updateCamera = function () {
  86226. this.utilityLayerScene.activeCamera = this.originalScene.activeCamera;
  86227. };
  86228. return UtilityLayerRenderer;
  86229. }());
  86230. BABYLON.UtilityLayerRenderer = UtilityLayerRenderer;
  86231. })(BABYLON || (BABYLON = {}));
  86232. //# sourceMappingURL=babylon.utilityLayerRenderer.js.map
  86233. var BABYLON;
  86234. (function (BABYLON) {
  86235. /**
  86236. * Renders gizmos on top of an existing scene which provide controls for position, rotation, etc.
  86237. */
  86238. var Gizmo = /** @class */ (function () {
  86239. /**
  86240. * Creates a gizmo
  86241. * @param gizmoLayer The utility layer the gizmo will be added to
  86242. */
  86243. function Gizmo(/** The utility layer the gizmo will be added to */ gizmoLayer) {
  86244. var _this = this;
  86245. this.gizmoLayer = gizmoLayer;
  86246. this._rootMesh = new BABYLON.Mesh("gizmoRootNode", gizmoLayer.utilityLayerScene);
  86247. this._beforeRenderObserver = this.gizmoLayer.utilityLayerScene.onBeforeRenderObservable.add(function () {
  86248. if (_this.gizmoLayer.utilityLayerScene.activeCamera && _this.attachedMesh) {
  86249. var dist = _this.attachedMesh.position.subtract(_this.gizmoLayer.utilityLayerScene.activeCamera.position).length() / 5;
  86250. _this._rootMesh.scaling.set(dist, dist, dist);
  86251. }
  86252. if (_this.attachedMesh) {
  86253. _this._rootMesh.position.copyFrom(_this.attachedMesh.position);
  86254. }
  86255. });
  86256. }
  86257. /**
  86258. * Disposes of the gizmo
  86259. */
  86260. Gizmo.prototype.dispose = function () {
  86261. this._rootMesh.dispose();
  86262. if (this._beforeRenderObserver) {
  86263. this.gizmoLayer.utilityLayerScene.onBeforeRenderObservable.remove(this._beforeRenderObserver);
  86264. }
  86265. };
  86266. return Gizmo;
  86267. }());
  86268. BABYLON.Gizmo = Gizmo;
  86269. })(BABYLON || (BABYLON = {}));
  86270. //# sourceMappingURL=babylon.gizmo.js.map
  86271. var BABYLON;
  86272. (function (BABYLON) {
  86273. /**
  86274. * Single axis drag gizmo
  86275. */
  86276. var AxisDragGizmo = /** @class */ (function (_super) {
  86277. __extends(AxisDragGizmo, _super);
  86278. /**
  86279. * Creates an AxisDragGizmo
  86280. * @param gizmoLayer The utility layer the gizmo will be added to
  86281. * @param dragAxis The axis which the gizmo will be able to drag on
  86282. * @param color The color of the gizmo
  86283. */
  86284. function AxisDragGizmo(gizmoLayer, dragAxis, color) {
  86285. var _this = _super.call(this, gizmoLayer) || this;
  86286. // Create Material
  86287. var coloredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  86288. coloredMaterial.disableLighting = true;
  86289. coloredMaterial.emissiveColor = color;
  86290. // Build mesh on root node
  86291. var arrowMesh = BABYLON.MeshBuilder.CreateCylinder("yPosMesh", { diameterTop: 0, height: 2, tessellation: 96 }, gizmoLayer.utilityLayerScene);
  86292. var arrowTail = BABYLON.MeshBuilder.CreateCylinder("yPosMesh", { diameter: 0.03, height: 0.2, tessellation: 96 }, gizmoLayer.utilityLayerScene);
  86293. _this._rootMesh.addChild(arrowMesh);
  86294. _this._rootMesh.addChild(arrowTail);
  86295. // Position arrow pointing in its drag axis
  86296. arrowMesh.scaling.scaleInPlace(0.1);
  86297. arrowMesh.material = coloredMaterial;
  86298. arrowMesh.rotation.x = Math.PI / 2;
  86299. arrowMesh.position.z += 0.3;
  86300. arrowTail.rotation.x = Math.PI / 2;
  86301. arrowTail.material = coloredMaterial;
  86302. arrowTail.position.z += 0.2;
  86303. _this._rootMesh.lookAt(_this._rootMesh.position.subtract(dragAxis));
  86304. // Add drag behavior to handle events when the gizmo is dragged
  86305. _this._dragBehavior = new BABYLON.PointerDragBehavior({ dragAxis: dragAxis, pointerObservableScene: gizmoLayer.originalScene });
  86306. _this._dragBehavior.moveAttached = false;
  86307. _this._rootMesh.addBehavior(_this._dragBehavior);
  86308. _this._dragBehavior.onDragObservable.add(function (event) {
  86309. if (_this.attachedMesh) {
  86310. _this.attachedMesh.position.addInPlace(event.delta);
  86311. }
  86312. });
  86313. return _this;
  86314. }
  86315. /**
  86316. * Disposes of the gizmo
  86317. */
  86318. AxisDragGizmo.prototype.dispose = function () {
  86319. this._dragBehavior.detach();
  86320. _super.prototype.dispose.call(this);
  86321. };
  86322. return AxisDragGizmo;
  86323. }(BABYLON.Gizmo));
  86324. BABYLON.AxisDragGizmo = AxisDragGizmo;
  86325. })(BABYLON || (BABYLON = {}));
  86326. //# sourceMappingURL=babylon.axisDragGizmo.js.map
  86327. var BABYLON;
  86328. (function (BABYLON) {
  86329. /**
  86330. * Gizmo that enables dragging a mesh along 3 axis
  86331. */
  86332. var PositionGizmo = /** @class */ (function (_super) {
  86333. __extends(PositionGizmo, _super);
  86334. /**
  86335. * Creates a PositionGizmo
  86336. * @param gizmoLayer The utility layer the gizmo will be added to
  86337. */
  86338. function PositionGizmo(gizmoLayer) {
  86339. var _this = _super.call(this, gizmoLayer) || this;
  86340. _this._xDrag = new BABYLON.AxisDragGizmo(gizmoLayer, new BABYLON.Vector3(1, 0, 0), BABYLON.Color3.FromHexString("#00b894"));
  86341. _this._yDrag = new BABYLON.AxisDragGizmo(gizmoLayer, new BABYLON.Vector3(0, 1, 0), BABYLON.Color3.FromHexString("#d63031"));
  86342. _this._zDrag = new BABYLON.AxisDragGizmo(gizmoLayer, new BABYLON.Vector3(0, 0, 1), BABYLON.Color3.FromHexString("#0984e3"));
  86343. return _this;
  86344. }
  86345. Object.defineProperty(PositionGizmo.prototype, "attachedMesh", {
  86346. set: function (mesh) {
  86347. this._xDrag.attachedMesh = mesh;
  86348. this._yDrag.attachedMesh = mesh;
  86349. this._zDrag.attachedMesh = mesh;
  86350. },
  86351. enumerable: true,
  86352. configurable: true
  86353. });
  86354. /**
  86355. * Disposes of the gizmo
  86356. */
  86357. PositionGizmo.prototype.dispose = function () {
  86358. this._xDrag.dispose();
  86359. this._yDrag.dispose();
  86360. this._zDrag.dispose();
  86361. };
  86362. return PositionGizmo;
  86363. }(BABYLON.Gizmo));
  86364. BABYLON.PositionGizmo = PositionGizmo;
  86365. })(BABYLON || (BABYLON = {}));
  86366. //# sourceMappingURL=babylon.positionGizmo.js.map
  86367. var BABYLON;
  86368. (function (BABYLON) {
  86369. /**
  86370. * Defines a target to use with MorphTargetManager
  86371. * @see http://doc.babylonjs.com/how_to/how_to_use_morphtargets
  86372. */
  86373. var MorphTarget = /** @class */ (function () {
  86374. /**
  86375. * Creates a new MorphTarget
  86376. * @param name defines the name of the target
  86377. * @param influence defines the influence to use
  86378. */
  86379. function MorphTarget(
  86380. /** defines the name of the target */
  86381. name, influence, scene) {
  86382. if (influence === void 0) { influence = 0; }
  86383. if (scene === void 0) { scene = null; }
  86384. this.name = name;
  86385. /**
  86386. * Gets or sets the list of animations
  86387. */
  86388. this.animations = new Array();
  86389. this._positions = null;
  86390. this._normals = null;
  86391. this._tangents = null;
  86392. /**
  86393. * Observable raised when the influence changes
  86394. */
  86395. this.onInfluenceChanged = new BABYLON.Observable();
  86396. this._animationPropertiesOverride = null;
  86397. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  86398. this.influence = influence;
  86399. }
  86400. Object.defineProperty(MorphTarget.prototype, "influence", {
  86401. /**
  86402. * Gets or sets the influence of this target (ie. its weight in the overall morphing)
  86403. */
  86404. get: function () {
  86405. return this._influence;
  86406. },
  86407. set: function (influence) {
  86408. if (this._influence === influence) {
  86409. return;
  86410. }
  86411. var previous = this._influence;
  86412. this._influence = influence;
  86413. if (this.onInfluenceChanged.hasObservers) {
  86414. this.onInfluenceChanged.notifyObservers(previous === 0 || influence === 0);
  86415. }
  86416. },
  86417. enumerable: true,
  86418. configurable: true
  86419. });
  86420. Object.defineProperty(MorphTarget.prototype, "animationPropertiesOverride", {
  86421. /**
  86422. * Gets or sets the animation properties override
  86423. */
  86424. get: function () {
  86425. if (!this._animationPropertiesOverride && this._scene) {
  86426. return this._scene.animationPropertiesOverride;
  86427. }
  86428. return this._animationPropertiesOverride;
  86429. },
  86430. set: function (value) {
  86431. this._animationPropertiesOverride = value;
  86432. },
  86433. enumerable: true,
  86434. configurable: true
  86435. });
  86436. Object.defineProperty(MorphTarget.prototype, "hasPositions", {
  86437. /**
  86438. * Gets a boolean defining if the target contains position data
  86439. */
  86440. get: function () {
  86441. return !!this._positions;
  86442. },
  86443. enumerable: true,
  86444. configurable: true
  86445. });
  86446. Object.defineProperty(MorphTarget.prototype, "hasNormals", {
  86447. /**
  86448. * Gets a boolean defining if the target contains normal data
  86449. */
  86450. get: function () {
  86451. return !!this._normals;
  86452. },
  86453. enumerable: true,
  86454. configurable: true
  86455. });
  86456. Object.defineProperty(MorphTarget.prototype, "hasTangents", {
  86457. /**
  86458. * Gets a boolean defining if the target contains tangent data
  86459. */
  86460. get: function () {
  86461. return !!this._tangents;
  86462. },
  86463. enumerable: true,
  86464. configurable: true
  86465. });
  86466. /**
  86467. * Affects position data to this target
  86468. * @param data defines the position data to use
  86469. */
  86470. MorphTarget.prototype.setPositions = function (data) {
  86471. this._positions = data;
  86472. };
  86473. /**
  86474. * Gets the position data stored in this target
  86475. * @returns a FloatArray containing the position data (or null if not present)
  86476. */
  86477. MorphTarget.prototype.getPositions = function () {
  86478. return this._positions;
  86479. };
  86480. /**
  86481. * Affects normal data to this target
  86482. * @param data defines the normal data to use
  86483. */
  86484. MorphTarget.prototype.setNormals = function (data) {
  86485. this._normals = data;
  86486. };
  86487. /**
  86488. * Gets the normal data stored in this target
  86489. * @returns a FloatArray containing the normal data (or null if not present)
  86490. */
  86491. MorphTarget.prototype.getNormals = function () {
  86492. return this._normals;
  86493. };
  86494. /**
  86495. * Affects tangent data to this target
  86496. * @param data defines the tangent data to use
  86497. */
  86498. MorphTarget.prototype.setTangents = function (data) {
  86499. this._tangents = data;
  86500. };
  86501. /**
  86502. * Gets the tangent data stored in this target
  86503. * @returns a FloatArray containing the tangent data (or null if not present)
  86504. */
  86505. MorphTarget.prototype.getTangents = function () {
  86506. return this._tangents;
  86507. };
  86508. /**
  86509. * Serializes the current target into a Serialization object
  86510. * @returns the serialized object
  86511. */
  86512. MorphTarget.prototype.serialize = function () {
  86513. var serializationObject = {};
  86514. serializationObject.name = this.name;
  86515. serializationObject.influence = this.influence;
  86516. serializationObject.positions = Array.prototype.slice.call(this.getPositions());
  86517. if (this.hasNormals) {
  86518. serializationObject.normals = Array.prototype.slice.call(this.getNormals());
  86519. }
  86520. if (this.hasTangents) {
  86521. serializationObject.tangents = Array.prototype.slice.call(this.getTangents());
  86522. }
  86523. // Animations
  86524. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  86525. return serializationObject;
  86526. };
  86527. // Statics
  86528. /**
  86529. * Creates a new target from serialized data
  86530. * @param serializationObject defines the serialized data to use
  86531. * @returns a new MorphTarget
  86532. */
  86533. MorphTarget.Parse = function (serializationObject) {
  86534. var result = new MorphTarget(serializationObject.name, serializationObject.influence);
  86535. result.setPositions(serializationObject.positions);
  86536. if (serializationObject.normals) {
  86537. result.setNormals(serializationObject.normals);
  86538. }
  86539. if (serializationObject.tangents) {
  86540. result.setTangents(serializationObject.tangents);
  86541. }
  86542. // Animations
  86543. if (serializationObject.animations) {
  86544. for (var animationIndex = 0; animationIndex < serializationObject.animations.length; animationIndex++) {
  86545. var parsedAnimation = serializationObject.animations[animationIndex];
  86546. result.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  86547. }
  86548. }
  86549. return result;
  86550. };
  86551. /**
  86552. * Creates a MorphTarget from mesh data
  86553. * @param mesh defines the source mesh
  86554. * @param name defines the name to use for the new target
  86555. * @param influence defines the influence to attach to the target
  86556. * @returns a new MorphTarget
  86557. */
  86558. MorphTarget.FromMesh = function (mesh, name, influence) {
  86559. if (!name) {
  86560. name = mesh.name;
  86561. }
  86562. var result = new MorphTarget(name, influence, mesh.getScene());
  86563. result.setPositions(mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  86564. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  86565. result.setNormals(mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  86566. }
  86567. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  86568. result.setTangents(mesh.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  86569. }
  86570. return result;
  86571. };
  86572. return MorphTarget;
  86573. }());
  86574. BABYLON.MorphTarget = MorphTarget;
  86575. })(BABYLON || (BABYLON = {}));
  86576. //# sourceMappingURL=babylon.morphTarget.js.map
  86577. var BABYLON;
  86578. (function (BABYLON) {
  86579. /**
  86580. * This class is used to deform meshes using morphing between different targets
  86581. * @see http://doc.babylonjs.com/how_to/how_to_use_morphtargets
  86582. */
  86583. var MorphTargetManager = /** @class */ (function () {
  86584. /**
  86585. * Creates a new MorphTargetManager
  86586. * @param scene defines the current scene
  86587. */
  86588. function MorphTargetManager(scene) {
  86589. if (scene === void 0) { scene = null; }
  86590. this._targets = new Array();
  86591. this._targetObservable = new Array();
  86592. this._activeTargets = new BABYLON.SmartArray(16);
  86593. this._supportsNormals = false;
  86594. this._supportsTangents = false;
  86595. this._vertexCount = 0;
  86596. this._uniqueId = 0;
  86597. this._tempInfluences = new Array();
  86598. if (!scene) {
  86599. scene = BABYLON.Engine.LastCreatedScene;
  86600. }
  86601. this._scene = scene;
  86602. if (this._scene) {
  86603. this._scene.morphTargetManagers.push(this);
  86604. this._uniqueId = this._scene.getUniqueId();
  86605. }
  86606. }
  86607. Object.defineProperty(MorphTargetManager.prototype, "uniqueId", {
  86608. /**
  86609. * Gets the unique ID of this manager
  86610. */
  86611. get: function () {
  86612. return this._uniqueId;
  86613. },
  86614. enumerable: true,
  86615. configurable: true
  86616. });
  86617. Object.defineProperty(MorphTargetManager.prototype, "vertexCount", {
  86618. /**
  86619. * Gets the number of vertices handled by this manager
  86620. */
  86621. get: function () {
  86622. return this._vertexCount;
  86623. },
  86624. enumerable: true,
  86625. configurable: true
  86626. });
  86627. Object.defineProperty(MorphTargetManager.prototype, "supportsNormals", {
  86628. /**
  86629. * Gets a boolean indicating if this manager supports morphing of normals
  86630. */
  86631. get: function () {
  86632. return this._supportsNormals;
  86633. },
  86634. enumerable: true,
  86635. configurable: true
  86636. });
  86637. Object.defineProperty(MorphTargetManager.prototype, "supportsTangents", {
  86638. /**
  86639. * Gets a boolean indicating if this manager supports morphing of tangents
  86640. */
  86641. get: function () {
  86642. return this._supportsTangents;
  86643. },
  86644. enumerable: true,
  86645. configurable: true
  86646. });
  86647. Object.defineProperty(MorphTargetManager.prototype, "numTargets", {
  86648. /**
  86649. * Gets the number of targets stored in this manager
  86650. */
  86651. get: function () {
  86652. return this._targets.length;
  86653. },
  86654. enumerable: true,
  86655. configurable: true
  86656. });
  86657. Object.defineProperty(MorphTargetManager.prototype, "numInfluencers", {
  86658. /**
  86659. * Gets the number of influencers (ie. the number of targets with influences > 0)
  86660. */
  86661. get: function () {
  86662. return this._activeTargets.length;
  86663. },
  86664. enumerable: true,
  86665. configurable: true
  86666. });
  86667. Object.defineProperty(MorphTargetManager.prototype, "influences", {
  86668. /**
  86669. * Gets the list of influences (one per target)
  86670. */
  86671. get: function () {
  86672. return this._influences;
  86673. },
  86674. enumerable: true,
  86675. configurable: true
  86676. });
  86677. /**
  86678. * Gets the active target at specified index. An active target is a target with an influence > 0
  86679. * @param index defines the index to check
  86680. * @returns the requested target
  86681. */
  86682. MorphTargetManager.prototype.getActiveTarget = function (index) {
  86683. return this._activeTargets.data[index];
  86684. };
  86685. /**
  86686. * Gets the target at specified index
  86687. * @param index defines the index to check
  86688. * @returns the requested target
  86689. */
  86690. MorphTargetManager.prototype.getTarget = function (index) {
  86691. return this._targets[index];
  86692. };
  86693. /**
  86694. * Add a new target to this manager
  86695. * @param target defines the target to add
  86696. */
  86697. MorphTargetManager.prototype.addTarget = function (target) {
  86698. var _this = this;
  86699. this._targets.push(target);
  86700. this._targetObservable.push(target.onInfluenceChanged.add(function (needUpdate) {
  86701. _this._syncActiveTargets(needUpdate);
  86702. }));
  86703. this._syncActiveTargets(true);
  86704. };
  86705. /**
  86706. * Removes a target from the manager
  86707. * @param target defines the target to remove
  86708. */
  86709. MorphTargetManager.prototype.removeTarget = function (target) {
  86710. var index = this._targets.indexOf(target);
  86711. if (index >= 0) {
  86712. this._targets.splice(index, 1);
  86713. target.onInfluenceChanged.remove(this._targetObservable.splice(index, 1)[0]);
  86714. this._syncActiveTargets(true);
  86715. }
  86716. };
  86717. /**
  86718. * Serializes the current manager into a Serialization object
  86719. * @returns the serialized object
  86720. */
  86721. MorphTargetManager.prototype.serialize = function () {
  86722. var serializationObject = {};
  86723. serializationObject.id = this.uniqueId;
  86724. serializationObject.targets = [];
  86725. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  86726. var target = _a[_i];
  86727. serializationObject.targets.push(target.serialize());
  86728. }
  86729. return serializationObject;
  86730. };
  86731. MorphTargetManager.prototype._syncActiveTargets = function (needUpdate) {
  86732. var influenceCount = 0;
  86733. this._activeTargets.reset();
  86734. this._supportsNormals = true;
  86735. this._supportsTangents = true;
  86736. this._vertexCount = 0;
  86737. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  86738. var target = _a[_i];
  86739. this._activeTargets.push(target);
  86740. this._tempInfluences[influenceCount++] = target.influence;
  86741. var positions = target.getPositions();
  86742. if (positions) {
  86743. this._supportsNormals = this._supportsNormals && target.hasNormals;
  86744. this._supportsTangents = this._supportsTangents && target.hasTangents;
  86745. var vertexCount = positions.length / 3;
  86746. if (this._vertexCount === 0) {
  86747. this._vertexCount = vertexCount;
  86748. }
  86749. else if (this._vertexCount !== vertexCount) {
  86750. BABYLON.Tools.Error("Incompatible target. Targets must all have the same vertices count.");
  86751. return;
  86752. }
  86753. }
  86754. }
  86755. if (!this._influences || this._influences.length !== influenceCount) {
  86756. this._influences = new Float32Array(influenceCount);
  86757. }
  86758. for (var index = 0; index < influenceCount; index++) {
  86759. this._influences[index] = this._tempInfluences[index];
  86760. }
  86761. if (needUpdate) {
  86762. this.synchronize();
  86763. }
  86764. };
  86765. /**
  86766. * Syncrhonize the targets with all the meshes using this morph target manager
  86767. */
  86768. MorphTargetManager.prototype.synchronize = function () {
  86769. if (!this._scene) {
  86770. return;
  86771. }
  86772. // Flag meshes as dirty to resync with the active targets
  86773. for (var _i = 0, _a = this._scene.meshes; _i < _a.length; _i++) {
  86774. var mesh = _a[_i];
  86775. if (mesh.morphTargetManager === this) {
  86776. mesh._syncGeometryWithMorphTargetManager();
  86777. }
  86778. }
  86779. };
  86780. // Statics
  86781. /**
  86782. * Creates a new MorphTargetManager from serialized data
  86783. * @param serializationObject defines the serialized data
  86784. * @param scene defines the hosting scene
  86785. * @returns the new MorphTargetManager
  86786. */
  86787. MorphTargetManager.Parse = function (serializationObject, scene) {
  86788. var result = new MorphTargetManager(scene);
  86789. result._uniqueId = serializationObject.id;
  86790. for (var _i = 0, _a = serializationObject.targets; _i < _a.length; _i++) {
  86791. var targetData = _a[_i];
  86792. result.addTarget(BABYLON.MorphTarget.Parse(targetData));
  86793. }
  86794. return result;
  86795. };
  86796. return MorphTargetManager;
  86797. }());
  86798. BABYLON.MorphTargetManager = MorphTargetManager;
  86799. })(BABYLON || (BABYLON = {}));
  86800. //# sourceMappingURL=babylon.morphTargetManager.js.map
  86801. var BABYLON;
  86802. (function (BABYLON) {
  86803. var Octree = /** @class */ (function () {
  86804. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  86805. if (maxDepth === void 0) { maxDepth = 2; }
  86806. this.maxDepth = maxDepth;
  86807. this.dynamicContent = new Array();
  86808. this._maxBlockCapacity = maxBlockCapacity || 64;
  86809. this._selectionContent = new BABYLON.SmartArrayNoDuplicate(1024);
  86810. this._creationFunc = creationFunc;
  86811. }
  86812. // Methods
  86813. Octree.prototype.update = function (worldMin, worldMax, entries) {
  86814. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  86815. };
  86816. Octree.prototype.addMesh = function (entry) {
  86817. for (var index = 0; index < this.blocks.length; index++) {
  86818. var block = this.blocks[index];
  86819. block.addEntry(entry);
  86820. }
  86821. };
  86822. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  86823. this._selectionContent.reset();
  86824. for (var index = 0; index < this.blocks.length; index++) {
  86825. var block = this.blocks[index];
  86826. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  86827. }
  86828. if (allowDuplicate) {
  86829. this._selectionContent.concat(this.dynamicContent);
  86830. }
  86831. else {
  86832. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  86833. }
  86834. return this._selectionContent;
  86835. };
  86836. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  86837. this._selectionContent.reset();
  86838. for (var index = 0; index < this.blocks.length; index++) {
  86839. var block = this.blocks[index];
  86840. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  86841. }
  86842. if (allowDuplicate) {
  86843. this._selectionContent.concat(this.dynamicContent);
  86844. }
  86845. else {
  86846. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  86847. }
  86848. return this._selectionContent;
  86849. };
  86850. Octree.prototype.intersectsRay = function (ray) {
  86851. this._selectionContent.reset();
  86852. for (var index = 0; index < this.blocks.length; index++) {
  86853. var block = this.blocks[index];
  86854. block.intersectsRay(ray, this._selectionContent);
  86855. }
  86856. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  86857. return this._selectionContent;
  86858. };
  86859. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  86860. target.blocks = new Array();
  86861. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  86862. // Segmenting space
  86863. for (var x = 0; x < 2; x++) {
  86864. for (var y = 0; y < 2; y++) {
  86865. for (var z = 0; z < 2; z++) {
  86866. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  86867. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  86868. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  86869. block.addEntries(entries);
  86870. target.blocks.push(block);
  86871. }
  86872. }
  86873. }
  86874. };
  86875. Octree.CreationFuncForMeshes = function (entry, block) {
  86876. var boundingInfo = entry.getBoundingInfo();
  86877. if (!entry.isBlocked && boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  86878. block.entries.push(entry);
  86879. }
  86880. };
  86881. Octree.CreationFuncForSubMeshes = function (entry, block) {
  86882. var boundingInfo = entry.getBoundingInfo();
  86883. if (boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  86884. block.entries.push(entry);
  86885. }
  86886. };
  86887. return Octree;
  86888. }());
  86889. BABYLON.Octree = Octree;
  86890. })(BABYLON || (BABYLON = {}));
  86891. //# sourceMappingURL=babylon.octree.js.map
  86892. var BABYLON;
  86893. (function (BABYLON) {
  86894. var OctreeBlock = /** @class */ (function () {
  86895. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  86896. this.entries = new Array();
  86897. this._boundingVectors = new Array();
  86898. this._capacity = capacity;
  86899. this._depth = depth;
  86900. this._maxDepth = maxDepth;
  86901. this._creationFunc = creationFunc;
  86902. this._minPoint = minPoint;
  86903. this._maxPoint = maxPoint;
  86904. this._boundingVectors.push(minPoint.clone());
  86905. this._boundingVectors.push(maxPoint.clone());
  86906. this._boundingVectors.push(minPoint.clone());
  86907. this._boundingVectors[2].x = maxPoint.x;
  86908. this._boundingVectors.push(minPoint.clone());
  86909. this._boundingVectors[3].y = maxPoint.y;
  86910. this._boundingVectors.push(minPoint.clone());
  86911. this._boundingVectors[4].z = maxPoint.z;
  86912. this._boundingVectors.push(maxPoint.clone());
  86913. this._boundingVectors[5].z = minPoint.z;
  86914. this._boundingVectors.push(maxPoint.clone());
  86915. this._boundingVectors[6].x = minPoint.x;
  86916. this._boundingVectors.push(maxPoint.clone());
  86917. this._boundingVectors[7].y = minPoint.y;
  86918. }
  86919. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  86920. // Property
  86921. get: function () {
  86922. return this._capacity;
  86923. },
  86924. enumerable: true,
  86925. configurable: true
  86926. });
  86927. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  86928. get: function () {
  86929. return this._minPoint;
  86930. },
  86931. enumerable: true,
  86932. configurable: true
  86933. });
  86934. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  86935. get: function () {
  86936. return this._maxPoint;
  86937. },
  86938. enumerable: true,
  86939. configurable: true
  86940. });
  86941. // Methods
  86942. OctreeBlock.prototype.addEntry = function (entry) {
  86943. if (this.blocks) {
  86944. for (var index = 0; index < this.blocks.length; index++) {
  86945. var block = this.blocks[index];
  86946. block.addEntry(entry);
  86947. }
  86948. return;
  86949. }
  86950. this._creationFunc(entry, this);
  86951. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  86952. this.createInnerBlocks();
  86953. }
  86954. };
  86955. OctreeBlock.prototype.addEntries = function (entries) {
  86956. for (var index = 0; index < entries.length; index++) {
  86957. var mesh = entries[index];
  86958. this.addEntry(mesh);
  86959. }
  86960. };
  86961. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  86962. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  86963. if (this.blocks) {
  86964. for (var index = 0; index < this.blocks.length; index++) {
  86965. var block = this.blocks[index];
  86966. block.select(frustumPlanes, selection, allowDuplicate);
  86967. }
  86968. return;
  86969. }
  86970. if (allowDuplicate) {
  86971. selection.concat(this.entries);
  86972. }
  86973. else {
  86974. selection.concatWithNoDuplicate(this.entries);
  86975. }
  86976. }
  86977. };
  86978. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  86979. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  86980. if (this.blocks) {
  86981. for (var index = 0; index < this.blocks.length; index++) {
  86982. var block = this.blocks[index];
  86983. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  86984. }
  86985. return;
  86986. }
  86987. if (allowDuplicate) {
  86988. selection.concat(this.entries);
  86989. }
  86990. else {
  86991. selection.concatWithNoDuplicate(this.entries);
  86992. }
  86993. }
  86994. };
  86995. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  86996. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  86997. if (this.blocks) {
  86998. for (var index = 0; index < this.blocks.length; index++) {
  86999. var block = this.blocks[index];
  87000. block.intersectsRay(ray, selection);
  87001. }
  87002. return;
  87003. }
  87004. selection.concatWithNoDuplicate(this.entries);
  87005. }
  87006. };
  87007. OctreeBlock.prototype.createInnerBlocks = function () {
  87008. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  87009. };
  87010. return OctreeBlock;
  87011. }());
  87012. BABYLON.OctreeBlock = OctreeBlock;
  87013. })(BABYLON || (BABYLON = {}));
  87014. //# sourceMappingURL=babylon.octreeBlock.js.map
  87015. var BABYLON;
  87016. (function (BABYLON) {
  87017. var VRDistortionCorrectionPostProcess = /** @class */ (function (_super) {
  87018. __extends(VRDistortionCorrectionPostProcess, _super);
  87019. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  87020. var _this = _super.call(this, name, "vrDistortionCorrection", [
  87021. 'LensCenter',
  87022. 'Scale',
  87023. 'ScaleIn',
  87024. 'HmdWarpParam'
  87025. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE) || this;
  87026. _this._isRightEye = isRightEye;
  87027. _this._distortionFactors = vrMetrics.distortionK;
  87028. _this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  87029. _this._lensCenterOffset = vrMetrics.lensCenterOffset;
  87030. _this.adaptScaleToCurrentViewport = true;
  87031. _this.onSizeChangedObservable.add(function () {
  87032. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  87033. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  87034. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  87035. });
  87036. _this.onApplyObservable.add(function (effect) {
  87037. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  87038. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  87039. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  87040. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  87041. });
  87042. return _this;
  87043. }
  87044. return VRDistortionCorrectionPostProcess;
  87045. }(BABYLON.PostProcess));
  87046. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  87047. })(BABYLON || (BABYLON = {}));
  87048. //# sourceMappingURL=babylon.vrDistortionCorrectionPostProcess.js.map
  87049. var BABYLON;
  87050. (function (BABYLON) {
  87051. /**
  87052. * Postprocess used to generate anaglyphic rendering
  87053. */
  87054. var AnaglyphPostProcess = /** @class */ (function (_super) {
  87055. __extends(AnaglyphPostProcess, _super);
  87056. /**
  87057. * Creates a new AnaglyphPostProcess
  87058. * @param name defines postprocess name
  87059. * @param options defines creation options or target ratio scale
  87060. * @param rigCameras defines cameras using this postprocess
  87061. * @param samplingMode defines required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)
  87062. * @param engine defines hosting engine
  87063. * @param reusable defines if the postprocess will be reused multiple times per frame
  87064. */
  87065. function AnaglyphPostProcess(name, options, rigCameras, samplingMode, engine, reusable) {
  87066. var _this = _super.call(this, name, "anaglyph", null, ["leftSampler"], options, rigCameras[1], samplingMode, engine, reusable) || this;
  87067. _this._passedProcess = rigCameras[0]._rigPostProcess;
  87068. _this.onApplyObservable.add(function (effect) {
  87069. effect.setTextureFromPostProcess("leftSampler", _this._passedProcess);
  87070. });
  87071. return _this;
  87072. }
  87073. return AnaglyphPostProcess;
  87074. }(BABYLON.PostProcess));
  87075. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  87076. })(BABYLON || (BABYLON = {}));
  87077. //# sourceMappingURL=babylon.anaglyphPostProcess.js.map
  87078. var BABYLON;
  87079. (function (BABYLON) {
  87080. var StereoscopicInterlacePostProcess = /** @class */ (function (_super) {
  87081. __extends(StereoscopicInterlacePostProcess, _super);
  87082. function StereoscopicInterlacePostProcess(name, rigCameras, isStereoscopicHoriz, samplingMode, engine, reusable) {
  87083. var _this = _super.call(this, name, "stereoscopicInterlace", ['stepSize'], ['camASampler'], 1, rigCameras[1], samplingMode, engine, reusable, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined) || this;
  87084. _this._passedProcess = rigCameras[0]._rigPostProcess;
  87085. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  87086. _this.onSizeChangedObservable.add(function () {
  87087. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  87088. });
  87089. _this.onApplyObservable.add(function (effect) {
  87090. effect.setTextureFromPostProcess("camASampler", _this._passedProcess);
  87091. effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
  87092. });
  87093. return _this;
  87094. }
  87095. return StereoscopicInterlacePostProcess;
  87096. }(BABYLON.PostProcess));
  87097. BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;
  87098. })(BABYLON || (BABYLON = {}));
  87099. //# sourceMappingURL=babylon.stereoscopicInterlacePostProcess.js.map
  87100. var BABYLON;
  87101. (function (BABYLON) {
  87102. /**
  87103. * Takes information about the orientation of the device as reported by the deviceorientation event to orient the camera.
  87104. * Screen rotation is taken into account.
  87105. */
  87106. var FreeCameraDeviceOrientationInput = /** @class */ (function () {
  87107. function FreeCameraDeviceOrientationInput() {
  87108. var _this = this;
  87109. this._screenOrientationAngle = 0;
  87110. this._screenQuaternion = new BABYLON.Quaternion();
  87111. this._alpha = 0;
  87112. this._beta = 0;
  87113. this._gamma = 0;
  87114. this._orientationChanged = function () {
  87115. _this._screenOrientationAngle = (window.orientation !== undefined ? +window.orientation : (window.screen.orientation && window.screen.orientation['angle'] ? window.screen.orientation.angle : 0));
  87116. _this._screenOrientationAngle = -BABYLON.Tools.ToRadians(_this._screenOrientationAngle / 2);
  87117. _this._screenQuaternion.copyFromFloats(0, Math.sin(_this._screenOrientationAngle), 0, Math.cos(_this._screenOrientationAngle));
  87118. };
  87119. this._deviceOrientation = function (evt) {
  87120. _this._alpha = evt.alpha !== null ? evt.alpha : 0;
  87121. _this._beta = evt.beta !== null ? evt.beta : 0;
  87122. _this._gamma = evt.gamma !== null ? evt.gamma : 0;
  87123. };
  87124. this._constantTranform = new BABYLON.Quaternion(-Math.sqrt(0.5), 0, 0, Math.sqrt(0.5));
  87125. this._orientationChanged();
  87126. }
  87127. Object.defineProperty(FreeCameraDeviceOrientationInput.prototype, "camera", {
  87128. get: function () {
  87129. return this._camera;
  87130. },
  87131. set: function (camera) {
  87132. this._camera = camera;
  87133. if (this._camera != null && !this._camera.rotationQuaternion) {
  87134. this._camera.rotationQuaternion = new BABYLON.Quaternion();
  87135. }
  87136. },
  87137. enumerable: true,
  87138. configurable: true
  87139. });
  87140. FreeCameraDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  87141. window.addEventListener("orientationchange", this._orientationChanged);
  87142. window.addEventListener("deviceorientation", this._deviceOrientation);
  87143. //In certain cases, the attach control is called AFTER orientation was changed,
  87144. //So this is needed.
  87145. this._orientationChanged();
  87146. };
  87147. FreeCameraDeviceOrientationInput.prototype.detachControl = function (element) {
  87148. window.removeEventListener("orientationchange", this._orientationChanged);
  87149. window.removeEventListener("deviceorientation", this._deviceOrientation);
  87150. };
  87151. FreeCameraDeviceOrientationInput.prototype.checkInputs = function () {
  87152. //if no device orientation provided, don't update the rotation.
  87153. //Only testing against alpha under the assumption thatnorientation will never be so exact when set.
  87154. if (!this._alpha)
  87155. return;
  87156. BABYLON.Quaternion.RotationYawPitchRollToRef(BABYLON.Tools.ToRadians(this._alpha), BABYLON.Tools.ToRadians(this._beta), -BABYLON.Tools.ToRadians(this._gamma), this.camera.rotationQuaternion);
  87157. this._camera.rotationQuaternion.multiplyInPlace(this._screenQuaternion);
  87158. this._camera.rotationQuaternion.multiplyInPlace(this._constantTranform);
  87159. //Mirror on XY Plane
  87160. this._camera.rotationQuaternion.z *= -1;
  87161. this._camera.rotationQuaternion.w *= -1;
  87162. };
  87163. FreeCameraDeviceOrientationInput.prototype.getClassName = function () {
  87164. return "FreeCameraDeviceOrientationInput";
  87165. };
  87166. FreeCameraDeviceOrientationInput.prototype.getSimpleName = function () {
  87167. return "deviceOrientation";
  87168. };
  87169. return FreeCameraDeviceOrientationInput;
  87170. }());
  87171. BABYLON.FreeCameraDeviceOrientationInput = FreeCameraDeviceOrientationInput;
  87172. BABYLON.CameraInputTypes["FreeCameraDeviceOrientationInput"] = FreeCameraDeviceOrientationInput;
  87173. })(BABYLON || (BABYLON = {}));
  87174. //# sourceMappingURL=babylon.freeCameraDeviceOrientationInput.js.map
  87175. var BABYLON;
  87176. (function (BABYLON) {
  87177. var ArcRotateCameraVRDeviceOrientationInput = /** @class */ (function () {
  87178. function ArcRotateCameraVRDeviceOrientationInput() {
  87179. this.alphaCorrection = 1;
  87180. this.betaCorrection = 1;
  87181. this.gammaCorrection = 1;
  87182. this._alpha = 0;
  87183. this._gamma = 0;
  87184. this._dirty = false;
  87185. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  87186. }
  87187. ArcRotateCameraVRDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  87188. this.camera.attachControl(element, noPreventDefault);
  87189. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  87190. };
  87191. ArcRotateCameraVRDeviceOrientationInput.prototype._onOrientationEvent = function (evt) {
  87192. if (evt.alpha !== null) {
  87193. this._alpha = +evt.alpha | 0;
  87194. }
  87195. if (evt.gamma !== null) {
  87196. this._gamma = +evt.gamma | 0;
  87197. }
  87198. this._dirty = true;
  87199. };
  87200. ArcRotateCameraVRDeviceOrientationInput.prototype.checkInputs = function () {
  87201. if (this._dirty) {
  87202. this._dirty = false;
  87203. if (this._gamma < 0) {
  87204. this._gamma = 180 + this._gamma;
  87205. }
  87206. this.camera.alpha = (-this._alpha / 180.0 * Math.PI) % Math.PI * 2;
  87207. this.camera.beta = (this._gamma / 180.0 * Math.PI);
  87208. }
  87209. };
  87210. ArcRotateCameraVRDeviceOrientationInput.prototype.detachControl = function (element) {
  87211. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  87212. };
  87213. ArcRotateCameraVRDeviceOrientationInput.prototype.getClassName = function () {
  87214. return "ArcRotateCameraVRDeviceOrientationInput";
  87215. };
  87216. ArcRotateCameraVRDeviceOrientationInput.prototype.getSimpleName = function () {
  87217. return "VRDeviceOrientation";
  87218. };
  87219. return ArcRotateCameraVRDeviceOrientationInput;
  87220. }());
  87221. BABYLON.ArcRotateCameraVRDeviceOrientationInput = ArcRotateCameraVRDeviceOrientationInput;
  87222. BABYLON.CameraInputTypes["ArcRotateCameraVRDeviceOrientationInput"] = ArcRotateCameraVRDeviceOrientationInput;
  87223. })(BABYLON || (BABYLON = {}));
  87224. //# sourceMappingURL=babylon.arcRotateCameraVRDeviceOrientationInput.js.map
  87225. var BABYLON;
  87226. (function (BABYLON) {
  87227. var VRCameraMetrics = /** @class */ (function () {
  87228. function VRCameraMetrics() {
  87229. this.compensateDistortion = true;
  87230. }
  87231. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
  87232. get: function () {
  87233. return this.hResolution / (2 * this.vResolution);
  87234. },
  87235. enumerable: true,
  87236. configurable: true
  87237. });
  87238. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
  87239. get: function () {
  87240. return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
  87241. },
  87242. enumerable: true,
  87243. configurable: true
  87244. });
  87245. Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
  87246. get: function () {
  87247. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  87248. var h = (4 * meters) / this.hScreenSize;
  87249. return BABYLON.Matrix.Translation(h, 0, 0);
  87250. },
  87251. enumerable: true,
  87252. configurable: true
  87253. });
  87254. Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
  87255. get: function () {
  87256. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  87257. var h = (4 * meters) / this.hScreenSize;
  87258. return BABYLON.Matrix.Translation(-h, 0, 0);
  87259. },
  87260. enumerable: true,
  87261. configurable: true
  87262. });
  87263. Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
  87264. get: function () {
  87265. return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
  87266. },
  87267. enumerable: true,
  87268. configurable: true
  87269. });
  87270. Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
  87271. get: function () {
  87272. return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
  87273. },
  87274. enumerable: true,
  87275. configurable: true
  87276. });
  87277. VRCameraMetrics.GetDefault = function () {
  87278. var result = new VRCameraMetrics();
  87279. result.hResolution = 1280;
  87280. result.vResolution = 800;
  87281. result.hScreenSize = 0.149759993;
  87282. result.vScreenSize = 0.0935999975;
  87283. result.vScreenCenter = 0.0467999987;
  87284. result.eyeToScreenDistance = 0.0410000011;
  87285. result.lensSeparationDistance = 0.0635000020;
  87286. result.interpupillaryDistance = 0.0640000030;
  87287. result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
  87288. result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
  87289. result.postProcessScaleFactor = 1.714605507808412;
  87290. result.lensCenterOffset = 0.151976421;
  87291. return result;
  87292. };
  87293. return VRCameraMetrics;
  87294. }());
  87295. BABYLON.VRCameraMetrics = VRCameraMetrics;
  87296. })(BABYLON || (BABYLON = {}));
  87297. //# sourceMappingURL=babylon.vrCameraMetrics.js.map
  87298. var BABYLON;
  87299. (function (BABYLON) {
  87300. /**
  87301. * This represents a WebVR camera.
  87302. * The WebVR camera is Babylon's simple interface to interaction with Windows Mixed Reality, HTC Vive and Oculus Rift.
  87303. * @example http://doc.babylonjs.com/how_to/webvr_camera
  87304. */
  87305. var WebVRFreeCamera = /** @class */ (function (_super) {
  87306. __extends(WebVRFreeCamera, _super);
  87307. /**
  87308. * Instantiates a WebVRFreeCamera.
  87309. * @param name The name of the WebVRFreeCamera
  87310. * @param position The starting anchor position for the camera
  87311. * @param scene The scene the camera belongs to
  87312. * @param webVROptions a set of customizable options for the webVRCamera
  87313. */
  87314. function WebVRFreeCamera(name, position, scene, webVROptions) {
  87315. if (webVROptions === void 0) { webVROptions = {}; }
  87316. var _this = _super.call(this, name, position, scene) || this;
  87317. _this.webVROptions = webVROptions;
  87318. /**
  87319. * The vrDisplay tied to the camera. See https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay
  87320. */
  87321. _this._vrDevice = null;
  87322. /**
  87323. * The rawPose of the vrDevice.
  87324. */
  87325. _this.rawPose = null;
  87326. _this._specsVersion = "1.1";
  87327. _this._attached = false;
  87328. _this._descendants = [];
  87329. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  87330. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  87331. _this._deviceRoomRotationQuaternion = BABYLON.Quaternion.Identity();
  87332. _this._standingMatrix = null;
  87333. /**
  87334. * Represents device position in babylon space.
  87335. */
  87336. _this.devicePosition = BABYLON.Vector3.Zero();
  87337. /**
  87338. * Represents device rotation in babylon space.
  87339. */
  87340. _this.deviceRotationQuaternion = BABYLON.Quaternion.Identity();
  87341. /**
  87342. * The scale of the device to be used when translating from device space to babylon space.
  87343. */
  87344. _this.deviceScaleFactor = 1;
  87345. _this._deviceToWorld = BABYLON.Matrix.Identity();
  87346. _this._worldToDevice = BABYLON.Matrix.Identity();
  87347. /**
  87348. * References to the webVR controllers for the vrDevice.
  87349. */
  87350. _this.controllers = [];
  87351. /**
  87352. * Emits an event when a controller is attached.
  87353. */
  87354. _this.onControllersAttachedObservable = new BABYLON.Observable();
  87355. /**
  87356. * Emits an event when a controller's mesh has been loaded;
  87357. */
  87358. _this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  87359. /**
  87360. * If the rig cameras be used as parent instead of this camera.
  87361. */
  87362. _this.rigParenting = true;
  87363. _this._defaultHeight = undefined;
  87364. _this._workingVector = BABYLON.Vector3.Zero();
  87365. _this._oneVector = BABYLON.Vector3.One();
  87366. _this._workingMatrix = BABYLON.Matrix.Identity();
  87367. _this._cache.position = BABYLON.Vector3.Zero();
  87368. if (webVROptions.defaultHeight) {
  87369. _this._defaultHeight = webVROptions.defaultHeight;
  87370. _this.position.y = _this._defaultHeight;
  87371. }
  87372. _this.minZ = 0.1;
  87373. //legacy support - the compensation boolean was removed.
  87374. if (arguments.length === 5) {
  87375. _this.webVROptions = arguments[4];
  87376. }
  87377. // default webVR options
  87378. if (_this.webVROptions.trackPosition == undefined) {
  87379. _this.webVROptions.trackPosition = true;
  87380. }
  87381. if (_this.webVROptions.controllerMeshes == undefined) {
  87382. _this.webVROptions.controllerMeshes = true;
  87383. }
  87384. if (_this.webVROptions.defaultLightingOnControllers == undefined) {
  87385. _this.webVROptions.defaultLightingOnControllers = true;
  87386. }
  87387. _this.rotationQuaternion = new BABYLON.Quaternion();
  87388. if (_this.webVROptions && _this.webVROptions.positionScale) {
  87389. _this.deviceScaleFactor = _this.webVROptions.positionScale;
  87390. }
  87391. //enable VR
  87392. var engine = _this.getEngine();
  87393. _this._onVREnabled = function (success) { if (success) {
  87394. _this.initControllers();
  87395. } };
  87396. engine.onVRRequestPresentComplete.add(_this._onVREnabled);
  87397. engine.initWebVR().add(function (event) {
  87398. if (!event.vrDisplay || _this._vrDevice === event.vrDisplay) {
  87399. return;
  87400. }
  87401. _this._vrDevice = event.vrDisplay;
  87402. //reset the rig parameters.
  87403. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_WEBVR, { parentCamera: _this, vrDisplay: _this._vrDevice, frameData: _this._frameData, specs: _this._specsVersion });
  87404. if (_this._attached) {
  87405. _this.getEngine().enableVR();
  87406. }
  87407. });
  87408. if (typeof (VRFrameData) !== "undefined")
  87409. _this._frameData = new VRFrameData();
  87410. /**
  87411. * The idea behind the following lines:
  87412. * objects that have the camera as parent should actually have the rig cameras as a parent.
  87413. * BUT, each of those cameras has a different view matrix, which means that if we set the parent to the first rig camera,
  87414. * the second will not show it correctly.
  87415. *
  87416. * To solve this - each object that has the camera as parent will be added to a protected array.
  87417. * When the rig camera renders, it will take this array and set all of those to be its children.
  87418. * This way, the right camera will be used as a parent, and the mesh will be rendered correctly.
  87419. * Amazing!
  87420. */
  87421. scene.onBeforeCameraRenderObservable.add(function (camera) {
  87422. if (camera.parent === _this && _this.rigParenting) {
  87423. _this._descendants = _this.getDescendants(true, function (n) {
  87424. // don't take the cameras or the controllers!
  87425. var isController = _this.controllers.some(function (controller) { return controller._mesh === n; });
  87426. var isRigCamera = _this._rigCameras.indexOf(n) !== -1;
  87427. return !isController && !isRigCamera;
  87428. });
  87429. _this._descendants.forEach(function (node) {
  87430. node.parent = camera;
  87431. });
  87432. }
  87433. });
  87434. scene.onAfterCameraRenderObservable.add(function (camera) {
  87435. if (camera.parent === _this && _this.rigParenting) {
  87436. _this._descendants.forEach(function (node) {
  87437. node.parent = _this;
  87438. });
  87439. }
  87440. });
  87441. return _this;
  87442. }
  87443. /**
  87444. * Gets the device distance from the ground in meters.
  87445. * @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.
  87446. */
  87447. WebVRFreeCamera.prototype.deviceDistanceToRoomGround = function () {
  87448. if (this._standingMatrix) {
  87449. // Add standing matrix offset to get real offset from ground in room
  87450. this._standingMatrix.getTranslationToRef(this._workingVector);
  87451. return this._deviceRoomPosition.y + this._workingVector.y;
  87452. }
  87453. //If VRDisplay does not inform stage parameters and no default height is set we fallback to zero.
  87454. return this._defaultHeight || 0;
  87455. };
  87456. /**
  87457. * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.
  87458. * @param callback will be called when the standing matrix is set. Callback parameter is if the standing matrix is supported.
  87459. */
  87460. WebVRFreeCamera.prototype.useStandingMatrix = function (callback) {
  87461. var _this = this;
  87462. if (callback === void 0) { callback = function (bool) { }; }
  87463. // Use standing matrix if available
  87464. this.getEngine().initWebVRAsync().then(function (result) {
  87465. if (!result.vrDisplay || !result.vrDisplay.stageParameters || !result.vrDisplay.stageParameters.sittingToStandingTransform) {
  87466. callback(false);
  87467. }
  87468. else {
  87469. _this._standingMatrix = new BABYLON.Matrix();
  87470. BABYLON.Matrix.FromFloat32ArrayToRefScaled(result.vrDisplay.stageParameters.sittingToStandingTransform, 0, 1, _this._standingMatrix);
  87471. if (!_this.getScene().useRightHandedSystem) {
  87472. [2, 6, 8, 9, 14].forEach(function (num) {
  87473. if (_this._standingMatrix) {
  87474. _this._standingMatrix.m[num] *= -1;
  87475. }
  87476. });
  87477. }
  87478. callback(true);
  87479. }
  87480. });
  87481. };
  87482. /**
  87483. * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.
  87484. * @returns A promise with a boolean set to if the standing matrix is supported.
  87485. */
  87486. WebVRFreeCamera.prototype.useStandingMatrixAsync = function () {
  87487. var _this = this;
  87488. return new Promise(function (res, rej) {
  87489. _this.useStandingMatrix(function (supported) {
  87490. res(supported);
  87491. });
  87492. });
  87493. };
  87494. /**
  87495. * Disposes the camera
  87496. */
  87497. WebVRFreeCamera.prototype.dispose = function () {
  87498. this.getEngine().onVRRequestPresentComplete.removeCallback(this._onVREnabled);
  87499. _super.prototype.dispose.call(this);
  87500. };
  87501. /**
  87502. * Gets a vrController by name.
  87503. * @param name The name of the controller to retreive
  87504. * @returns the controller matching the name specified or null if not found
  87505. */
  87506. WebVRFreeCamera.prototype.getControllerByName = function (name) {
  87507. for (var _i = 0, _a = this.controllers; _i < _a.length; _i++) {
  87508. var gp = _a[_i];
  87509. if (gp.hand === name) {
  87510. return gp;
  87511. }
  87512. }
  87513. return null;
  87514. };
  87515. Object.defineProperty(WebVRFreeCamera.prototype, "leftController", {
  87516. /**
  87517. * The controller corrisponding to the users left hand.
  87518. */
  87519. get: function () {
  87520. if (!this._leftController) {
  87521. this._leftController = this.getControllerByName("left");
  87522. }
  87523. return this._leftController;
  87524. },
  87525. enumerable: true,
  87526. configurable: true
  87527. });
  87528. ;
  87529. Object.defineProperty(WebVRFreeCamera.prototype, "rightController", {
  87530. /**
  87531. * The controller corrisponding to the users right hand.
  87532. */
  87533. get: function () {
  87534. if (!this._rightController) {
  87535. this._rightController = this.getControllerByName("right");
  87536. }
  87537. return this._rightController;
  87538. },
  87539. enumerable: true,
  87540. configurable: true
  87541. });
  87542. ;
  87543. /**
  87544. * Casts a ray forward from the vrCamera's gaze.
  87545. * @param length Length of the ray (default: 100)
  87546. * @returns the ray corrisponding to the gaze
  87547. */
  87548. WebVRFreeCamera.prototype.getForwardRay = function (length) {
  87549. if (length === void 0) { length = 100; }
  87550. if (this.leftCamera) {
  87551. // Use left eye to avoid computation to compute center on every call
  87552. return _super.prototype.getForwardRay.call(this, length, this.leftCamera.getWorldMatrix(), this.leftCamera.globalPosition); // Need the actual rendered camera
  87553. }
  87554. else {
  87555. return _super.prototype.getForwardRay.call(this, length);
  87556. }
  87557. };
  87558. /**
  87559. * Updates the camera based on device's frame data
  87560. */
  87561. WebVRFreeCamera.prototype._checkInputs = function () {
  87562. if (this._vrDevice && this._vrDevice.isPresenting) {
  87563. this._vrDevice.getFrameData(this._frameData);
  87564. this.updateFromDevice(this._frameData.pose);
  87565. }
  87566. _super.prototype._checkInputs.call(this);
  87567. };
  87568. /**
  87569. * Updates the poseControlled values based on the input device pose.
  87570. * @param poseData Pose coming from the device
  87571. */
  87572. WebVRFreeCamera.prototype.updateFromDevice = function (poseData) {
  87573. if (poseData && poseData.orientation) {
  87574. this.rawPose = poseData;
  87575. this._deviceRoomRotationQuaternion.copyFromFloats(poseData.orientation[0], poseData.orientation[1], -poseData.orientation[2], -poseData.orientation[3]);
  87576. if (this.getScene().useRightHandedSystem) {
  87577. this._deviceRoomRotationQuaternion.z *= -1;
  87578. this._deviceRoomRotationQuaternion.w *= -1;
  87579. }
  87580. if (this.webVROptions.trackPosition && this.rawPose.position) {
  87581. this._deviceRoomPosition.copyFromFloats(this.rawPose.position[0], this.rawPose.position[1], -this.rawPose.position[2]);
  87582. if (this.getScene().useRightHandedSystem) {
  87583. this._deviceRoomPosition.z *= -1;
  87584. }
  87585. }
  87586. }
  87587. };
  87588. /**
  87589. * WebVR's attach control will start broadcasting frames to the device.
  87590. * Note that in certain browsers (chrome for example) this function must be called
  87591. * within a user-interaction callback. Example:
  87592. * <pre> scene.onPointerDown = function() { camera.attachControl(canvas); }</pre>
  87593. *
  87594. * @param element html element to attach the vrDevice to
  87595. * @param noPreventDefault prevent the default html element operation when attaching the vrDevice
  87596. */
  87597. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  87598. _super.prototype.attachControl.call(this, element, noPreventDefault);
  87599. this._attached = true;
  87600. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  87601. if (this._vrDevice) {
  87602. this.getEngine().enableVR();
  87603. }
  87604. };
  87605. /**
  87606. * Detaches the camera from the html element and disables VR
  87607. *
  87608. * @param element html element to detach from
  87609. */
  87610. WebVRFreeCamera.prototype.detachControl = function (element) {
  87611. this.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  87612. this.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  87613. _super.prototype.detachControl.call(this, element);
  87614. this._attached = false;
  87615. this.getEngine().disableVR();
  87616. };
  87617. /**
  87618. * @returns the name of this class
  87619. */
  87620. WebVRFreeCamera.prototype.getClassName = function () {
  87621. return "WebVRFreeCamera";
  87622. };
  87623. /**
  87624. * Calls resetPose on the vrDisplay
  87625. * See: https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay/resetPose
  87626. */
  87627. WebVRFreeCamera.prototype.resetToCurrentRotation = function () {
  87628. //uses the vrDisplay's "resetPose()".
  87629. //pitch and roll won't be affected.
  87630. this._vrDevice.resetPose();
  87631. };
  87632. /**
  87633. * Updates the rig cameras (left and right eye)
  87634. */
  87635. WebVRFreeCamera.prototype._updateRigCameras = function () {
  87636. var camLeft = this._rigCameras[0];
  87637. var camRight = this._rigCameras[1];
  87638. camLeft.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  87639. camRight.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  87640. camLeft.position.copyFrom(this._deviceRoomPosition);
  87641. camRight.position.copyFrom(this._deviceRoomPosition);
  87642. };
  87643. /**
  87644. * Updates the cached values of the camera
  87645. * @param ignoreParentClass ignores updating the parent class's cache (default: false)
  87646. */
  87647. WebVRFreeCamera.prototype._updateCache = function (ignoreParentClass) {
  87648. var _this = this;
  87649. if (!this.rotationQuaternion.equals(this._cache.rotationQuaternion) || !this.position.equals(this._cache.position)) {
  87650. // Update to ensure devicePosition is up to date with most recent _deviceRoomPosition
  87651. if (!this.updateCacheCalled) {
  87652. // make sure it is only called once per loop. this.update() might cause an infinite loop.
  87653. this.updateCacheCalled = true;
  87654. this.update();
  87655. }
  87656. // Set working vector to the device position in room space rotated by the new rotation
  87657. this.rotationQuaternion.toRotationMatrix(this._workingMatrix);
  87658. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._workingMatrix, this._workingVector);
  87659. // Subtract this vector from the current device position in world to get the translation for the device world matrix
  87660. this.devicePosition.subtractToRef(this._workingVector, this._workingVector);
  87661. BABYLON.Matrix.ComposeToRef(this._oneVector, this.rotationQuaternion, this._workingVector, this._deviceToWorld);
  87662. // Add translation from anchor position
  87663. this._deviceToWorld.getTranslationToRef(this._workingVector);
  87664. this._workingVector.addInPlace(this.position);
  87665. this._workingVector.subtractInPlace(this._cache.position);
  87666. this._deviceToWorld.setTranslation(this._workingVector);
  87667. // Set an inverted matrix to be used when updating the camera
  87668. this._deviceToWorld.invertToRef(this._worldToDevice);
  87669. // Update the gamepad to ensure the mesh is updated on the same frame as camera
  87670. this.controllers.forEach(function (controller) {
  87671. controller._deviceToWorld.copyFrom(_this._deviceToWorld);
  87672. controller.update();
  87673. });
  87674. }
  87675. if (!ignoreParentClass) {
  87676. _super.prototype._updateCache.call(this);
  87677. }
  87678. this.updateCacheCalled = false;
  87679. };
  87680. /**
  87681. * Updates the current device position and rotation in the babylon world
  87682. */
  87683. WebVRFreeCamera.prototype.update = function () {
  87684. // Get current device position in babylon world
  87685. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._deviceToWorld, this.devicePosition);
  87686. // Get current device rotation in babylon world
  87687. BABYLON.Matrix.FromQuaternionToRef(this._deviceRoomRotationQuaternion, this._workingMatrix);
  87688. this._workingMatrix.multiplyToRef(this._deviceToWorld, this._workingMatrix);
  87689. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  87690. _super.prototype.update.call(this);
  87691. };
  87692. /**
  87693. * Gets the view matrix of this camera (Always set to identity as left and right eye cameras contain the actual view matrix)
  87694. * @returns an identity matrix
  87695. */
  87696. WebVRFreeCamera.prototype._getViewMatrix = function () {
  87697. return BABYLON.Matrix.Identity();
  87698. };
  87699. /**
  87700. * This function is called by the two RIG cameras.
  87701. * 'this' is the left or right camera (and NOT (!!!) the WebVRFreeCamera instance)
  87702. */
  87703. WebVRFreeCamera.prototype._getWebVRViewMatrix = function () {
  87704. var _this = this;
  87705. // Update the parent camera prior to using a child camera to avoid desynchronization
  87706. var parentCamera = this._cameraRigParams["parentCamera"];
  87707. parentCamera._updateCache();
  87708. //WebVR 1.1
  87709. var viewArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftViewMatrix : this._cameraRigParams["frameData"].rightViewMatrix;
  87710. BABYLON.Matrix.FromArrayToRef(viewArray, 0, this._webvrViewMatrix);
  87711. if (!this.getScene().useRightHandedSystem) {
  87712. [2, 6, 8, 9, 14].forEach(function (num) {
  87713. _this._webvrViewMatrix.m[num] *= -1;
  87714. });
  87715. }
  87716. // update the camera rotation matrix
  87717. this._webvrViewMatrix.getRotationMatrixToRef(this._cameraRotationMatrix);
  87718. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  87719. // Computing target and final matrix
  87720. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  87721. // should the view matrix be updated with scale and position offset?
  87722. if (parentCamera.deviceScaleFactor !== 1) {
  87723. this._webvrViewMatrix.invert();
  87724. // scale the position, if set
  87725. if (parentCamera.deviceScaleFactor) {
  87726. this._webvrViewMatrix.m[12] *= parentCamera.deviceScaleFactor;
  87727. this._webvrViewMatrix.m[13] *= parentCamera.deviceScaleFactor;
  87728. this._webvrViewMatrix.m[14] *= parentCamera.deviceScaleFactor;
  87729. }
  87730. this._webvrViewMatrix.invert();
  87731. }
  87732. parentCamera._worldToDevice.multiplyToRef(this._webvrViewMatrix, this._webvrViewMatrix);
  87733. // Compute global position
  87734. this._workingMatrix = this._workingMatrix || BABYLON.Matrix.Identity();
  87735. this._webvrViewMatrix.invertToRef(this._workingMatrix);
  87736. this._workingMatrix.multiplyToRef(parentCamera.getWorldMatrix(), this._workingMatrix);
  87737. this._workingMatrix.getTranslationToRef(this._globalPosition);
  87738. this._markSyncedWithParent();
  87739. return this._webvrViewMatrix;
  87740. };
  87741. WebVRFreeCamera.prototype._getWebVRProjectionMatrix = function () {
  87742. var _this = this;
  87743. var parentCamera = this.parent;
  87744. parentCamera._vrDevice.depthNear = parentCamera.minZ;
  87745. parentCamera._vrDevice.depthFar = parentCamera.maxZ;
  87746. var projectionArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftProjectionMatrix : this._cameraRigParams["frameData"].rightProjectionMatrix;
  87747. BABYLON.Matrix.FromArrayToRef(projectionArray, 0, this._projectionMatrix);
  87748. //babylon compatible matrix
  87749. if (!this.getScene().useRightHandedSystem) {
  87750. [8, 9, 10, 11].forEach(function (num) {
  87751. _this._projectionMatrix.m[num] *= -1;
  87752. });
  87753. }
  87754. return this._projectionMatrix;
  87755. };
  87756. /**
  87757. * Initializes the controllers and their meshes
  87758. */
  87759. WebVRFreeCamera.prototype.initControllers = function () {
  87760. var _this = this;
  87761. this.controllers = [];
  87762. var manager = this.getScene().gamepadManager;
  87763. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  87764. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  87765. var webVrController = gamepad;
  87766. if (webVrController.defaultModel) {
  87767. webVrController.defaultModel.setEnabled(false);
  87768. }
  87769. if (webVrController.hand === "right") {
  87770. _this._rightController = null;
  87771. }
  87772. if (webVrController.hand === "left") {
  87773. _this._leftController = null;
  87774. }
  87775. var controllerIndex = _this.controllers.indexOf(webVrController);
  87776. if (controllerIndex !== -1) {
  87777. _this.controllers.splice(controllerIndex, 1);
  87778. }
  87779. }
  87780. });
  87781. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  87782. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  87783. var webVrController_1 = gamepad;
  87784. webVrController_1.deviceScaleFactor = _this.deviceScaleFactor;
  87785. webVrController_1._deviceToWorld.copyFrom(_this._deviceToWorld);
  87786. if (_this.webVROptions.controllerMeshes) {
  87787. if (webVrController_1.defaultModel) {
  87788. webVrController_1.defaultModel.setEnabled(true);
  87789. }
  87790. else {
  87791. // Load the meshes
  87792. webVrController_1.initControllerMesh(_this.getScene(), function (loadedMesh) {
  87793. loadedMesh.scaling.scaleInPlace(_this.deviceScaleFactor);
  87794. _this.onControllerMeshLoadedObservable.notifyObservers(webVrController_1);
  87795. if (_this.webVROptions.defaultLightingOnControllers) {
  87796. if (!_this._lightOnControllers) {
  87797. _this._lightOnControllers = new BABYLON.HemisphericLight("vrControllersLight", new BABYLON.Vector3(0, 1, 0), _this.getScene());
  87798. }
  87799. var activateLightOnSubMeshes_1 = function (mesh, light) {
  87800. var children = mesh.getChildren();
  87801. if (children.length !== 0) {
  87802. children.forEach(function (mesh) {
  87803. light.includedOnlyMeshes.push(mesh);
  87804. activateLightOnSubMeshes_1(mesh, light);
  87805. });
  87806. }
  87807. };
  87808. _this._lightOnControllers.includedOnlyMeshes.push(loadedMesh);
  87809. activateLightOnSubMeshes_1(loadedMesh, _this._lightOnControllers);
  87810. }
  87811. });
  87812. }
  87813. }
  87814. webVrController_1.attachToPoseControlledCamera(_this);
  87815. // since this is async - sanity check. Is the controller already stored?
  87816. if (_this.controllers.indexOf(webVrController_1) === -1) {
  87817. //add to the controllers array
  87818. _this.controllers.push(webVrController_1);
  87819. // Forced to add some control code for Vive as it doesn't always fill properly the "hand" property
  87820. // Sometimes, both controllers are set correctly (left and right), sometimes none, sometimes only one of them...
  87821. // So we're overriding setting left & right manually to be sure
  87822. var firstViveWandDetected = false;
  87823. for (var i = 0; i < _this.controllers.length; i++) {
  87824. if (_this.controllers[i].controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  87825. if (!firstViveWandDetected) {
  87826. firstViveWandDetected = true;
  87827. _this.controllers[i].hand = "left";
  87828. }
  87829. else {
  87830. _this.controllers[i].hand = "right";
  87831. }
  87832. }
  87833. }
  87834. //did we find enough controllers? Great! let the developer know.
  87835. if (_this.controllers.length >= 2) {
  87836. _this.onControllersAttachedObservable.notifyObservers(_this.controllers);
  87837. }
  87838. }
  87839. }
  87840. });
  87841. };
  87842. return WebVRFreeCamera;
  87843. }(BABYLON.FreeCamera));
  87844. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  87845. })(BABYLON || (BABYLON = {}));
  87846. //# sourceMappingURL=babylon.webVRCamera.js.map
  87847. var BABYLON;
  87848. (function (BABYLON) {
  87849. // We're mainly based on the logic defined into the FreeCamera code
  87850. /**
  87851. * This is a camera specifically designed to react to device orientation events such as a modern mobile device
  87852. * being tilted forward or back and left or right.
  87853. */
  87854. var DeviceOrientationCamera = /** @class */ (function (_super) {
  87855. __extends(DeviceOrientationCamera, _super);
  87856. /**
  87857. * Creates a new device orientation camera
  87858. * @param name The name of the camera
  87859. * @param position The start position camera
  87860. * @param scene The scene the camera belongs to
  87861. */
  87862. function DeviceOrientationCamera(name, position, scene) {
  87863. var _this = _super.call(this, name, position, scene) || this;
  87864. _this._quaternionCache = new BABYLON.Quaternion();
  87865. _this.inputs.addDeviceOrientation();
  87866. return _this;
  87867. }
  87868. /**
  87869. * Gets the current instance class name ("DeviceOrientationCamera").
  87870. * This helps avoiding instanceof at run time.
  87871. * @returns the class name
  87872. */
  87873. DeviceOrientationCamera.prototype.getClassName = function () {
  87874. return "DeviceOrientationCamera";
  87875. };
  87876. /**
  87877. * Checks and applies the current values of the inputs to the camera. (Internal use only)
  87878. */
  87879. DeviceOrientationCamera.prototype._checkInputs = function () {
  87880. _super.prototype._checkInputs.call(this);
  87881. this._quaternionCache.copyFrom(this.rotationQuaternion);
  87882. if (this._initialQuaternion) {
  87883. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  87884. }
  87885. };
  87886. /**
  87887. * Reset the camera to its default orientation on the specified axis only.
  87888. * @param axis The axis to reset
  87889. */
  87890. DeviceOrientationCamera.prototype.resetToCurrentRotation = function (axis) {
  87891. var _this = this;
  87892. if (axis === void 0) { axis = BABYLON.Axis.Y; }
  87893. //can only work if this camera has a rotation quaternion already.
  87894. if (!this.rotationQuaternion)
  87895. return;
  87896. if (!this._initialQuaternion) {
  87897. this._initialQuaternion = new BABYLON.Quaternion();
  87898. }
  87899. this._initialQuaternion.copyFrom(this._quaternionCache || this.rotationQuaternion);
  87900. ['x', 'y', 'z'].forEach(function (axisName) {
  87901. if (!axis[axisName]) {
  87902. _this._initialQuaternion[axisName] = 0;
  87903. }
  87904. else {
  87905. _this._initialQuaternion[axisName] *= -1;
  87906. }
  87907. });
  87908. this._initialQuaternion.normalize();
  87909. //force rotation update
  87910. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  87911. };
  87912. return DeviceOrientationCamera;
  87913. }(BABYLON.FreeCamera));
  87914. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  87915. })(BABYLON || (BABYLON = {}));
  87916. //# sourceMappingURL=babylon.deviceOrientationCamera.js.map
  87917. var BABYLON;
  87918. (function (BABYLON) {
  87919. var VRDeviceOrientationFreeCamera = /** @class */ (function (_super) {
  87920. __extends(VRDeviceOrientationFreeCamera, _super);
  87921. function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  87922. if (compensateDistortion === void 0) { compensateDistortion = true; }
  87923. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  87924. var _this = _super.call(this, name, position, scene) || this;
  87925. vrCameraMetrics.compensateDistortion = compensateDistortion;
  87926. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  87927. return _this;
  87928. }
  87929. VRDeviceOrientationFreeCamera.prototype.getClassName = function () {
  87930. return "VRDeviceOrientationFreeCamera";
  87931. };
  87932. return VRDeviceOrientationFreeCamera;
  87933. }(BABYLON.DeviceOrientationCamera));
  87934. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  87935. var VRDeviceOrientationGamepadCamera = /** @class */ (function (_super) {
  87936. __extends(VRDeviceOrientationGamepadCamera, _super);
  87937. function VRDeviceOrientationGamepadCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  87938. if (compensateDistortion === void 0) { compensateDistortion = true; }
  87939. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  87940. var _this = _super.call(this, name, position, scene, compensateDistortion, vrCameraMetrics) || this;
  87941. _this.inputs.addGamepad();
  87942. return _this;
  87943. }
  87944. VRDeviceOrientationGamepadCamera.prototype.getClassName = function () {
  87945. return "VRDeviceOrientationGamepadCamera";
  87946. };
  87947. return VRDeviceOrientationGamepadCamera;
  87948. }(VRDeviceOrientationFreeCamera));
  87949. BABYLON.VRDeviceOrientationGamepadCamera = VRDeviceOrientationGamepadCamera;
  87950. var VRDeviceOrientationArcRotateCamera = /** @class */ (function (_super) {
  87951. __extends(VRDeviceOrientationArcRotateCamera, _super);
  87952. function VRDeviceOrientationArcRotateCamera(name, alpha, beta, radius, target, scene, compensateDistortion, vrCameraMetrics) {
  87953. if (compensateDistortion === void 0) { compensateDistortion = true; }
  87954. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  87955. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  87956. vrCameraMetrics.compensateDistortion = compensateDistortion;
  87957. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  87958. _this.inputs.addVRDeviceOrientation();
  87959. return _this;
  87960. }
  87961. VRDeviceOrientationArcRotateCamera.prototype.getClassName = function () {
  87962. return "VRDeviceOrientationArcRotateCamera";
  87963. };
  87964. return VRDeviceOrientationArcRotateCamera;
  87965. }(BABYLON.ArcRotateCamera));
  87966. BABYLON.VRDeviceOrientationArcRotateCamera = VRDeviceOrientationArcRotateCamera;
  87967. })(BABYLON || (BABYLON = {}));
  87968. //# sourceMappingURL=babylon.vrDeviceOrientationCamera.js.map
  87969. var BABYLON;
  87970. (function (BABYLON) {
  87971. /**
  87972. * Camera used to simulate anaglyphic rendering (based on FreeCamera)
  87973. */
  87974. var AnaglyphFreeCamera = /** @class */ (function (_super) {
  87975. __extends(AnaglyphFreeCamera, _super);
  87976. /**
  87977. * Creates a new AnaglyphFreeCamera
  87978. * @param name defines camera name
  87979. * @param position defines initial position
  87980. * @param interaxialDistance defines distance between each color axis
  87981. * @param scene defines the hosting scene
  87982. */
  87983. function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
  87984. var _this = _super.call(this, name, position, scene) || this;
  87985. _this.interaxialDistance = interaxialDistance;
  87986. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  87987. return _this;
  87988. }
  87989. /**
  87990. * Gets camera class name
  87991. * @returns AnaglyphFreeCamera
  87992. */
  87993. AnaglyphFreeCamera.prototype.getClassName = function () {
  87994. return "AnaglyphFreeCamera";
  87995. };
  87996. return AnaglyphFreeCamera;
  87997. }(BABYLON.FreeCamera));
  87998. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  87999. /**
  88000. * Camera used to simulate anaglyphic rendering (based on ArcRotateCamera)
  88001. */
  88002. var AnaglyphArcRotateCamera = /** @class */ (function (_super) {
  88003. __extends(AnaglyphArcRotateCamera, _super);
  88004. /**
  88005. * Creates a new AnaglyphArcRotateCamera
  88006. * @param name defines camera name
  88007. * @param alpha defines alpha angle (in radians)
  88008. * @param beta defines beta angle (in radians)
  88009. * @param radius defines radius
  88010. * @param target defines camera target
  88011. * @param interaxialDistance defines distance between each color axis
  88012. * @param scene defines the hosting scene
  88013. */
  88014. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
  88015. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  88016. _this.interaxialDistance = interaxialDistance;
  88017. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  88018. return _this;
  88019. }
  88020. /**
  88021. * Gets camera class name
  88022. * @returns AnaglyphArcRotateCamera
  88023. */
  88024. AnaglyphArcRotateCamera.prototype.getClassName = function () {
  88025. return "AnaglyphArcRotateCamera";
  88026. };
  88027. return AnaglyphArcRotateCamera;
  88028. }(BABYLON.ArcRotateCamera));
  88029. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  88030. /**
  88031. * Camera used to simulate anaglyphic rendering (based on GamepadCamera)
  88032. */
  88033. var AnaglyphGamepadCamera = /** @class */ (function (_super) {
  88034. __extends(AnaglyphGamepadCamera, _super);
  88035. /**
  88036. * Creates a new AnaglyphGamepadCamera
  88037. * @param name defines camera name
  88038. * @param position defines initial position
  88039. * @param interaxialDistance defines distance between each color axis
  88040. * @param scene defines the hosting scene
  88041. */
  88042. function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {
  88043. var _this = _super.call(this, name, position, scene) || this;
  88044. _this.interaxialDistance = interaxialDistance;
  88045. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  88046. return _this;
  88047. }
  88048. /**
  88049. * Gets camera class name
  88050. * @returns AnaglyphGamepadCamera
  88051. */
  88052. AnaglyphGamepadCamera.prototype.getClassName = function () {
  88053. return "AnaglyphGamepadCamera";
  88054. };
  88055. return AnaglyphGamepadCamera;
  88056. }(BABYLON.GamepadCamera));
  88057. BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
  88058. /**
  88059. * Camera used to simulate anaglyphic rendering (based on UniversalCamera)
  88060. */
  88061. var AnaglyphUniversalCamera = /** @class */ (function (_super) {
  88062. __extends(AnaglyphUniversalCamera, _super);
  88063. /**
  88064. * Creates a new AnaglyphUniversalCamera
  88065. * @param name defines camera name
  88066. * @param position defines initial position
  88067. * @param interaxialDistance defines distance between each color axis
  88068. * @param scene defines the hosting scene
  88069. */
  88070. function AnaglyphUniversalCamera(name, position, interaxialDistance, scene) {
  88071. var _this = _super.call(this, name, position, scene) || this;
  88072. _this.interaxialDistance = interaxialDistance;
  88073. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  88074. return _this;
  88075. }
  88076. /**
  88077. * Gets camera class name
  88078. * @returns AnaglyphUniversalCamera
  88079. */
  88080. AnaglyphUniversalCamera.prototype.getClassName = function () {
  88081. return "AnaglyphUniversalCamera";
  88082. };
  88083. return AnaglyphUniversalCamera;
  88084. }(BABYLON.UniversalCamera));
  88085. BABYLON.AnaglyphUniversalCamera = AnaglyphUniversalCamera;
  88086. /**
  88087. * Camera used to simulate stereoscopic rendering (based on FreeCamera)
  88088. */
  88089. var StereoscopicFreeCamera = /** @class */ (function (_super) {
  88090. __extends(StereoscopicFreeCamera, _super);
  88091. /**
  88092. * Creates a new StereoscopicFreeCamera
  88093. * @param name defines camera name
  88094. * @param position defines initial position
  88095. * @param interaxialDistance defines distance between each color axis
  88096. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  88097. * @param scene defines the hosting scene
  88098. */
  88099. function StereoscopicFreeCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  88100. var _this = _super.call(this, name, position, scene) || this;
  88101. _this.interaxialDistance = interaxialDistance;
  88102. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  88103. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  88104. return _this;
  88105. }
  88106. /**
  88107. * Gets camera class name
  88108. * @returns StereoscopicFreeCamera
  88109. */
  88110. StereoscopicFreeCamera.prototype.getClassName = function () {
  88111. return "StereoscopicFreeCamera";
  88112. };
  88113. return StereoscopicFreeCamera;
  88114. }(BABYLON.FreeCamera));
  88115. BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
  88116. /**
  88117. * Camera used to simulate stereoscopic rendering (based on ArcRotateCamera)
  88118. */
  88119. var StereoscopicArcRotateCamera = /** @class */ (function (_super) {
  88120. __extends(StereoscopicArcRotateCamera, _super);
  88121. /**
  88122. * Creates a new StereoscopicArcRotateCamera
  88123. * @param name defines camera name
  88124. * @param alpha defines alpha angle (in radians)
  88125. * @param beta defines beta angle (in radians)
  88126. * @param radius defines radius
  88127. * @param target defines camera target
  88128. * @param interaxialDistance defines distance between each color axis
  88129. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  88130. * @param scene defines the hosting scene
  88131. */
  88132. function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isStereoscopicSideBySide, scene) {
  88133. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  88134. _this.interaxialDistance = interaxialDistance;
  88135. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  88136. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  88137. return _this;
  88138. }
  88139. /**
  88140. * Gets camera class name
  88141. * @returns StereoscopicArcRotateCamera
  88142. */
  88143. StereoscopicArcRotateCamera.prototype.getClassName = function () {
  88144. return "StereoscopicArcRotateCamera";
  88145. };
  88146. return StereoscopicArcRotateCamera;
  88147. }(BABYLON.ArcRotateCamera));
  88148. BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
  88149. /**
  88150. * Camera used to simulate stereoscopic rendering (based on GamepadCamera)
  88151. */
  88152. var StereoscopicGamepadCamera = /** @class */ (function (_super) {
  88153. __extends(StereoscopicGamepadCamera, _super);
  88154. /**
  88155. * Creates a new StereoscopicGamepadCamera
  88156. * @param name defines camera name
  88157. * @param position defines initial position
  88158. * @param interaxialDistance defines distance between each color axis
  88159. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  88160. * @param scene defines the hosting scene
  88161. */
  88162. function StereoscopicGamepadCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  88163. var _this = _super.call(this, name, position, scene) || this;
  88164. _this.interaxialDistance = interaxialDistance;
  88165. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  88166. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  88167. return _this;
  88168. }
  88169. /**
  88170. * Gets camera class name
  88171. * @returns StereoscopicGamepadCamera
  88172. */
  88173. StereoscopicGamepadCamera.prototype.getClassName = function () {
  88174. return "StereoscopicGamepadCamera";
  88175. };
  88176. return StereoscopicGamepadCamera;
  88177. }(BABYLON.GamepadCamera));
  88178. BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
  88179. /**
  88180. * Camera used to simulate stereoscopic rendering (based on UniversalCamera)
  88181. */
  88182. var StereoscopicUniversalCamera = /** @class */ (function (_super) {
  88183. __extends(StereoscopicUniversalCamera, _super);
  88184. /**
  88185. * Creates a new StereoscopicUniversalCamera
  88186. * @param name defines camera name
  88187. * @param position defines initial position
  88188. * @param interaxialDistance defines distance between each color axis
  88189. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  88190. * @param scene defines the hosting scene
  88191. */
  88192. function StereoscopicUniversalCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  88193. var _this = _super.call(this, name, position, scene) || this;
  88194. _this.interaxialDistance = interaxialDistance;
  88195. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  88196. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  88197. return _this;
  88198. }
  88199. /**
  88200. * Gets camera class name
  88201. * @returns StereoscopicUniversalCamera
  88202. */
  88203. StereoscopicUniversalCamera.prototype.getClassName = function () {
  88204. return "StereoscopicUniversalCamera";
  88205. };
  88206. return StereoscopicUniversalCamera;
  88207. }(BABYLON.UniversalCamera));
  88208. BABYLON.StereoscopicUniversalCamera = StereoscopicUniversalCamera;
  88209. })(BABYLON || (BABYLON = {}));
  88210. //# sourceMappingURL=babylon.stereoscopicCameras.js.map
  88211. var BABYLON;
  88212. (function (BABYLON) {
  88213. var VRExperienceHelperGazer = /** @class */ (function () {
  88214. function VRExperienceHelperGazer(scene, gazeTrackerToClone) {
  88215. if (gazeTrackerToClone === void 0) { gazeTrackerToClone = null; }
  88216. this.scene = scene;
  88217. this._pointerDownOnMeshAsked = false;
  88218. this._isActionableMesh = false;
  88219. this._teleportationRequestInitiated = false;
  88220. this._teleportationBackRequestInitiated = false;
  88221. this._rotationRightAsked = false;
  88222. this._rotationLeftAsked = false;
  88223. this._dpadPressed = true;
  88224. this._activePointer = false;
  88225. this._id = VRExperienceHelperGazer._idCounter++;
  88226. // Gaze tracker
  88227. if (!gazeTrackerToClone) {
  88228. this._gazeTracker = BABYLON.Mesh.CreateTorus("gazeTracker", 0.0035, 0.0025, 20, scene, false);
  88229. this._gazeTracker.bakeCurrentTransformIntoVertices();
  88230. this._gazeTracker.isPickable = false;
  88231. this._gazeTracker.isVisible = false;
  88232. var targetMat = new BABYLON.StandardMaterial("targetMat", scene);
  88233. targetMat.specularColor = BABYLON.Color3.Black();
  88234. targetMat.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  88235. targetMat.backFaceCulling = false;
  88236. this._gazeTracker.material = targetMat;
  88237. }
  88238. else {
  88239. this._gazeTracker = gazeTrackerToClone.clone("gazeTracker");
  88240. }
  88241. }
  88242. VRExperienceHelperGazer.prototype._getForwardRay = function (length) {
  88243. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, length));
  88244. };
  88245. VRExperienceHelperGazer.prototype._selectionPointerDown = function () {
  88246. this._pointerDownOnMeshAsked = true;
  88247. if (this._currentHit) {
  88248. this.scene.simulatePointerDown(this._currentHit, { pointerId: this._id });
  88249. }
  88250. };
  88251. VRExperienceHelperGazer.prototype._selectionPointerUp = function () {
  88252. if (this._currentHit) {
  88253. this.scene.simulatePointerUp(this._currentHit, { pointerId: this._id });
  88254. }
  88255. this._pointerDownOnMeshAsked = false;
  88256. };
  88257. VRExperienceHelperGazer.prototype._activatePointer = function () {
  88258. this._activePointer = true;
  88259. };
  88260. VRExperienceHelperGazer.prototype._deactivatePointer = function () {
  88261. this._activePointer = false;
  88262. };
  88263. VRExperienceHelperGazer.prototype._updatePointerDistance = function (distance) {
  88264. if (distance === void 0) { distance = 100; }
  88265. };
  88266. VRExperienceHelperGazer.prototype.dispose = function () {
  88267. this._interactionsEnabled = false;
  88268. this._teleportationEnabled = false;
  88269. if (this._gazeTracker) {
  88270. this._gazeTracker.dispose();
  88271. }
  88272. };
  88273. VRExperienceHelperGazer._idCounter = 0;
  88274. return VRExperienceHelperGazer;
  88275. }());
  88276. var VRExperienceHelperControllerGazer = /** @class */ (function (_super) {
  88277. __extends(VRExperienceHelperControllerGazer, _super);
  88278. function VRExperienceHelperControllerGazer(webVRController, scene, gazeTrackerToClone) {
  88279. var _this = _super.call(this, scene, gazeTrackerToClone) || this;
  88280. _this.webVRController = webVRController;
  88281. // Laser pointer
  88282. _this._laserPointer = BABYLON.Mesh.CreateCylinder("laserPointer", 1, 0.004, 0.0002, 20, 1, scene, false);
  88283. var laserPointerMaterial = new BABYLON.StandardMaterial("laserPointerMat", scene);
  88284. laserPointerMaterial.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  88285. laserPointerMaterial.alpha = 0.6;
  88286. _this._laserPointer.material = laserPointerMaterial;
  88287. _this._laserPointer.rotation.x = Math.PI / 2;
  88288. _this._laserPointer.position.z = -0.5;
  88289. _this._laserPointer.isVisible = false;
  88290. if (!webVRController.mesh) {
  88291. // Create an empty mesh that is used prior to loading the high quality model
  88292. var preloadMesh = new BABYLON.Mesh("preloadControllerMesh", scene);
  88293. var preloadPointerPose = new BABYLON.Mesh(BABYLON.PoseEnabledController.POINTING_POSE, scene);
  88294. preloadPointerPose.rotation.x = -0.7;
  88295. preloadMesh.addChild(preloadPointerPose);
  88296. webVRController.attachToMesh(preloadMesh);
  88297. }
  88298. _this._setLaserPointerParent(webVRController.mesh);
  88299. _this._meshAttachedObserver = webVRController._meshAttachedObservable.add(function (mesh) {
  88300. _this._setLaserPointerParent(mesh);
  88301. });
  88302. return _this;
  88303. }
  88304. VRExperienceHelperControllerGazer.prototype._getForwardRay = function (length) {
  88305. return this.webVRController.getForwardRay(length);
  88306. };
  88307. VRExperienceHelperControllerGazer.prototype._activatePointer = function () {
  88308. _super.prototype._activatePointer.call(this);
  88309. this._laserPointer.isVisible = true;
  88310. };
  88311. VRExperienceHelperControllerGazer.prototype._deactivatePointer = function () {
  88312. _super.prototype._deactivatePointer.call(this);
  88313. this._laserPointer.isVisible = false;
  88314. };
  88315. VRExperienceHelperControllerGazer.prototype._setLaserPointerColor = function (color) {
  88316. this._laserPointer.material.emissiveColor = color;
  88317. };
  88318. VRExperienceHelperControllerGazer.prototype._setLaserPointerParent = function (mesh) {
  88319. var makeNotPick = function (root) {
  88320. root.name += " laserPointer";
  88321. root.getChildMeshes().forEach(function (c) {
  88322. makeNotPick(c);
  88323. });
  88324. };
  88325. makeNotPick(mesh);
  88326. var childMeshes = mesh.getChildMeshes();
  88327. this.webVRController._pointingPoseNode = null;
  88328. for (var i = 0; i < childMeshes.length; i++) {
  88329. if (childMeshes[i].name && childMeshes[i].name.indexOf(BABYLON.PoseEnabledController.POINTING_POSE) >= 0) {
  88330. mesh = childMeshes[i];
  88331. this.webVRController._pointingPoseNode = mesh;
  88332. break;
  88333. }
  88334. }
  88335. this._laserPointer.parent = mesh;
  88336. };
  88337. VRExperienceHelperControllerGazer.prototype._updatePointerDistance = function (distance) {
  88338. if (distance === void 0) { distance = 100; }
  88339. this._laserPointer.scaling.y = distance;
  88340. this._laserPointer.position.z = -distance / 2;
  88341. };
  88342. VRExperienceHelperControllerGazer.prototype.dispose = function () {
  88343. _super.prototype.dispose.call(this);
  88344. this._laserPointer.dispose();
  88345. if (this._meshAttachedObserver) {
  88346. this.webVRController._meshAttachedObservable.remove(this._meshAttachedObserver);
  88347. }
  88348. };
  88349. return VRExperienceHelperControllerGazer;
  88350. }(VRExperienceHelperGazer));
  88351. var VRExperienceHelperCameraGazer = /** @class */ (function (_super) {
  88352. __extends(VRExperienceHelperCameraGazer, _super);
  88353. function VRExperienceHelperCameraGazer(getCamera, scene) {
  88354. var _this = _super.call(this, scene) || this;
  88355. _this.getCamera = getCamera;
  88356. return _this;
  88357. }
  88358. VRExperienceHelperCameraGazer.prototype._getForwardRay = function (length) {
  88359. var camera = this.getCamera();
  88360. if (camera) {
  88361. return camera.getForwardRay(length);
  88362. }
  88363. else {
  88364. return new BABYLON.Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Forward());
  88365. }
  88366. };
  88367. return VRExperienceHelperCameraGazer;
  88368. }(VRExperienceHelperGazer));
  88369. /**
  88370. * Helps to quickly add VR support to an existing scene.
  88371. * See http://doc.babylonjs.com/how_to/webvr_helper
  88372. */
  88373. var VRExperienceHelper = /** @class */ (function () {
  88374. /**
  88375. * Instantiates a VRExperienceHelper.
  88376. * Helps to quickly add VR support to an existing scene.
  88377. * @param scene The scene the VRExperienceHelper belongs to.
  88378. * @param webVROptions Options to modify the vr experience helper's behavior.
  88379. */
  88380. function VRExperienceHelper(scene, /** Options to modify the vr experience helper's behavior. */ webVROptions) {
  88381. if (webVROptions === void 0) { webVROptions = {}; }
  88382. var _this = this;
  88383. this.webVROptions = webVROptions;
  88384. // Can the system support WebVR, even if a headset isn't plugged in?
  88385. this._webVRsupported = false;
  88386. // If WebVR is supported, is a headset plugged in and are we ready to present?
  88387. this._webVRready = false;
  88388. // Are we waiting for the requestPresent callback to complete?
  88389. this._webVRrequesting = false;
  88390. // Are we presenting to the headset right now?
  88391. this._webVRpresenting = false;
  88392. // Are we presenting in the fullscreen fallback?
  88393. this._fullscreenVRpresenting = false;
  88394. /**
  88395. * Observable raised when entering VR.
  88396. */
  88397. this.onEnteringVRObservable = new BABYLON.Observable();
  88398. /**
  88399. * Observable raised when exiting VR.
  88400. */
  88401. this.onExitingVRObservable = new BABYLON.Observable();
  88402. /**
  88403. * Observable raised when controller mesh is loaded.
  88404. */
  88405. this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  88406. this._useCustomVRButton = false;
  88407. this._teleportationRequested = false;
  88408. this._teleportActive = false;
  88409. this._floorMeshesCollection = [];
  88410. this._rotationAllowed = true;
  88411. this._teleportBackwardsVector = new BABYLON.Vector3(0, -1, -1);
  88412. this._isDefaultTeleportationTarget = true;
  88413. this._teleportationFillColor = "#444444";
  88414. this._teleportationBorderColor = "#FFFFFF";
  88415. this._rotationAngle = 0;
  88416. this._haloCenter = new BABYLON.Vector3(0, 0, 0);
  88417. this._padSensibilityUp = 0.65;
  88418. this._padSensibilityDown = 0.35;
  88419. this.leftController = null;
  88420. this.rightController = null;
  88421. /**
  88422. * Observable raised when a new mesh is selected based on meshSelectionPredicate
  88423. */
  88424. this.onNewMeshSelected = new BABYLON.Observable();
  88425. /**
  88426. * Observable raised when a new mesh is picked based on meshSelectionPredicate
  88427. */
  88428. this.onNewMeshPicked = new BABYLON.Observable();
  88429. /**
  88430. * Observable raised before camera teleportation
  88431. */
  88432. this.onBeforeCameraTeleport = new BABYLON.Observable();
  88433. /**
  88434. * Observable raised after camera teleportation
  88435. */
  88436. this.onAfterCameraTeleport = new BABYLON.Observable();
  88437. /**
  88438. * Observable raised when current selected mesh gets unselected
  88439. */
  88440. this.onSelectedMeshUnselected = new BABYLON.Observable();
  88441. /**
  88442. * Set teleportation enabled. If set to false camera teleportation will be disabled but camera rotation will be kept.
  88443. */
  88444. this.teleportationEnabled = true;
  88445. this._teleportationInitialized = false;
  88446. this._interactionsEnabled = false;
  88447. this._interactionsRequested = false;
  88448. this._displayGaze = true;
  88449. this._displayLaserPointer = true;
  88450. this._onResize = function () {
  88451. _this.moveButtonToBottomRight();
  88452. if (_this._fullscreenVRpresenting && _this._webVRready) {
  88453. _this.exitVR();
  88454. }
  88455. };
  88456. this._onFullscreenChange = function () {
  88457. if (document.fullscreen !== undefined) {
  88458. _this._fullscreenVRpresenting = document.fullscreen;
  88459. }
  88460. else if (document.mozFullScreen !== undefined) {
  88461. _this._fullscreenVRpresenting = document.mozFullScreen;
  88462. }
  88463. else if (document.webkitIsFullScreen !== undefined) {
  88464. _this._fullscreenVRpresenting = document.webkitIsFullScreen;
  88465. }
  88466. else if (document.msIsFullScreen !== undefined) {
  88467. _this._fullscreenVRpresenting = document.msIsFullScreen;
  88468. }
  88469. if (!_this._fullscreenVRpresenting && _this._canvas) {
  88470. _this.exitVR();
  88471. if (!_this._useCustomVRButton) {
  88472. _this._btnVR.style.top = _this._canvas.offsetTop + _this._canvas.offsetHeight - 70 + "px";
  88473. _this._btnVR.style.left = _this._canvas.offsetLeft + _this._canvas.offsetWidth - 100 + "px";
  88474. }
  88475. }
  88476. };
  88477. this.beforeRender = function () {
  88478. if (_this.leftController && _this.leftController._activePointer) {
  88479. _this._castRayAndSelectObject(_this.leftController);
  88480. }
  88481. if (_this.rightController && _this.rightController._activePointer) {
  88482. _this._castRayAndSelectObject(_this.rightController);
  88483. }
  88484. if (!(_this.leftController && _this.leftController._activePointer) && !(_this.rightController && _this.rightController._activePointer)) {
  88485. _this._castRayAndSelectObject(_this._cameraGazer);
  88486. }
  88487. else {
  88488. _this._cameraGazer._gazeTracker.isVisible = false;
  88489. }
  88490. };
  88491. this._onNewGamepadConnected = function (gamepad) {
  88492. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  88493. if (gamepad.leftStick) {
  88494. gamepad.onleftstickchanged(function (stickValues) {
  88495. if (_this._teleportationInitialized && _this.teleportationEnabled) {
  88496. // Listening to classic/xbox gamepad only if no VR controller is active
  88497. if ((!_this.leftController && !_this.rightController) ||
  88498. ((_this.leftController && !_this.leftController._activePointer) &&
  88499. (_this.rightController && !_this.rightController._activePointer))) {
  88500. _this._checkTeleportWithRay(stickValues, _this._cameraGazer);
  88501. _this._checkTeleportBackwards(stickValues, _this._cameraGazer);
  88502. }
  88503. }
  88504. });
  88505. }
  88506. if (gamepad.rightStick) {
  88507. gamepad.onrightstickchanged(function (stickValues) {
  88508. if (_this._teleportationInitialized) {
  88509. _this._checkRotate(stickValues, _this._cameraGazer);
  88510. }
  88511. });
  88512. }
  88513. if (gamepad.type === BABYLON.Gamepad.XBOX) {
  88514. gamepad.onbuttondown(function (buttonPressed) {
  88515. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  88516. _this._cameraGazer._selectionPointerDown();
  88517. }
  88518. });
  88519. gamepad.onbuttonup(function (buttonPressed) {
  88520. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  88521. _this._cameraGazer._selectionPointerUp();
  88522. }
  88523. });
  88524. }
  88525. }
  88526. else {
  88527. var webVRController = gamepad;
  88528. var controller = new VRExperienceHelperControllerGazer(webVRController, _this._scene, _this._cameraGazer._gazeTracker);
  88529. if (webVRController.hand === "right" || (_this.leftController && _this.leftController.webVRController != webVRController)) {
  88530. _this.rightController = controller;
  88531. }
  88532. else {
  88533. _this.leftController = controller;
  88534. }
  88535. _this._tryEnableInteractionOnController(controller);
  88536. }
  88537. };
  88538. // 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
  88539. this._tryEnableInteractionOnController = function (controller) {
  88540. if (_this._interactionsRequested && !controller._interactionsEnabled) {
  88541. _this._enableInteractionOnController(controller);
  88542. }
  88543. if (_this._teleportationRequested && !controller._teleportationEnabled) {
  88544. _this._enableTeleportationOnController(controller);
  88545. }
  88546. };
  88547. this._onNewGamepadDisconnected = function (gamepad) {
  88548. if (gamepad instanceof BABYLON.WebVRController) {
  88549. if (gamepad.hand === "left" && _this.leftController != null) {
  88550. _this.leftController.dispose();
  88551. _this.leftController = null;
  88552. }
  88553. if (gamepad.hand === "right" && _this.rightController != null) {
  88554. _this.rightController.dispose();
  88555. _this.rightController = null;
  88556. }
  88557. }
  88558. };
  88559. this._workingVector = BABYLON.Vector3.Zero();
  88560. this._workingQuaternion = BABYLON.Quaternion.Identity();
  88561. this._workingMatrix = BABYLON.Matrix.Identity();
  88562. this._scene = scene;
  88563. this._canvas = scene.getEngine().getRenderingCanvas();
  88564. // Parse options
  88565. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera === undefined) {
  88566. webVROptions.createFallbackVRDeviceOrientationFreeCamera = true;
  88567. }
  88568. if (webVROptions.createDeviceOrientationCamera === undefined) {
  88569. webVROptions.createDeviceOrientationCamera = true;
  88570. }
  88571. if (webVROptions.laserToggle === undefined) {
  88572. webVROptions.laserToggle = true;
  88573. }
  88574. if (webVROptions.defaultHeight === undefined) {
  88575. webVROptions.defaultHeight = 1.7;
  88576. }
  88577. if (webVROptions.useCustomVRButton) {
  88578. this._useCustomVRButton = true;
  88579. if (webVROptions.customVRButton) {
  88580. this._btnVR = webVROptions.customVRButton;
  88581. }
  88582. }
  88583. if (webVROptions.rayLength) {
  88584. this._rayLength = webVROptions.rayLength;
  88585. }
  88586. this._defaultHeight = webVROptions.defaultHeight;
  88587. if (webVROptions.positionScale) {
  88588. this._rayLength *= webVROptions.positionScale;
  88589. this._defaultHeight *= webVROptions.positionScale;
  88590. }
  88591. // Set position
  88592. if (this._scene.activeCamera) {
  88593. this._position = this._scene.activeCamera.position.clone();
  88594. }
  88595. else {
  88596. this._position = new BABYLON.Vector3(0, this._defaultHeight, 0);
  88597. }
  88598. // Set non-vr camera
  88599. if (webVROptions.createDeviceOrientationCamera || !this._scene.activeCamera) {
  88600. this._deviceOrientationCamera = new BABYLON.DeviceOrientationCamera("deviceOrientationVRHelper", this._position.clone(), scene);
  88601. // Copy data from existing camera
  88602. if (this._scene.activeCamera) {
  88603. this._deviceOrientationCamera.minZ = this._scene.activeCamera.minZ;
  88604. this._deviceOrientationCamera.maxZ = this._scene.activeCamera.maxZ;
  88605. // Set rotation from previous camera
  88606. if (this._scene.activeCamera instanceof BABYLON.TargetCamera && this._scene.activeCamera.rotation) {
  88607. var targetCamera = this._scene.activeCamera;
  88608. if (targetCamera.rotationQuaternion) {
  88609. this._deviceOrientationCamera.rotationQuaternion.copyFrom(targetCamera.rotationQuaternion);
  88610. }
  88611. else {
  88612. this._deviceOrientationCamera.rotationQuaternion.copyFrom(BABYLON.Quaternion.RotationYawPitchRoll(targetCamera.rotation.y, targetCamera.rotation.x, targetCamera.rotation.z));
  88613. }
  88614. this._deviceOrientationCamera.rotation = targetCamera.rotation.clone();
  88615. }
  88616. }
  88617. this._scene.activeCamera = this._deviceOrientationCamera;
  88618. if (this._canvas) {
  88619. this._scene.activeCamera.attachControl(this._canvas);
  88620. }
  88621. }
  88622. else {
  88623. this._existingCamera = this._scene.activeCamera;
  88624. }
  88625. // Create VR cameras
  88626. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  88627. this._vrDeviceOrientationCamera = new BABYLON.VRDeviceOrientationFreeCamera("VRDeviceOrientationVRHelper", this._position, this._scene);
  88628. }
  88629. this._webVRCamera = new BABYLON.WebVRFreeCamera("WebVRHelper", this._position, this._scene, webVROptions);
  88630. this._webVRCamera.useStandingMatrix();
  88631. this._cameraGazer = new VRExperienceHelperCameraGazer(function () { return _this.currentVRCamera; }, scene);
  88632. // Create default button
  88633. if (!this._useCustomVRButton) {
  88634. this._btnVR = document.createElement("BUTTON");
  88635. this._btnVR.className = "babylonVRicon";
  88636. this._btnVR.id = "babylonVRiconbtn";
  88637. this._btnVR.title = "Click to switch to VR";
  88638. 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) }";
  88639. css += ".babylonVRicon.vrdisplaypresenting { display: none; }";
  88640. // TODO: Add user feedback so that they know what state the VRDisplay is in (disconnected, connected, entering-VR)
  88641. // css += ".babylonVRicon.vrdisplaysupported { }";
  88642. // css += ".babylonVRicon.vrdisplayready { }";
  88643. // css += ".babylonVRicon.vrdisplayrequesting { }";
  88644. var style = document.createElement('style');
  88645. style.appendChild(document.createTextNode(css));
  88646. document.getElementsByTagName('head')[0].appendChild(style);
  88647. this.moveButtonToBottomRight();
  88648. }
  88649. // VR button click event
  88650. if (this._btnVR) {
  88651. this._btnVR.addEventListener("click", function () {
  88652. if (!_this.isInVRMode) {
  88653. _this.enterVR();
  88654. }
  88655. else {
  88656. _this.exitVR();
  88657. }
  88658. });
  88659. }
  88660. // Window events
  88661. window.addEventListener("resize", this._onResize);
  88662. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  88663. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  88664. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  88665. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  88666. // Display vr button when headset is connected
  88667. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  88668. this.displayVRButton();
  88669. }
  88670. else {
  88671. this._scene.getEngine().onVRDisplayChangedObservable.add(function (e) {
  88672. if (e.vrDisplay) {
  88673. _this.displayVRButton();
  88674. }
  88675. });
  88676. }
  88677. // Exiting VR mode using 'ESC' key on desktop
  88678. this._onKeyDown = function (event) {
  88679. if (event.keyCode === 27 && _this.isInVRMode) {
  88680. _this.exitVR();
  88681. }
  88682. };
  88683. document.addEventListener("keydown", this._onKeyDown);
  88684. // Exiting VR mode double tapping the touch screen
  88685. this._scene.onPrePointerObservable.add(function (pointerInfo, eventState) {
  88686. if (_this.isInVRMode) {
  88687. _this.exitVR();
  88688. if (_this._fullscreenVRpresenting) {
  88689. _this._scene.getEngine().switchFullscreen(true);
  88690. }
  88691. }
  88692. }, BABYLON.PointerEventTypes.POINTERDOUBLETAP, false);
  88693. // Listen for WebVR display changes
  88694. this._onVRDisplayChanged = function (eventArgs) { return _this.onVRDisplayChanged(eventArgs); };
  88695. this._onVrDisplayPresentChange = function () { return _this.onVrDisplayPresentChange(); };
  88696. this._onVRRequestPresentStart = function () {
  88697. _this._webVRrequesting = true;
  88698. _this.updateButtonVisibility();
  88699. };
  88700. this._onVRRequestPresentComplete = function (success) {
  88701. _this._webVRrequesting = false;
  88702. _this.updateButtonVisibility();
  88703. };
  88704. scene.getEngine().onVRDisplayChangedObservable.add(this._onVRDisplayChanged);
  88705. scene.getEngine().onVRRequestPresentStart.add(this._onVRRequestPresentStart);
  88706. scene.getEngine().onVRRequestPresentComplete.add(this._onVRRequestPresentComplete);
  88707. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  88708. scene.onDisposeObservable.add(function () {
  88709. _this.dispose();
  88710. });
  88711. // Gamepad connection events
  88712. this._webVRCamera.onControllerMeshLoadedObservable.add(function (webVRController) { return _this._onDefaultMeshLoaded(webVRController); });
  88713. this._scene.gamepadManager.onGamepadConnectedObservable.add(this._onNewGamepadConnected);
  88714. this._scene.gamepadManager.onGamepadDisconnectedObservable.add(this._onNewGamepadDisconnected);
  88715. this.updateButtonVisibility();
  88716. //create easing functions
  88717. this._circleEase = new BABYLON.CircleEase();
  88718. this._circleEase.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  88719. if (this.webVROptions.floorMeshes) {
  88720. this.enableTeleportation({ floorMeshes: this.webVROptions.floorMeshes });
  88721. }
  88722. }
  88723. Object.defineProperty(VRExperienceHelper.prototype, "onEnteringVR", {
  88724. /** Return this.onEnteringVRObservable
  88725. * Note: This one is for backward compatibility. Please use onEnteringVRObservable directly
  88726. */
  88727. get: function () {
  88728. return this.onEnteringVRObservable;
  88729. },
  88730. enumerable: true,
  88731. configurable: true
  88732. });
  88733. Object.defineProperty(VRExperienceHelper.prototype, "onExitingVR", {
  88734. /** Return this.onExitingVRObservable
  88735. * Note: This one is for backward compatibility. Please use onExitingVRObservable directly
  88736. */
  88737. get: function () {
  88738. return this.onExitingVRObservable;
  88739. },
  88740. enumerable: true,
  88741. configurable: true
  88742. });
  88743. Object.defineProperty(VRExperienceHelper.prototype, "onControllerMeshLoaded", {
  88744. /** Return this.onControllerMeshLoadedObservable
  88745. * Note: This one is for backward compatibility. Please use onControllerMeshLoadedObservable directly
  88746. */
  88747. get: function () {
  88748. return this.onControllerMeshLoadedObservable;
  88749. },
  88750. enumerable: true,
  88751. configurable: true
  88752. });
  88753. Object.defineProperty(VRExperienceHelper.prototype, "teleportationTarget", {
  88754. /**
  88755. * The mesh used to display where the user is going to teleport.
  88756. */
  88757. get: function () {
  88758. return this._teleportationTarget;
  88759. },
  88760. /**
  88761. * Sets the mesh to be used to display where the user is going to teleport.
  88762. */
  88763. set: function (value) {
  88764. if (value) {
  88765. value.name = "teleportationTarget";
  88766. this._isDefaultTeleportationTarget = false;
  88767. this._teleportationTarget = value;
  88768. }
  88769. },
  88770. enumerable: true,
  88771. configurable: true
  88772. });
  88773. Object.defineProperty(VRExperienceHelper.prototype, "gazeTrackerMesh", {
  88774. /**
  88775. * The mesh used to display where the user is selecting,
  88776. * when set bakeCurrentTransformIntoVertices will be called on the mesh.
  88777. * See http://doc.babylonjs.com/resources/baking_transformations
  88778. */
  88779. get: function () {
  88780. return this._cameraGazer._gazeTracker;
  88781. },
  88782. set: function (value) {
  88783. if (value) {
  88784. this._cameraGazer._gazeTracker = value;
  88785. this._cameraGazer._gazeTracker.bakeCurrentTransformIntoVertices();
  88786. this._cameraGazer._gazeTracker.isPickable = false;
  88787. this._cameraGazer._gazeTracker.isVisible = false;
  88788. this._cameraGazer._gazeTracker.name = "gazeTracker";
  88789. if (this.leftController) {
  88790. this.leftController._gazeTracker = this._cameraGazer._gazeTracker.clone("gazeTracker");
  88791. }
  88792. if (this.rightController) {
  88793. this.rightController._gazeTracker = this._cameraGazer._gazeTracker.clone("gazeTracker");
  88794. }
  88795. }
  88796. },
  88797. enumerable: true,
  88798. configurable: true
  88799. });
  88800. Object.defineProperty(VRExperienceHelper.prototype, "displayGaze", {
  88801. /**
  88802. * If the ray of the gaze should be displayed.
  88803. */
  88804. get: function () {
  88805. return this._displayGaze;
  88806. },
  88807. /**
  88808. * Sets if the ray of the gaze should be displayed.
  88809. */
  88810. set: function (value) {
  88811. this._displayGaze = value;
  88812. if (!value) {
  88813. this._cameraGazer._gazeTracker.isVisible = false;
  88814. if (this.leftController) {
  88815. this.leftController._gazeTracker.isVisible = false;
  88816. }
  88817. if (this.rightController) {
  88818. this.rightController._gazeTracker.isVisible = false;
  88819. }
  88820. }
  88821. },
  88822. enumerable: true,
  88823. configurable: true
  88824. });
  88825. Object.defineProperty(VRExperienceHelper.prototype, "displayLaserPointer", {
  88826. /**
  88827. * If the ray of the LaserPointer should be displayed.
  88828. */
  88829. get: function () {
  88830. return this._displayLaserPointer;
  88831. },
  88832. /**
  88833. * Sets if the ray of the LaserPointer should be displayed.
  88834. */
  88835. set: function (value) {
  88836. this._displayLaserPointer = value;
  88837. if (!value) {
  88838. if (this.rightController) {
  88839. this.rightController._deactivatePointer();
  88840. this.rightController._gazeTracker.isVisible = false;
  88841. }
  88842. if (this.leftController) {
  88843. this.leftController._deactivatePointer();
  88844. this.leftController._gazeTracker.isVisible = false;
  88845. }
  88846. }
  88847. else {
  88848. if (this.rightController) {
  88849. this.rightController._activatePointer();
  88850. }
  88851. if (this.leftController) {
  88852. this.leftController._activatePointer();
  88853. }
  88854. }
  88855. },
  88856. enumerable: true,
  88857. configurable: true
  88858. });
  88859. Object.defineProperty(VRExperienceHelper.prototype, "deviceOrientationCamera", {
  88860. /**
  88861. * The deviceOrientationCamera used as the camera when not in VR.
  88862. */
  88863. get: function () {
  88864. return this._deviceOrientationCamera;
  88865. },
  88866. enumerable: true,
  88867. configurable: true
  88868. });
  88869. Object.defineProperty(VRExperienceHelper.prototype, "currentVRCamera", {
  88870. /**
  88871. * Based on the current WebVR support, returns the current VR camera used.
  88872. */
  88873. get: function () {
  88874. if (this._webVRready) {
  88875. return this._webVRCamera;
  88876. }
  88877. else {
  88878. return this._scene.activeCamera;
  88879. }
  88880. },
  88881. enumerable: true,
  88882. configurable: true
  88883. });
  88884. Object.defineProperty(VRExperienceHelper.prototype, "webVRCamera", {
  88885. /**
  88886. * The webVRCamera which is used when in VR.
  88887. */
  88888. get: function () {
  88889. return this._webVRCamera;
  88890. },
  88891. enumerable: true,
  88892. configurable: true
  88893. });
  88894. Object.defineProperty(VRExperienceHelper.prototype, "vrDeviceOrientationCamera", {
  88895. /**
  88896. * The deviceOrientationCamera that is used as a fallback when vr device is not connected.
  88897. */
  88898. get: function () {
  88899. return this._vrDeviceOrientationCamera;
  88900. },
  88901. enumerable: true,
  88902. configurable: true
  88903. });
  88904. Object.defineProperty(VRExperienceHelper.prototype, "_teleportationRequestInitiated", {
  88905. get: function () {
  88906. var result = this._cameraGazer._teleportationRequestInitiated
  88907. || (this.leftController !== null && this.leftController._teleportationRequestInitiated)
  88908. || (this.rightController !== null && this.rightController._teleportationRequestInitiated);
  88909. return result;
  88910. },
  88911. enumerable: true,
  88912. configurable: true
  88913. });
  88914. // Raised when one of the controller has loaded successfully its associated default mesh
  88915. VRExperienceHelper.prototype._onDefaultMeshLoaded = function (webVRController) {
  88916. if (this.leftController && this.leftController.webVRController == webVRController) {
  88917. if (webVRController.mesh) {
  88918. this.leftController._setLaserPointerParent(webVRController.mesh);
  88919. }
  88920. }
  88921. if (this.rightController && this.rightController.webVRController == webVRController) {
  88922. if (webVRController.mesh) {
  88923. this.rightController._setLaserPointerParent(webVRController.mesh);
  88924. }
  88925. }
  88926. try {
  88927. this.onControllerMeshLoadedObservable.notifyObservers(webVRController);
  88928. }
  88929. catch (err) {
  88930. BABYLON.Tools.Warn("Error in your custom logic onControllerMeshLoaded: " + err);
  88931. }
  88932. };
  88933. Object.defineProperty(VRExperienceHelper.prototype, "isInVRMode", {
  88934. /**
  88935. * Gets a value indicating if we are currently in VR mode.
  88936. */
  88937. get: function () {
  88938. return this._webVRpresenting || this._fullscreenVRpresenting;
  88939. },
  88940. enumerable: true,
  88941. configurable: true
  88942. });
  88943. VRExperienceHelper.prototype.onVrDisplayPresentChange = function () {
  88944. var vrDisplay = this._scene.getEngine().getVRDevice();
  88945. if (vrDisplay) {
  88946. var wasPresenting = this._webVRpresenting;
  88947. // A VR display is connected
  88948. this._webVRpresenting = vrDisplay.isPresenting;
  88949. if (wasPresenting && !this._webVRpresenting)
  88950. this.exitVR();
  88951. }
  88952. else {
  88953. BABYLON.Tools.Warn('Detected VRDisplayPresentChange on an unknown VRDisplay. Did you can enterVR on the vrExperienceHelper?');
  88954. }
  88955. this.updateButtonVisibility();
  88956. };
  88957. VRExperienceHelper.prototype.onVRDisplayChanged = function (eventArgs) {
  88958. this._webVRsupported = eventArgs.vrSupported;
  88959. this._webVRready = !!eventArgs.vrDisplay;
  88960. this._webVRpresenting = eventArgs.vrDisplay && eventArgs.vrDisplay.isPresenting;
  88961. this.updateButtonVisibility();
  88962. };
  88963. VRExperienceHelper.prototype.moveButtonToBottomRight = function () {
  88964. if (this._canvas && !this._useCustomVRButton) {
  88965. this._btnVR.style.top = this._canvas.offsetTop + this._canvas.offsetHeight - 70 + "px";
  88966. this._btnVR.style.left = this._canvas.offsetLeft + this._canvas.offsetWidth - 100 + "px";
  88967. }
  88968. };
  88969. VRExperienceHelper.prototype.displayVRButton = function () {
  88970. if (!this._useCustomVRButton && !this._btnVRDisplayed) {
  88971. document.body.appendChild(this._btnVR);
  88972. this._btnVRDisplayed = true;
  88973. }
  88974. };
  88975. VRExperienceHelper.prototype.updateButtonVisibility = function () {
  88976. if (!this._btnVR || this._useCustomVRButton) {
  88977. return;
  88978. }
  88979. this._btnVR.className = "babylonVRicon";
  88980. if (this.isInVRMode) {
  88981. this._btnVR.className += " vrdisplaypresenting";
  88982. }
  88983. else {
  88984. if (this._webVRready)
  88985. this._btnVR.className += " vrdisplayready";
  88986. if (this._webVRsupported)
  88987. this._btnVR.className += " vrdisplaysupported";
  88988. if (this._webVRrequesting)
  88989. this._btnVR.className += " vrdisplayrequesting";
  88990. }
  88991. };
  88992. /**
  88993. * Attempt to enter VR. If a headset is connected and ready, will request present on that.
  88994. * Otherwise, will use the fullscreen API.
  88995. */
  88996. VRExperienceHelper.prototype.enterVR = function () {
  88997. if (this.onEnteringVRObservable) {
  88998. try {
  88999. this.onEnteringVRObservable.notifyObservers(this);
  89000. }
  89001. catch (err) {
  89002. BABYLON.Tools.Warn("Error in your custom logic onEnteringVR: " + err);
  89003. }
  89004. }
  89005. if (this._scene.activeCamera) {
  89006. this._position = this._scene.activeCamera.position.clone();
  89007. // make sure that we return to the last active camera
  89008. this._existingCamera = this._scene.activeCamera;
  89009. }
  89010. if (this._webVRrequesting)
  89011. return;
  89012. // If WebVR is supported and a headset is connected
  89013. if (this._webVRready) {
  89014. if (!this._webVRpresenting) {
  89015. this._webVRCamera.position = this._position;
  89016. this._scene.activeCamera = this._webVRCamera;
  89017. }
  89018. }
  89019. else if (this._vrDeviceOrientationCamera) {
  89020. this._vrDeviceOrientationCamera.position = this._position;
  89021. if (this._scene.activeCamera) {
  89022. this._vrDeviceOrientationCamera.minZ = this._scene.activeCamera.minZ;
  89023. }
  89024. this._scene.activeCamera = this._vrDeviceOrientationCamera;
  89025. this._scene.getEngine().switchFullscreen(true);
  89026. this.updateButtonVisibility();
  89027. }
  89028. if (this._scene.activeCamera && this._canvas) {
  89029. this._scene.activeCamera.attachControl(this._canvas);
  89030. }
  89031. if (this._interactionsEnabled) {
  89032. this._scene.registerBeforeRender(this.beforeRender);
  89033. }
  89034. };
  89035. /**
  89036. * Attempt to exit VR, or fullscreen.
  89037. */
  89038. VRExperienceHelper.prototype.exitVR = function () {
  89039. if (this.onExitingVRObservable) {
  89040. try {
  89041. this.onExitingVRObservable.notifyObservers(this);
  89042. }
  89043. catch (err) {
  89044. BABYLON.Tools.Warn("Error in your custom logic onExitingVR: " + err);
  89045. }
  89046. }
  89047. if (this._webVRpresenting) {
  89048. this._scene.getEngine().disableVR();
  89049. }
  89050. if (this._scene.activeCamera) {
  89051. this._position = this._scene.activeCamera.position.clone();
  89052. }
  89053. if (this._deviceOrientationCamera) {
  89054. this._deviceOrientationCamera.position = this._position;
  89055. this._scene.activeCamera = this._deviceOrientationCamera;
  89056. if (this._canvas) {
  89057. this._scene.activeCamera.attachControl(this._canvas);
  89058. }
  89059. }
  89060. else if (this._existingCamera) {
  89061. this._existingCamera.position = this._position;
  89062. this._scene.activeCamera = this._existingCamera;
  89063. }
  89064. this.updateButtonVisibility();
  89065. if (this._interactionsEnabled) {
  89066. this._scene.unregisterBeforeRender(this.beforeRender);
  89067. }
  89068. // resize to update width and height when exiting vr exits fullscreen
  89069. this._scene.getEngine().resize();
  89070. };
  89071. Object.defineProperty(VRExperienceHelper.prototype, "position", {
  89072. /**
  89073. * The position of the vr experience helper.
  89074. */
  89075. get: function () {
  89076. return this._position;
  89077. },
  89078. /**
  89079. * Sets the position of the vr experience helper.
  89080. */
  89081. set: function (value) {
  89082. this._position = value;
  89083. if (this._scene.activeCamera) {
  89084. this._scene.activeCamera.position = value;
  89085. }
  89086. },
  89087. enumerable: true,
  89088. configurable: true
  89089. });
  89090. /**
  89091. * Enables controllers and user interactions suck as selecting and object or clicking on an object.
  89092. */
  89093. VRExperienceHelper.prototype.enableInteractions = function () {
  89094. var _this = this;
  89095. if (!this._interactionsEnabled) {
  89096. this._interactionsRequested = true;
  89097. if (this.leftController) {
  89098. this._enableInteractionOnController(this.leftController);
  89099. }
  89100. if (this.rightController) {
  89101. this._enableInteractionOnController(this.rightController);
  89102. }
  89103. this.raySelectionPredicate = function (mesh) {
  89104. return mesh.isVisible;
  89105. };
  89106. this.meshSelectionPredicate = function (mesh) {
  89107. return true;
  89108. };
  89109. this._raySelectionPredicate = function (mesh) {
  89110. if (_this._isTeleportationFloor(mesh) || (mesh.name.indexOf("gazeTracker") === -1
  89111. && mesh.name.indexOf("teleportationTarget") === -1
  89112. && mesh.name.indexOf("torusTeleportation") === -1
  89113. && mesh.name.indexOf("laserPointer") === -1)) {
  89114. return _this.raySelectionPredicate(mesh);
  89115. }
  89116. return false;
  89117. };
  89118. this._interactionsEnabled = true;
  89119. }
  89120. };
  89121. VRExperienceHelper.prototype._isTeleportationFloor = function (mesh) {
  89122. for (var i = 0; i < this._floorMeshesCollection.length; i++) {
  89123. if (this._floorMeshesCollection[i].id === mesh.id) {
  89124. return true;
  89125. }
  89126. }
  89127. if (this._floorMeshName && mesh.name === this._floorMeshName) {
  89128. return true;
  89129. }
  89130. return false;
  89131. };
  89132. /**
  89133. * Adds a floor mesh to be used for teleportation.
  89134. * @param floorMesh the mesh to be used for teleportation.
  89135. */
  89136. VRExperienceHelper.prototype.addFloorMesh = function (floorMesh) {
  89137. if (!this._floorMeshesCollection) {
  89138. return;
  89139. }
  89140. if (this._floorMeshesCollection.indexOf(floorMesh) > -1) {
  89141. return;
  89142. }
  89143. this._floorMeshesCollection.push(floorMesh);
  89144. };
  89145. /**
  89146. * Removes a floor mesh from being used for teleportation.
  89147. * @param floorMesh the mesh to be removed.
  89148. */
  89149. VRExperienceHelper.prototype.removeFloorMesh = function (floorMesh) {
  89150. if (!this._floorMeshesCollection) {
  89151. return;
  89152. }
  89153. var meshIndex = this._floorMeshesCollection.indexOf(floorMesh);
  89154. if (meshIndex !== -1) {
  89155. this._floorMeshesCollection.splice(meshIndex, 1);
  89156. }
  89157. };
  89158. /**
  89159. * Enables interactions and teleportation using the VR controllers and gaze.
  89160. * @param vrTeleportationOptions options to modify teleportation behavior.
  89161. */
  89162. VRExperienceHelper.prototype.enableTeleportation = function (vrTeleportationOptions) {
  89163. if (vrTeleportationOptions === void 0) { vrTeleportationOptions = {}; }
  89164. if (!this._teleportationInitialized) {
  89165. this._teleportationRequested = true;
  89166. this.enableInteractions();
  89167. if (vrTeleportationOptions.floorMeshName) {
  89168. this._floorMeshName = vrTeleportationOptions.floorMeshName;
  89169. }
  89170. if (vrTeleportationOptions.floorMeshes) {
  89171. this._floorMeshesCollection = vrTeleportationOptions.floorMeshes;
  89172. }
  89173. if (this.leftController != null) {
  89174. this._enableTeleportationOnController(this.leftController);
  89175. }
  89176. if (this.rightController != null) {
  89177. this._enableTeleportationOnController(this.rightController);
  89178. }
  89179. // Creates an image processing post process for the vignette not relying
  89180. // on the main scene configuration for image processing to reduce setup and spaces
  89181. // (gamma/linear) conflicts.
  89182. var imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  89183. imageProcessingConfiguration.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  89184. imageProcessingConfiguration.vignetteEnabled = true;
  89185. this._postProcessMove = new BABYLON.ImageProcessingPostProcess("postProcessMove", 1.0, this._webVRCamera, undefined, undefined, undefined, undefined, imageProcessingConfiguration);
  89186. this._webVRCamera.detachPostProcess(this._postProcessMove);
  89187. this._teleportationInitialized = true;
  89188. if (this._isDefaultTeleportationTarget) {
  89189. this._createTeleportationCircles();
  89190. this._teleportationTarget.scaling.scaleInPlace(this._webVRCamera.deviceScaleFactor);
  89191. }
  89192. }
  89193. };
  89194. VRExperienceHelper.prototype._enableInteractionOnController = function (controller) {
  89195. var _this = this;
  89196. var controllerMesh = controller.webVRController.mesh;
  89197. if (controllerMesh) {
  89198. controller._interactionsEnabled = true;
  89199. controller._activatePointer();
  89200. if (this.webVROptions.laserToggle) {
  89201. controller.webVRController.onMainButtonStateChangedObservable.add(function (stateObject) {
  89202. // Enabling / disabling laserPointer
  89203. if (_this._displayLaserPointer && stateObject.value === 1) {
  89204. if (controller._activePointer) {
  89205. controller._deactivatePointer();
  89206. }
  89207. else {
  89208. controller._activatePointer();
  89209. }
  89210. if (_this.displayGaze) {
  89211. controller._gazeTracker.isVisible = controller._activePointer;
  89212. }
  89213. }
  89214. });
  89215. }
  89216. controller.webVRController.onTriggerStateChangedObservable.add(function (stateObject) {
  89217. if (!controller._pointerDownOnMeshAsked) {
  89218. if (stateObject.value > _this._padSensibilityUp) {
  89219. controller._selectionPointerDown();
  89220. }
  89221. }
  89222. else if (stateObject.value < _this._padSensibilityDown) {
  89223. controller._selectionPointerUp();
  89224. }
  89225. });
  89226. }
  89227. };
  89228. VRExperienceHelper.prototype._checkTeleportWithRay = function (stateObject, gazer) {
  89229. // Dont teleport if another gaze already requested teleportation
  89230. if (this._teleportationRequestInitiated && !gazer._teleportationRequestInitiated) {
  89231. return;
  89232. }
  89233. if (!gazer._teleportationRequestInitiated) {
  89234. if (stateObject.y < -this._padSensibilityUp && gazer._dpadPressed) {
  89235. gazer._activatePointer();
  89236. gazer._teleportationRequestInitiated = true;
  89237. }
  89238. }
  89239. else {
  89240. // Listening to the proper controller values changes to confirm teleportation
  89241. if (Math.sqrt(stateObject.y * stateObject.y + stateObject.x * stateObject.x) < this._padSensibilityDown) {
  89242. if (this._teleportActive) {
  89243. this._teleportCamera(this._haloCenter);
  89244. }
  89245. gazer._teleportationRequestInitiated = false;
  89246. }
  89247. }
  89248. };
  89249. VRExperienceHelper.prototype._checkRotate = function (stateObject, gazer) {
  89250. // Only rotate when user is not currently selecting a teleportation location
  89251. if (gazer._teleportationRequestInitiated) {
  89252. return;
  89253. }
  89254. if (!gazer._rotationLeftAsked) {
  89255. if (stateObject.x < -this._padSensibilityUp && gazer._dpadPressed) {
  89256. gazer._rotationLeftAsked = true;
  89257. if (this._rotationAllowed) {
  89258. this._rotateCamera(false);
  89259. }
  89260. }
  89261. }
  89262. else {
  89263. if (stateObject.x > -this._padSensibilityDown) {
  89264. gazer._rotationLeftAsked = false;
  89265. }
  89266. }
  89267. if (!gazer._rotationRightAsked) {
  89268. if (stateObject.x > this._padSensibilityUp && gazer._dpadPressed) {
  89269. gazer._rotationRightAsked = true;
  89270. if (this._rotationAllowed) {
  89271. this._rotateCamera(true);
  89272. }
  89273. }
  89274. }
  89275. else {
  89276. if (stateObject.x < this._padSensibilityDown) {
  89277. gazer._rotationRightAsked = false;
  89278. }
  89279. }
  89280. };
  89281. VRExperienceHelper.prototype._checkTeleportBackwards = function (stateObject, gazer) {
  89282. // Only teleport backwards when user is not currently selecting a teleportation location
  89283. if (gazer._teleportationRequestInitiated) {
  89284. return;
  89285. }
  89286. // Teleport backwards
  89287. if (stateObject.y > this._padSensibilityUp && gazer._dpadPressed) {
  89288. if (!gazer._teleportationBackRequestInitiated) {
  89289. if (!this.currentVRCamera) {
  89290. return;
  89291. }
  89292. // Get rotation and position of the current camera
  89293. var rotation = BABYLON.Quaternion.FromRotationMatrix(this.currentVRCamera.getWorldMatrix().getRotationMatrix());
  89294. var position = this.currentVRCamera.position;
  89295. // If the camera has device position, use that instead
  89296. if (this.currentVRCamera.devicePosition && this.currentVRCamera.deviceRotationQuaternion) {
  89297. rotation = this.currentVRCamera.deviceRotationQuaternion;
  89298. position = this.currentVRCamera.devicePosition;
  89299. }
  89300. // Get matrix with only the y rotation of the device rotation
  89301. rotation.toEulerAnglesToRef(this._workingVector);
  89302. this._workingVector.z = 0;
  89303. this._workingVector.x = 0;
  89304. BABYLON.Quaternion.RotationYawPitchRollToRef(this._workingVector.y, this._workingVector.x, this._workingVector.z, this._workingQuaternion);
  89305. this._workingQuaternion.toRotationMatrix(this._workingMatrix);
  89306. // Rotate backwards ray by device rotation to cast at the ground behind the user
  89307. BABYLON.Vector3.TransformCoordinatesToRef(this._teleportBackwardsVector, this._workingMatrix, this._workingVector);
  89308. // Teleport if ray hit the ground and is not to far away eg. backwards off a cliff
  89309. var ray = new BABYLON.Ray(position, this._workingVector);
  89310. var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate);
  89311. if (hit && hit.pickedPoint && hit.pickedMesh && this._isTeleportationFloor(hit.pickedMesh) && hit.distance < 5) {
  89312. this._teleportCamera(hit.pickedPoint);
  89313. }
  89314. gazer._teleportationBackRequestInitiated = true;
  89315. }
  89316. }
  89317. else {
  89318. gazer._teleportationBackRequestInitiated = false;
  89319. }
  89320. };
  89321. VRExperienceHelper.prototype._enableTeleportationOnController = function (controller) {
  89322. var _this = this;
  89323. var controllerMesh = controller.webVRController.mesh;
  89324. if (controllerMesh) {
  89325. if (!controller._interactionsEnabled) {
  89326. this._enableInteractionOnController(controller);
  89327. }
  89328. controller._interactionsEnabled = true;
  89329. controller._teleportationEnabled = true;
  89330. if (controller.webVRController.controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  89331. controller._dpadPressed = false;
  89332. controller.webVRController.onPadStateChangedObservable.add(function (stateObject) {
  89333. controller._dpadPressed = stateObject.pressed;
  89334. if (!controller._dpadPressed) {
  89335. controller._rotationLeftAsked = false;
  89336. controller._rotationRightAsked = false;
  89337. controller._teleportationBackRequestInitiated = false;
  89338. }
  89339. });
  89340. }
  89341. controller.webVRController.onPadValuesChangedObservable.add(function (stateObject) {
  89342. if (_this.teleportationEnabled) {
  89343. _this._checkTeleportBackwards(stateObject, controller);
  89344. _this._checkTeleportWithRay(stateObject, controller);
  89345. }
  89346. _this._checkRotate(stateObject, controller);
  89347. });
  89348. }
  89349. };
  89350. VRExperienceHelper.prototype._createTeleportationCircles = function () {
  89351. this._teleportationTarget = BABYLON.Mesh.CreateGround("teleportationTarget", 2, 2, 2, this._scene);
  89352. this._teleportationTarget.isPickable = false;
  89353. var length = 512;
  89354. var dynamicTexture = new BABYLON.DynamicTexture("DynamicTexture", length, this._scene, true);
  89355. dynamicTexture.hasAlpha = true;
  89356. var context = dynamicTexture.getContext();
  89357. var centerX = length / 2;
  89358. var centerY = length / 2;
  89359. var radius = 200;
  89360. context.beginPath();
  89361. context.arc(centerX, centerY, radius, 0, 2 * Math.PI, false);
  89362. context.fillStyle = this._teleportationFillColor;
  89363. context.fill();
  89364. context.lineWidth = 10;
  89365. context.strokeStyle = this._teleportationBorderColor;
  89366. context.stroke();
  89367. context.closePath();
  89368. dynamicTexture.update();
  89369. var teleportationCircleMaterial = new BABYLON.StandardMaterial("TextPlaneMaterial", this._scene);
  89370. teleportationCircleMaterial.diffuseTexture = dynamicTexture;
  89371. this._teleportationTarget.material = teleportationCircleMaterial;
  89372. var torus = BABYLON.Mesh.CreateTorus("torusTeleportation", 0.75, 0.1, 25, this._scene, false);
  89373. torus.isPickable = false;
  89374. torus.parent = this._teleportationTarget;
  89375. var animationInnerCircle = new BABYLON.Animation("animationInnerCircle", "position.y", 30, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  89376. var keys = [];
  89377. keys.push({
  89378. frame: 0,
  89379. value: 0
  89380. });
  89381. keys.push({
  89382. frame: 30,
  89383. value: 0.4
  89384. });
  89385. keys.push({
  89386. frame: 60,
  89387. value: 0
  89388. });
  89389. animationInnerCircle.setKeys(keys);
  89390. var easingFunction = new BABYLON.SineEase();
  89391. easingFunction.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  89392. animationInnerCircle.setEasingFunction(easingFunction);
  89393. torus.animations = [];
  89394. torus.animations.push(animationInnerCircle);
  89395. this._scene.beginAnimation(torus, 0, 60, true);
  89396. this._hideTeleportationTarget();
  89397. };
  89398. VRExperienceHelper.prototype._displayTeleportationTarget = function () {
  89399. this._teleportActive = true;
  89400. if (this._teleportationInitialized) {
  89401. this._teleportationTarget.isVisible = true;
  89402. if (this._isDefaultTeleportationTarget) {
  89403. this._teleportationTarget.getChildren()[0].isVisible = true;
  89404. }
  89405. }
  89406. };
  89407. VRExperienceHelper.prototype._hideTeleportationTarget = function () {
  89408. this._teleportActive = false;
  89409. if (this._teleportationInitialized) {
  89410. this._teleportationTarget.isVisible = false;
  89411. if (this._isDefaultTeleportationTarget) {
  89412. this._teleportationTarget.getChildren()[0].isVisible = false;
  89413. }
  89414. }
  89415. };
  89416. VRExperienceHelper.prototype._rotateCamera = function (right) {
  89417. var _this = this;
  89418. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  89419. return;
  89420. }
  89421. if (right) {
  89422. this._rotationAngle++;
  89423. }
  89424. else {
  89425. this._rotationAngle--;
  89426. }
  89427. this.currentVRCamera.animations = [];
  89428. var target = BABYLON.Quaternion.FromRotationMatrix(BABYLON.Matrix.RotationY(Math.PI / 4 * this._rotationAngle));
  89429. var animationRotation = new BABYLON.Animation("animationRotation", "rotationQuaternion", 90, BABYLON.Animation.ANIMATIONTYPE_QUATERNION, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  89430. var animationRotationKeys = [];
  89431. animationRotationKeys.push({
  89432. frame: 0,
  89433. value: this.currentVRCamera.rotationQuaternion
  89434. });
  89435. animationRotationKeys.push({
  89436. frame: 6,
  89437. value: target
  89438. });
  89439. animationRotation.setKeys(animationRotationKeys);
  89440. animationRotation.setEasingFunction(this._circleEase);
  89441. this.currentVRCamera.animations.push(animationRotation);
  89442. this._postProcessMove.animations = [];
  89443. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  89444. var vignetteWeightKeys = [];
  89445. vignetteWeightKeys.push({
  89446. frame: 0,
  89447. value: 0
  89448. });
  89449. vignetteWeightKeys.push({
  89450. frame: 3,
  89451. value: 4
  89452. });
  89453. vignetteWeightKeys.push({
  89454. frame: 6,
  89455. value: 0
  89456. });
  89457. animationPP.setKeys(vignetteWeightKeys);
  89458. animationPP.setEasingFunction(this._circleEase);
  89459. this._postProcessMove.animations.push(animationPP);
  89460. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  89461. var vignetteStretchKeys = [];
  89462. vignetteStretchKeys.push({
  89463. frame: 0,
  89464. value: 0
  89465. });
  89466. vignetteStretchKeys.push({
  89467. frame: 3,
  89468. value: 10
  89469. });
  89470. vignetteStretchKeys.push({
  89471. frame: 6,
  89472. value: 0
  89473. });
  89474. animationPP2.setKeys(vignetteStretchKeys);
  89475. animationPP2.setEasingFunction(this._circleEase);
  89476. this._postProcessMove.animations.push(animationPP2);
  89477. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  89478. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  89479. this._postProcessMove.samples = 4;
  89480. this._webVRCamera.attachPostProcess(this._postProcessMove);
  89481. this._scene.beginAnimation(this._postProcessMove, 0, 6, false, 1, function () {
  89482. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  89483. });
  89484. this._scene.beginAnimation(this.currentVRCamera, 0, 6, false, 1);
  89485. };
  89486. VRExperienceHelper.prototype._moveTeleportationSelectorTo = function (hit, gazer, ray) {
  89487. if (hit.pickedPoint) {
  89488. if (gazer._teleportationRequestInitiated) {
  89489. this._displayTeleportationTarget();
  89490. this._haloCenter.copyFrom(hit.pickedPoint);
  89491. this._teleportationTarget.position.copyFrom(hit.pickedPoint);
  89492. }
  89493. var pickNormal = this._convertNormalToDirectionOfRay(hit.getNormal(true, false), ray);
  89494. if (pickNormal) {
  89495. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  89496. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  89497. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, this._teleportationTarget.rotation);
  89498. }
  89499. this._teleportationTarget.position.y += 0.1;
  89500. }
  89501. };
  89502. VRExperienceHelper.prototype._teleportCamera = function (location) {
  89503. var _this = this;
  89504. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  89505. return;
  89506. }
  89507. // Teleport the hmd to where the user is looking by moving the anchor to where they are looking minus the
  89508. // offset of the headset from the anchor.
  89509. if (this.webVRCamera.leftCamera) {
  89510. this._workingVector.copyFrom(this.webVRCamera.leftCamera.globalPosition);
  89511. this._workingVector.subtractInPlace(this.webVRCamera.position);
  89512. location.subtractToRef(this._workingVector, this._workingVector);
  89513. }
  89514. else {
  89515. this._workingVector.copyFrom(location);
  89516. }
  89517. // Add height to account for user's height offset
  89518. if (this.isInVRMode) {
  89519. this._workingVector.y += this.webVRCamera.deviceDistanceToRoomGround() * this._webVRCamera.deviceScaleFactor;
  89520. }
  89521. else {
  89522. this._workingVector.y += this._defaultHeight;
  89523. }
  89524. this.onBeforeCameraTeleport.notifyObservers(this._workingVector);
  89525. // Create animation from the camera's position to the new location
  89526. this.currentVRCamera.animations = [];
  89527. var animationCameraTeleportation = new BABYLON.Animation("animationCameraTeleportation", "position", 90, BABYLON.Animation.ANIMATIONTYPE_VECTOR3, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  89528. var animationCameraTeleportationKeys = [{
  89529. frame: 0,
  89530. value: this.currentVRCamera.position
  89531. },
  89532. {
  89533. frame: 11,
  89534. value: this._workingVector
  89535. }
  89536. ];
  89537. animationCameraTeleportation.setKeys(animationCameraTeleportationKeys);
  89538. animationCameraTeleportation.setEasingFunction(this._circleEase);
  89539. this.currentVRCamera.animations.push(animationCameraTeleportation);
  89540. this._postProcessMove.animations = [];
  89541. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  89542. var vignetteWeightKeys = [];
  89543. vignetteWeightKeys.push({
  89544. frame: 0,
  89545. value: 0
  89546. });
  89547. vignetteWeightKeys.push({
  89548. frame: 5,
  89549. value: 8
  89550. });
  89551. vignetteWeightKeys.push({
  89552. frame: 11,
  89553. value: 0
  89554. });
  89555. animationPP.setKeys(vignetteWeightKeys);
  89556. this._postProcessMove.animations.push(animationPP);
  89557. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  89558. var vignetteStretchKeys = [];
  89559. vignetteStretchKeys.push({
  89560. frame: 0,
  89561. value: 0
  89562. });
  89563. vignetteStretchKeys.push({
  89564. frame: 5,
  89565. value: 10
  89566. });
  89567. vignetteStretchKeys.push({
  89568. frame: 11,
  89569. value: 0
  89570. });
  89571. animationPP2.setKeys(vignetteStretchKeys);
  89572. this._postProcessMove.animations.push(animationPP2);
  89573. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  89574. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  89575. this._webVRCamera.attachPostProcess(this._postProcessMove);
  89576. this._scene.beginAnimation(this._postProcessMove, 0, 11, false, 1, function () {
  89577. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  89578. });
  89579. this._scene.beginAnimation(this.currentVRCamera, 0, 11, false, 1, function () {
  89580. _this.onAfterCameraTeleport.notifyObservers(_this._workingVector);
  89581. });
  89582. this._hideTeleportationTarget();
  89583. };
  89584. VRExperienceHelper.prototype._convertNormalToDirectionOfRay = function (normal, ray) {
  89585. if (normal) {
  89586. var angle = Math.acos(BABYLON.Vector3.Dot(normal, ray.direction));
  89587. if (angle < Math.PI / 2) {
  89588. normal.scaleInPlace(-1);
  89589. }
  89590. }
  89591. return normal;
  89592. };
  89593. VRExperienceHelper.prototype._castRayAndSelectObject = function (gazer) {
  89594. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  89595. return;
  89596. }
  89597. var ray = gazer._getForwardRay(this._rayLength);
  89598. var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate);
  89599. if (hit) {
  89600. // Populate the contrllers mesh that can be used for drag/drop
  89601. if (gazer._laserPointer) {
  89602. hit.originMesh = gazer._laserPointer.parent;
  89603. }
  89604. this._scene.simulatePointerMove(hit, { pointerId: gazer._id });
  89605. }
  89606. gazer._currentHit = hit;
  89607. // Moving the gazeTracker on the mesh face targetted
  89608. if (hit && hit.pickedPoint) {
  89609. if (this._displayGaze) {
  89610. var multiplier = 1;
  89611. gazer._gazeTracker.isVisible = true;
  89612. if (gazer._isActionableMesh) {
  89613. multiplier = 3;
  89614. }
  89615. gazer._gazeTracker.scaling.x = hit.distance * multiplier;
  89616. gazer._gazeTracker.scaling.y = hit.distance * multiplier;
  89617. gazer._gazeTracker.scaling.z = hit.distance * multiplier;
  89618. var pickNormal = this._convertNormalToDirectionOfRay(hit.getNormal(), ray);
  89619. // To avoid z-fighting
  89620. var deltaFighting = 0.002;
  89621. if (pickNormal) {
  89622. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  89623. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  89624. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, gazer._gazeTracker.rotation);
  89625. }
  89626. gazer._gazeTracker.position.copyFrom(hit.pickedPoint);
  89627. if (gazer._gazeTracker.position.x < 0) {
  89628. gazer._gazeTracker.position.x += deltaFighting;
  89629. }
  89630. else {
  89631. gazer._gazeTracker.position.x -= deltaFighting;
  89632. }
  89633. if (gazer._gazeTracker.position.y < 0) {
  89634. gazer._gazeTracker.position.y += deltaFighting;
  89635. }
  89636. else {
  89637. gazer._gazeTracker.position.y -= deltaFighting;
  89638. }
  89639. if (gazer._gazeTracker.position.z < 0) {
  89640. gazer._gazeTracker.position.z += deltaFighting;
  89641. }
  89642. else {
  89643. gazer._gazeTracker.position.z -= deltaFighting;
  89644. }
  89645. }
  89646. // Changing the size of the laser pointer based on the distance from the targetted point
  89647. gazer._updatePointerDistance(hit.distance);
  89648. }
  89649. else {
  89650. gazer._updatePointerDistance();
  89651. gazer._gazeTracker.isVisible = false;
  89652. }
  89653. if (hit && hit.pickedMesh) {
  89654. // The object selected is the floor, we're in a teleportation scenario
  89655. if (this._teleportationInitialized && this._isTeleportationFloor(hit.pickedMesh) && hit.pickedPoint) {
  89656. // Moving the teleportation area to this targetted point
  89657. //Raise onSelectedMeshUnselected observable if ray collided floor mesh/meshes and a non floor mesh was previously selected
  89658. if (gazer._currentMeshSelected && !this._isTeleportationFloor(gazer._currentMeshSelected)) {
  89659. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  89660. }
  89661. gazer._currentMeshSelected = null;
  89662. if (gazer._teleportationRequestInitiated) {
  89663. this._moveTeleportationSelectorTo(hit, gazer, ray);
  89664. }
  89665. return;
  89666. }
  89667. // If not, we're in a selection scenario
  89668. //this._teleportationAllowed = false;
  89669. if (hit.pickedMesh !== gazer._currentMeshSelected) {
  89670. if (this.meshSelectionPredicate(hit.pickedMesh)) {
  89671. this.onNewMeshPicked.notifyObservers(hit);
  89672. gazer._currentMeshSelected = hit.pickedMesh;
  89673. if (hit.pickedMesh.isPickable && hit.pickedMesh.actionManager) {
  89674. this.changeGazeColor(new BABYLON.Color3(0, 0, 1));
  89675. this.changeLaserColor(new BABYLON.Color3(0.2, 0.2, 1));
  89676. gazer._isActionableMesh = true;
  89677. }
  89678. else {
  89679. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  89680. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  89681. gazer._isActionableMesh = false;
  89682. }
  89683. try {
  89684. this.onNewMeshSelected.notifyObservers(hit.pickedMesh);
  89685. }
  89686. catch (err) {
  89687. BABYLON.Tools.Warn("Error in your custom logic onNewMeshSelected: " + err);
  89688. }
  89689. }
  89690. else {
  89691. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  89692. gazer._currentMeshSelected = null;
  89693. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  89694. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  89695. }
  89696. }
  89697. }
  89698. else {
  89699. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  89700. gazer._currentMeshSelected = null;
  89701. //this._teleportationAllowed = false;
  89702. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  89703. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  89704. }
  89705. };
  89706. VRExperienceHelper.prototype._notifySelectedMeshUnselected = function (mesh) {
  89707. if (mesh) {
  89708. this.onSelectedMeshUnselected.notifyObservers(mesh);
  89709. }
  89710. };
  89711. /**
  89712. * Sets the color of the laser ray from the vr controllers.
  89713. * @param color new color for the ray.
  89714. */
  89715. VRExperienceHelper.prototype.changeLaserColor = function (color) {
  89716. if (this.leftController) {
  89717. this.leftController._setLaserPointerColor(color);
  89718. }
  89719. if (this.rightController) {
  89720. this.rightController._setLaserPointerColor(color);
  89721. }
  89722. };
  89723. /**
  89724. * Sets the color of the ray from the vr headsets gaze.
  89725. * @param color new color for the ray.
  89726. */
  89727. VRExperienceHelper.prototype.changeGazeColor = function (color) {
  89728. if (!this._cameraGazer._gazeTracker.material) {
  89729. return;
  89730. }
  89731. this._cameraGazer._gazeTracker.material.emissiveColor = color;
  89732. if (this.leftController) {
  89733. this.leftController._gazeTracker.material.emissiveColor = color;
  89734. }
  89735. if (this.rightController) {
  89736. this.rightController._gazeTracker.material.emissiveColor = color;
  89737. }
  89738. };
  89739. /**
  89740. * Exits VR and disposes of the vr experience helper
  89741. */
  89742. VRExperienceHelper.prototype.dispose = function () {
  89743. if (this.isInVRMode) {
  89744. this.exitVR();
  89745. }
  89746. if (this._postProcessMove) {
  89747. this._postProcessMove.dispose();
  89748. }
  89749. if (this._webVRCamera) {
  89750. this._webVRCamera.dispose();
  89751. }
  89752. if (this._vrDeviceOrientationCamera) {
  89753. this._vrDeviceOrientationCamera.dispose();
  89754. }
  89755. if (!this._useCustomVRButton && this._btnVR.parentNode) {
  89756. document.body.removeChild(this._btnVR);
  89757. }
  89758. if (this._deviceOrientationCamera && (this._scene.activeCamera != this._deviceOrientationCamera)) {
  89759. this._deviceOrientationCamera.dispose();
  89760. }
  89761. if (this._cameraGazer) {
  89762. this._cameraGazer.dispose();
  89763. }
  89764. if (this.leftController) {
  89765. this.leftController.dispose();
  89766. }
  89767. if (this.rightController) {
  89768. this.rightController.dispose();
  89769. }
  89770. if (this._teleportationTarget) {
  89771. this._teleportationTarget.dispose();
  89772. }
  89773. this._floorMeshesCollection = [];
  89774. document.removeEventListener("keydown", this._onKeyDown);
  89775. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  89776. window.removeEventListener("resize", this._onResize);
  89777. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  89778. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  89779. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  89780. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  89781. this._scene.getEngine().onVRDisplayChangedObservable.removeCallback(this._onVRDisplayChanged);
  89782. this._scene.getEngine().onVRRequestPresentStart.removeCallback(this._onVRRequestPresentStart);
  89783. this._scene.getEngine().onVRRequestPresentComplete.removeCallback(this._onVRRequestPresentComplete);
  89784. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  89785. this._scene.gamepadManager.onGamepadConnectedObservable.removeCallback(this._onNewGamepadConnected);
  89786. this._scene.gamepadManager.onGamepadDisconnectedObservable.removeCallback(this._onNewGamepadDisconnected);
  89787. this._scene.unregisterBeforeRender(this.beforeRender);
  89788. };
  89789. /**
  89790. * Gets the name of the VRExperienceHelper class
  89791. * @returns "VRExperienceHelper"
  89792. */
  89793. VRExperienceHelper.prototype.getClassName = function () {
  89794. return "VRExperienceHelper";
  89795. };
  89796. return VRExperienceHelper;
  89797. }());
  89798. BABYLON.VRExperienceHelper = VRExperienceHelper;
  89799. })(BABYLON || (BABYLON = {}));
  89800. //# sourceMappingURL=babylon.vrExperienceHelper.js.map
  89801. // Mainly based on these 2 articles :
  89802. // 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
  89803. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  89804. var BABYLON;
  89805. (function (BABYLON) {
  89806. /**
  89807. * Defines the potential axis of a Joystick
  89808. */
  89809. var JoystickAxis;
  89810. (function (JoystickAxis) {
  89811. /** X axis */
  89812. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  89813. /** Y axis */
  89814. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  89815. /** Z axis */
  89816. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  89817. })(JoystickAxis = BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  89818. /**
  89819. * Class used to define virtual joystick (used in touch mode)
  89820. */
  89821. var VirtualJoystick = /** @class */ (function () {
  89822. /**
  89823. * Creates a new virtual joystick
  89824. * @param leftJoystick defines that the joystick is for left hand (false by default)
  89825. */
  89826. function VirtualJoystick(leftJoystick) {
  89827. var _this = this;
  89828. if (leftJoystick) {
  89829. this._leftJoystick = true;
  89830. }
  89831. else {
  89832. this._leftJoystick = false;
  89833. }
  89834. VirtualJoystick._globalJoystickIndex++;
  89835. // By default left & right arrow keys are moving the X
  89836. // and up & down keys are moving the Y
  89837. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  89838. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  89839. this.reverseLeftRight = false;
  89840. this.reverseUpDown = false;
  89841. // collections of pointers
  89842. this._touches = new BABYLON.StringDictionary();
  89843. this.deltaPosition = BABYLON.Vector3.Zero();
  89844. this._joystickSensibility = 25;
  89845. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  89846. this._onResize = function (evt) {
  89847. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  89848. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  89849. if (VirtualJoystick.vjCanvas) {
  89850. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  89851. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  89852. }
  89853. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  89854. };
  89855. // injecting a canvas element on top of the canvas 3D game
  89856. if (!VirtualJoystick.vjCanvas) {
  89857. window.addEventListener("resize", this._onResize, false);
  89858. VirtualJoystick.vjCanvas = document.createElement("canvas");
  89859. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  89860. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  89861. VirtualJoystick.vjCanvas.width = window.innerWidth;
  89862. VirtualJoystick.vjCanvas.height = window.innerHeight;
  89863. VirtualJoystick.vjCanvas.style.width = "100%";
  89864. VirtualJoystick.vjCanvas.style.height = "100%";
  89865. VirtualJoystick.vjCanvas.style.position = "absolute";
  89866. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  89867. VirtualJoystick.vjCanvas.style.top = "0px";
  89868. VirtualJoystick.vjCanvas.style.left = "0px";
  89869. VirtualJoystick.vjCanvas.style.zIndex = "5";
  89870. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  89871. // Support for jQuery PEP polyfill
  89872. VirtualJoystick.vjCanvas.setAttribute("touch-action", "none");
  89873. var context = VirtualJoystick.vjCanvas.getContext('2d');
  89874. if (!context) {
  89875. throw new Error("Unable to create canvas for virtual joystick");
  89876. }
  89877. VirtualJoystick.vjCanvasContext = context;
  89878. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  89879. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  89880. document.body.appendChild(VirtualJoystick.vjCanvas);
  89881. }
  89882. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  89883. this.pressed = false;
  89884. // default joystick color
  89885. this._joystickColor = "cyan";
  89886. this._joystickPointerID = -1;
  89887. // current joystick position
  89888. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  89889. this._joystickPreviousPointerPos = new BABYLON.Vector2(0, 0);
  89890. // origin joystick position
  89891. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  89892. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  89893. this._onPointerDownHandlerRef = function (evt) {
  89894. _this._onPointerDown(evt);
  89895. };
  89896. this._onPointerMoveHandlerRef = function (evt) {
  89897. _this._onPointerMove(evt);
  89898. };
  89899. this._onPointerUpHandlerRef = function (evt) {
  89900. _this._onPointerUp(evt);
  89901. };
  89902. VirtualJoystick.vjCanvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false);
  89903. VirtualJoystick.vjCanvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);
  89904. VirtualJoystick.vjCanvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);
  89905. VirtualJoystick.vjCanvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);
  89906. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  89907. evt.preventDefault(); // Disables system menu
  89908. }, false);
  89909. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  89910. }
  89911. /**
  89912. * Defines joystick sensibility (ie. the ratio beteen a physical move and virtual joystick position change)
  89913. * @param newJoystickSensibility defines the new sensibility
  89914. */
  89915. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  89916. this._joystickSensibility = newJoystickSensibility;
  89917. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  89918. };
  89919. VirtualJoystick.prototype._onPointerDown = function (e) {
  89920. var positionOnScreenCondition;
  89921. e.preventDefault();
  89922. if (this._leftJoystick === true) {
  89923. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  89924. }
  89925. else {
  89926. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  89927. }
  89928. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  89929. // First contact will be dedicated to the virtual joystick
  89930. this._joystickPointerID = e.pointerId;
  89931. this._joystickPointerStartPos.x = e.clientX;
  89932. this._joystickPointerStartPos.y = e.clientY;
  89933. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  89934. this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();
  89935. this._deltaJoystickVector.x = 0;
  89936. this._deltaJoystickVector.y = 0;
  89937. this.pressed = true;
  89938. this._touches.add(e.pointerId.toString(), e);
  89939. }
  89940. else {
  89941. // You can only trigger the action buttons with a joystick declared
  89942. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  89943. this._action();
  89944. this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });
  89945. }
  89946. }
  89947. };
  89948. VirtualJoystick.prototype._onPointerMove = function (e) {
  89949. // If the current pointer is the one associated to the joystick (first touch contact)
  89950. if (this._joystickPointerID == e.pointerId) {
  89951. this._joystickPointerPos.x = e.clientX;
  89952. this._joystickPointerPos.y = e.clientY;
  89953. this._deltaJoystickVector = this._joystickPointerPos.clone();
  89954. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  89955. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  89956. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  89957. switch (this._axisTargetedByLeftAndRight) {
  89958. case JoystickAxis.X:
  89959. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  89960. break;
  89961. case JoystickAxis.Y:
  89962. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  89963. break;
  89964. case JoystickAxis.Z:
  89965. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  89966. break;
  89967. }
  89968. var directionUpDown = this.reverseUpDown ? 1 : -1;
  89969. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  89970. switch (this._axisTargetedByUpAndDown) {
  89971. case JoystickAxis.X:
  89972. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  89973. break;
  89974. case JoystickAxis.Y:
  89975. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  89976. break;
  89977. case JoystickAxis.Z:
  89978. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  89979. break;
  89980. }
  89981. }
  89982. else {
  89983. var data = this._touches.get(e.pointerId.toString());
  89984. if (data) {
  89985. data.x = e.clientX;
  89986. data.y = e.clientY;
  89987. }
  89988. }
  89989. };
  89990. VirtualJoystick.prototype._onPointerUp = function (e) {
  89991. if (this._joystickPointerID == e.pointerId) {
  89992. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 64, this._joystickPointerStartPos.y - 64, 128, 128);
  89993. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 42, this._joystickPreviousPointerPos.y - 42, 84, 84);
  89994. this._joystickPointerID = -1;
  89995. this.pressed = false;
  89996. }
  89997. else {
  89998. var touch = this._touches.get(e.pointerId.toString());
  89999. if (touch) {
  90000. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  90001. }
  90002. }
  90003. this._deltaJoystickVector.x = 0;
  90004. this._deltaJoystickVector.y = 0;
  90005. this._touches.remove(e.pointerId.toString());
  90006. };
  90007. /**
  90008. * Change the color of the virtual joystick
  90009. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  90010. */
  90011. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  90012. this._joystickColor = newColor;
  90013. };
  90014. /**
  90015. * Defines a callback to call when the joystick is touched
  90016. * @param action defines the callback
  90017. */
  90018. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  90019. this._action = action;
  90020. };
  90021. /**
  90022. * Defines which axis you'd like to control for left & right
  90023. * @param axis defines the axis to use
  90024. */
  90025. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  90026. switch (axis) {
  90027. case JoystickAxis.X:
  90028. case JoystickAxis.Y:
  90029. case JoystickAxis.Z:
  90030. this._axisTargetedByLeftAndRight = axis;
  90031. break;
  90032. default:
  90033. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  90034. break;
  90035. }
  90036. };
  90037. /**
  90038. * Defines which axis you'd like to control for up & down
  90039. * @param axis defines the axis to use
  90040. */
  90041. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  90042. switch (axis) {
  90043. case JoystickAxis.X:
  90044. case JoystickAxis.Y:
  90045. case JoystickAxis.Z:
  90046. this._axisTargetedByUpAndDown = axis;
  90047. break;
  90048. default:
  90049. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  90050. break;
  90051. }
  90052. };
  90053. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  90054. var _this = this;
  90055. if (this.pressed) {
  90056. this._touches.forEach(function (key, touch) {
  90057. if (touch.pointerId === _this._joystickPointerID) {
  90058. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPointerStartPos.x - 64, _this._joystickPointerStartPos.y - 64, 128, 128);
  90059. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPreviousPointerPos.x - 42, _this._joystickPreviousPointerPos.y - 42, 84, 84);
  90060. VirtualJoystick.vjCanvasContext.beginPath();
  90061. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  90062. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  90063. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  90064. VirtualJoystick.vjCanvasContext.stroke();
  90065. VirtualJoystick.vjCanvasContext.closePath();
  90066. VirtualJoystick.vjCanvasContext.beginPath();
  90067. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  90068. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  90069. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  90070. VirtualJoystick.vjCanvasContext.stroke();
  90071. VirtualJoystick.vjCanvasContext.closePath();
  90072. VirtualJoystick.vjCanvasContext.beginPath();
  90073. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  90074. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  90075. VirtualJoystick.vjCanvasContext.stroke();
  90076. VirtualJoystick.vjCanvasContext.closePath();
  90077. _this._joystickPreviousPointerPos = _this._joystickPointerPos.clone();
  90078. }
  90079. else {
  90080. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  90081. VirtualJoystick.vjCanvasContext.beginPath();
  90082. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  90083. VirtualJoystick.vjCanvasContext.beginPath();
  90084. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  90085. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  90086. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  90087. VirtualJoystick.vjCanvasContext.stroke();
  90088. VirtualJoystick.vjCanvasContext.closePath();
  90089. touch.prevX = touch.x;
  90090. touch.prevY = touch.y;
  90091. }
  90092. ;
  90093. });
  90094. }
  90095. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  90096. };
  90097. /**
  90098. * Release internal HTML canvas
  90099. */
  90100. VirtualJoystick.prototype.releaseCanvas = function () {
  90101. if (VirtualJoystick.vjCanvas) {
  90102. VirtualJoystick.vjCanvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef);
  90103. VirtualJoystick.vjCanvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef);
  90104. VirtualJoystick.vjCanvas.removeEventListener('pointerup', this._onPointerUpHandlerRef);
  90105. VirtualJoystick.vjCanvas.removeEventListener('pointerout', this._onPointerUpHandlerRef);
  90106. window.removeEventListener("resize", this._onResize);
  90107. document.body.removeChild(VirtualJoystick.vjCanvas);
  90108. VirtualJoystick.vjCanvas = null;
  90109. }
  90110. };
  90111. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  90112. VirtualJoystick._globalJoystickIndex = 0;
  90113. return VirtualJoystick;
  90114. }());
  90115. BABYLON.VirtualJoystick = VirtualJoystick;
  90116. })(BABYLON || (BABYLON = {}));
  90117. //# sourceMappingURL=babylon.virtualJoystick.js.map
  90118. var BABYLON;
  90119. (function (BABYLON) {
  90120. // We're mainly based on the logic defined into the FreeCamera code
  90121. var VirtualJoysticksCamera = /** @class */ (function (_super) {
  90122. __extends(VirtualJoysticksCamera, _super);
  90123. function VirtualJoysticksCamera(name, position, scene) {
  90124. var _this = _super.call(this, name, position, scene) || this;
  90125. _this.inputs.addVirtualJoystick();
  90126. return _this;
  90127. }
  90128. VirtualJoysticksCamera.prototype.getClassName = function () {
  90129. return "VirtualJoysticksCamera";
  90130. };
  90131. return VirtualJoysticksCamera;
  90132. }(BABYLON.FreeCamera));
  90133. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  90134. })(BABYLON || (BABYLON = {}));
  90135. //# sourceMappingURL=babylon.virtualJoysticksCamera.js.map
  90136. var BABYLON;
  90137. (function (BABYLON) {
  90138. var FreeCameraVirtualJoystickInput = /** @class */ (function () {
  90139. function FreeCameraVirtualJoystickInput() {
  90140. }
  90141. FreeCameraVirtualJoystickInput.prototype.getLeftJoystick = function () {
  90142. return this._leftjoystick;
  90143. };
  90144. FreeCameraVirtualJoystickInput.prototype.getRightJoystick = function () {
  90145. return this._rightjoystick;
  90146. };
  90147. FreeCameraVirtualJoystickInput.prototype.checkInputs = function () {
  90148. if (this._leftjoystick) {
  90149. var camera = this.camera;
  90150. var speed = camera._computeLocalCameraSpeed() * 50;
  90151. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
  90152. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
  90153. camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
  90154. camera.cameraRotation = camera.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  90155. if (!this._leftjoystick.pressed) {
  90156. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  90157. }
  90158. if (!this._rightjoystick.pressed) {
  90159. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  90160. }
  90161. }
  90162. };
  90163. FreeCameraVirtualJoystickInput.prototype.attachControl = function (element, noPreventDefault) {
  90164. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  90165. this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
  90166. this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
  90167. this._leftjoystick.setJoystickSensibility(0.15);
  90168. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  90169. this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
  90170. this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
  90171. this._rightjoystick.reverseUpDown = true;
  90172. this._rightjoystick.setJoystickSensibility(0.05);
  90173. this._rightjoystick.setJoystickColor("yellow");
  90174. };
  90175. FreeCameraVirtualJoystickInput.prototype.detachControl = function (element) {
  90176. this._leftjoystick.releaseCanvas();
  90177. this._rightjoystick.releaseCanvas();
  90178. };
  90179. FreeCameraVirtualJoystickInput.prototype.getClassName = function () {
  90180. return "FreeCameraVirtualJoystickInput";
  90181. };
  90182. FreeCameraVirtualJoystickInput.prototype.getSimpleName = function () {
  90183. return "virtualJoystick";
  90184. };
  90185. return FreeCameraVirtualJoystickInput;
  90186. }());
  90187. BABYLON.FreeCameraVirtualJoystickInput = FreeCameraVirtualJoystickInput;
  90188. BABYLON.CameraInputTypes["FreeCameraVirtualJoystickInput"] = FreeCameraVirtualJoystickInput;
  90189. })(BABYLON || (BABYLON = {}));
  90190. //# sourceMappingURL=babylon.freeCameraVirtualJoystickInput.js.map
  90191. var BABYLON;
  90192. (function (BABYLON) {
  90193. var SimplificationSettings = /** @class */ (function () {
  90194. function SimplificationSettings(quality, distance, optimizeMesh) {
  90195. this.quality = quality;
  90196. this.distance = distance;
  90197. this.optimizeMesh = optimizeMesh;
  90198. }
  90199. return SimplificationSettings;
  90200. }());
  90201. BABYLON.SimplificationSettings = SimplificationSettings;
  90202. var SimplificationQueue = /** @class */ (function () {
  90203. function SimplificationQueue() {
  90204. this.running = false;
  90205. this._simplificationArray = [];
  90206. }
  90207. SimplificationQueue.prototype.addTask = function (task) {
  90208. this._simplificationArray.push(task);
  90209. };
  90210. SimplificationQueue.prototype.executeNext = function () {
  90211. var task = this._simplificationArray.pop();
  90212. if (task) {
  90213. this.running = true;
  90214. this.runSimplification(task);
  90215. }
  90216. else {
  90217. this.running = false;
  90218. }
  90219. };
  90220. SimplificationQueue.prototype.runSimplification = function (task) {
  90221. var _this = this;
  90222. if (task.parallelProcessing) {
  90223. //parallel simplifier
  90224. task.settings.forEach(function (setting) {
  90225. var simplifier = _this.getSimplifier(task);
  90226. simplifier.simplify(setting, function (newMesh) {
  90227. task.mesh.addLODLevel(setting.distance, newMesh);
  90228. newMesh.isVisible = true;
  90229. //check if it is the last
  90230. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  90231. //all done, run the success callback.
  90232. task.successCallback();
  90233. }
  90234. _this.executeNext();
  90235. });
  90236. });
  90237. }
  90238. else {
  90239. //single simplifier.
  90240. var simplifier = this.getSimplifier(task);
  90241. var runDecimation = function (setting, callback) {
  90242. simplifier.simplify(setting, function (newMesh) {
  90243. task.mesh.addLODLevel(setting.distance, newMesh);
  90244. newMesh.isVisible = true;
  90245. //run the next quality level
  90246. callback();
  90247. });
  90248. };
  90249. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  90250. runDecimation(task.settings[loop.index], function () {
  90251. loop.executeNext();
  90252. });
  90253. }, function () {
  90254. //execution ended, run the success callback.
  90255. if (task.successCallback) {
  90256. task.successCallback();
  90257. }
  90258. _this.executeNext();
  90259. });
  90260. }
  90261. };
  90262. SimplificationQueue.prototype.getSimplifier = function (task) {
  90263. switch (task.simplificationType) {
  90264. case SimplificationType.QUADRATIC:
  90265. default:
  90266. return new QuadraticErrorSimplification(task.mesh);
  90267. }
  90268. };
  90269. return SimplificationQueue;
  90270. }());
  90271. BABYLON.SimplificationQueue = SimplificationQueue;
  90272. /**
  90273. * The implemented types of simplification
  90274. * At the moment only Quadratic Error Decimation is implemented
  90275. */
  90276. var SimplificationType;
  90277. (function (SimplificationType) {
  90278. /** Quadratic error decimation */
  90279. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  90280. })(SimplificationType = BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  90281. var DecimationTriangle = /** @class */ (function () {
  90282. function DecimationTriangle(vertices) {
  90283. this.vertices = vertices;
  90284. this.error = new Array(4);
  90285. this.deleted = false;
  90286. this.isDirty = false;
  90287. this.deletePending = false;
  90288. this.borderFactor = 0;
  90289. }
  90290. return DecimationTriangle;
  90291. }());
  90292. BABYLON.DecimationTriangle = DecimationTriangle;
  90293. var DecimationVertex = /** @class */ (function () {
  90294. function DecimationVertex(position, id) {
  90295. this.position = position;
  90296. this.id = id;
  90297. this.isBorder = true;
  90298. this.q = new QuadraticMatrix();
  90299. this.triangleCount = 0;
  90300. this.triangleStart = 0;
  90301. this.originalOffsets = [];
  90302. }
  90303. DecimationVertex.prototype.updatePosition = function (newPosition) {
  90304. this.position.copyFrom(newPosition);
  90305. };
  90306. return DecimationVertex;
  90307. }());
  90308. BABYLON.DecimationVertex = DecimationVertex;
  90309. var QuadraticMatrix = /** @class */ (function () {
  90310. function QuadraticMatrix(data) {
  90311. this.data = new Array(10);
  90312. for (var i = 0; i < 10; ++i) {
  90313. if (data && data[i]) {
  90314. this.data[i] = data[i];
  90315. }
  90316. else {
  90317. this.data[i] = 0;
  90318. }
  90319. }
  90320. }
  90321. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  90322. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  90323. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  90324. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  90325. return det;
  90326. };
  90327. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  90328. for (var i = 0; i < 10; ++i) {
  90329. this.data[i] += matrix.data[i];
  90330. }
  90331. };
  90332. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  90333. for (var i = 0; i < 10; ++i) {
  90334. this.data[i] += data[i];
  90335. }
  90336. };
  90337. QuadraticMatrix.prototype.add = function (matrix) {
  90338. var m = new QuadraticMatrix();
  90339. for (var i = 0; i < 10; ++i) {
  90340. m.data[i] = this.data[i] + matrix.data[i];
  90341. }
  90342. return m;
  90343. };
  90344. QuadraticMatrix.FromData = function (a, b, c, d) {
  90345. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  90346. };
  90347. //returning an array to avoid garbage collection
  90348. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  90349. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  90350. };
  90351. return QuadraticMatrix;
  90352. }());
  90353. BABYLON.QuadraticMatrix = QuadraticMatrix;
  90354. var Reference = /** @class */ (function () {
  90355. function Reference(vertexId, triangleId) {
  90356. this.vertexId = vertexId;
  90357. this.triangleId = triangleId;
  90358. }
  90359. return Reference;
  90360. }());
  90361. BABYLON.Reference = Reference;
  90362. /**
  90363. * An implementation of the Quadratic Error simplification algorithm.
  90364. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  90365. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  90366. * @author RaananW
  90367. */
  90368. var QuadraticErrorSimplification = /** @class */ (function () {
  90369. function QuadraticErrorSimplification(_mesh) {
  90370. this._mesh = _mesh;
  90371. this.syncIterations = 5000;
  90372. this.aggressiveness = 7;
  90373. this.decimationIterations = 100;
  90374. this.boundingBoxEpsilon = BABYLON.Epsilon;
  90375. }
  90376. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  90377. var _this = this;
  90378. this.initDecimatedMesh();
  90379. //iterating through the submeshes array, one after the other.
  90380. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  90381. _this.initWithMesh(loop.index, function () {
  90382. _this.runDecimation(settings, loop.index, function () {
  90383. loop.executeNext();
  90384. });
  90385. }, settings.optimizeMesh);
  90386. }, function () {
  90387. setTimeout(function () {
  90388. successCallback(_this._reconstructedMesh);
  90389. }, 0);
  90390. });
  90391. };
  90392. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  90393. var _this = this;
  90394. var targetCount = ~~(this.triangles.length * settings.quality);
  90395. var deletedTriangles = 0;
  90396. var triangleCount = this.triangles.length;
  90397. var iterationFunction = function (iteration, callback) {
  90398. setTimeout(function () {
  90399. if (iteration % 5 === 0) {
  90400. _this.updateMesh(iteration === 0);
  90401. }
  90402. for (var i = 0; i < _this.triangles.length; ++i) {
  90403. _this.triangles[i].isDirty = false;
  90404. }
  90405. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  90406. var trianglesIterator = function (i) {
  90407. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  90408. var t = _this.triangles[tIdx];
  90409. if (!t)
  90410. return;
  90411. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  90412. return;
  90413. }
  90414. for (var j = 0; j < 3; ++j) {
  90415. if (t.error[j] < threshold) {
  90416. var deleted0 = [];
  90417. var deleted1 = [];
  90418. var v0 = t.vertices[j];
  90419. var v1 = t.vertices[(j + 1) % 3];
  90420. if (v0.isBorder || v1.isBorder)
  90421. continue;
  90422. var p = BABYLON.Vector3.Zero();
  90423. var n = BABYLON.Vector3.Zero();
  90424. var uv = BABYLON.Vector2.Zero();
  90425. var color = new BABYLON.Color4(0, 0, 0, 1);
  90426. _this.calculateError(v0, v1, p, n, uv, color);
  90427. var delTr = new Array();
  90428. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  90429. continue;
  90430. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  90431. continue;
  90432. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  90433. continue;
  90434. var uniqueArray = new Array();
  90435. delTr.forEach(function (deletedT) {
  90436. if (uniqueArray.indexOf(deletedT) === -1) {
  90437. deletedT.deletePending = true;
  90438. uniqueArray.push(deletedT);
  90439. }
  90440. });
  90441. if (uniqueArray.length % 2 !== 0) {
  90442. continue;
  90443. }
  90444. v0.q = v1.q.add(v0.q);
  90445. v0.updatePosition(p);
  90446. var tStart = _this.references.length;
  90447. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  90448. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  90449. var tCount = _this.references.length - tStart;
  90450. if (tCount <= v0.triangleCount) {
  90451. if (tCount) {
  90452. for (var c = 0; c < tCount; c++) {
  90453. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  90454. }
  90455. }
  90456. }
  90457. else {
  90458. v0.triangleStart = tStart;
  90459. }
  90460. v0.triangleCount = tCount;
  90461. break;
  90462. }
  90463. }
  90464. };
  90465. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
  90466. }, 0);
  90467. };
  90468. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  90469. if (triangleCount - deletedTriangles <= targetCount)
  90470. loop.breakLoop();
  90471. else {
  90472. iterationFunction(loop.index, function () {
  90473. loop.executeNext();
  90474. });
  90475. }
  90476. }, function () {
  90477. setTimeout(function () {
  90478. //reconstruct this part of the mesh
  90479. _this.reconstructMesh(submeshIndex);
  90480. successCallback();
  90481. }, 0);
  90482. });
  90483. };
  90484. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  90485. var _this = this;
  90486. this.vertices = [];
  90487. this.triangles = [];
  90488. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  90489. var indices = this._mesh.getIndices();
  90490. var submesh = this._mesh.subMeshes[submeshIndex];
  90491. var findInVertices = function (positionToSearch) {
  90492. if (optimizeMesh) {
  90493. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  90494. if (_this.vertices[ii].position.equals(positionToSearch)) {
  90495. return _this.vertices[ii];
  90496. }
  90497. }
  90498. }
  90499. return null;
  90500. };
  90501. var vertexReferences = [];
  90502. var vertexInit = function (i) {
  90503. if (!positionData) {
  90504. return;
  90505. }
  90506. var offset = i + submesh.verticesStart;
  90507. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  90508. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  90509. vertex.originalOffsets.push(offset);
  90510. if (vertex.id === _this.vertices.length) {
  90511. _this.vertices.push(vertex);
  90512. }
  90513. vertexReferences.push(vertex.id);
  90514. };
  90515. //var totalVertices = mesh.getTotalVertices();
  90516. var totalVertices = submesh.verticesCount;
  90517. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  90518. var indicesInit = function (i) {
  90519. if (!indices) {
  90520. return;
  90521. }
  90522. var offset = (submesh.indexStart / 3) + i;
  90523. var pos = (offset * 3);
  90524. var i0 = indices[pos + 0];
  90525. var i1 = indices[pos + 1];
  90526. var i2 = indices[pos + 2];
  90527. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  90528. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  90529. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  90530. var triangle = new DecimationTriangle([v0, v1, v2]);
  90531. triangle.originalOffset = pos;
  90532. _this.triangles.push(triangle);
  90533. };
  90534. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  90535. _this.init(callback);
  90536. });
  90537. });
  90538. };
  90539. QuadraticErrorSimplification.prototype.init = function (callback) {
  90540. var _this = this;
  90541. var triangleInit1 = function (i) {
  90542. var t = _this.triangles[i];
  90543. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  90544. for (var j = 0; j < 3; j++) {
  90545. 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))));
  90546. }
  90547. };
  90548. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  90549. var triangleInit2 = function (i) {
  90550. var t = _this.triangles[i];
  90551. for (var j = 0; j < 3; ++j) {
  90552. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  90553. }
  90554. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  90555. };
  90556. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  90557. callback();
  90558. });
  90559. });
  90560. };
  90561. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  90562. var newTriangles = [];
  90563. var i;
  90564. for (i = 0; i < this.vertices.length; ++i) {
  90565. this.vertices[i].triangleCount = 0;
  90566. }
  90567. var t;
  90568. var j;
  90569. for (i = 0; i < this.triangles.length; ++i) {
  90570. if (!this.triangles[i].deleted) {
  90571. t = this.triangles[i];
  90572. for (j = 0; j < 3; ++j) {
  90573. t.vertices[j].triangleCount = 1;
  90574. }
  90575. newTriangles.push(t);
  90576. }
  90577. }
  90578. var newPositionData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []);
  90579. var newNormalData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []);
  90580. var newUVsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || []);
  90581. var newColorsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || []);
  90582. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  90583. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  90584. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  90585. var vertexCount = 0;
  90586. for (i = 0; i < this.vertices.length; ++i) {
  90587. var vertex = this.vertices[i];
  90588. vertex.id = vertexCount;
  90589. if (vertex.triangleCount) {
  90590. vertex.originalOffsets.forEach(function (originalOffset) {
  90591. if (!normalData) {
  90592. return;
  90593. }
  90594. newPositionData.push(vertex.position.x);
  90595. newPositionData.push(vertex.position.y);
  90596. newPositionData.push(vertex.position.z);
  90597. newNormalData.push(normalData[originalOffset * 3]);
  90598. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  90599. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  90600. if (uvs && uvs.length) {
  90601. newUVsData.push(uvs[(originalOffset * 2)]);
  90602. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  90603. }
  90604. else if (colorsData && colorsData.length) {
  90605. newColorsData.push(colorsData[(originalOffset * 4)]);
  90606. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  90607. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  90608. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  90609. }
  90610. ++vertexCount;
  90611. });
  90612. }
  90613. }
  90614. var startingIndex = this._reconstructedMesh.getTotalIndices();
  90615. var startingVertex = this._reconstructedMesh.getTotalVertices();
  90616. var submeshesArray = this._reconstructedMesh.subMeshes;
  90617. this._reconstructedMesh.subMeshes = [];
  90618. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  90619. var originalIndices = this._mesh.getIndices();
  90620. for (i = 0; i < newTriangles.length; ++i) {
  90621. t = newTriangles[i]; //now get the new referencing point for each vertex
  90622. [0, 1, 2].forEach(function (idx) {
  90623. var id = originalIndices[t.originalOffset + idx];
  90624. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  90625. if (offset < 0)
  90626. offset = 0;
  90627. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  90628. });
  90629. }
  90630. //overwriting the old vertex buffers and indices.
  90631. this._reconstructedMesh.setIndices(newIndicesArray);
  90632. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  90633. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  90634. if (newUVsData.length > 0)
  90635. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  90636. if (newColorsData.length > 0)
  90637. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  90638. //create submesh
  90639. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  90640. if (submeshIndex > 0) {
  90641. this._reconstructedMesh.subMeshes = [];
  90642. submeshesArray.forEach(function (submesh) {
  90643. BABYLON.SubMesh.AddToMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, /* 0, newPositionData.length/3, */ submesh.indexStart, submesh.indexCount, submesh.getMesh());
  90644. });
  90645. BABYLON.SubMesh.AddToMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, /* 0, newPositionData.length / 3, */ startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  90646. }
  90647. };
  90648. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  90649. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  90650. this._reconstructedMesh.material = this._mesh.material;
  90651. this._reconstructedMesh.parent = this._mesh.parent;
  90652. this._reconstructedMesh.isVisible = false;
  90653. this._reconstructedMesh.renderingGroupId = this._mesh.renderingGroupId;
  90654. };
  90655. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  90656. for (var i = 0; i < vertex1.triangleCount; ++i) {
  90657. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  90658. if (t.deleted)
  90659. continue;
  90660. var s = this.references[vertex1.triangleStart + i].vertexId;
  90661. var v1 = t.vertices[(s + 1) % 3];
  90662. var v2 = t.vertices[(s + 2) % 3];
  90663. if ((v1 === vertex2 || v2 === vertex2)) {
  90664. deletedArray[i] = true;
  90665. delTr.push(t);
  90666. continue;
  90667. }
  90668. var d1 = v1.position.subtract(point);
  90669. d1 = d1.normalize();
  90670. var d2 = v2.position.subtract(point);
  90671. d2 = d2.normalize();
  90672. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  90673. return true;
  90674. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  90675. deletedArray[i] = false;
  90676. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  90677. return true;
  90678. }
  90679. return false;
  90680. };
  90681. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  90682. var newDeleted = deletedTriangles;
  90683. for (var i = 0; i < vertex.triangleCount; ++i) {
  90684. var ref = this.references[vertex.triangleStart + i];
  90685. var t = this.triangles[ref.triangleId];
  90686. if (t.deleted)
  90687. continue;
  90688. if (deletedArray[i] && t.deletePending) {
  90689. t.deleted = true;
  90690. newDeleted++;
  90691. continue;
  90692. }
  90693. t.vertices[ref.vertexId] = origVertex;
  90694. t.isDirty = true;
  90695. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  90696. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  90697. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  90698. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  90699. this.references.push(ref);
  90700. }
  90701. return newDeleted;
  90702. };
  90703. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  90704. for (var i = 0; i < this.vertices.length; ++i) {
  90705. var vCount = [];
  90706. var vId = [];
  90707. var v = this.vertices[i];
  90708. var j;
  90709. for (j = 0; j < v.triangleCount; ++j) {
  90710. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  90711. for (var ii = 0; ii < 3; ii++) {
  90712. var ofs = 0;
  90713. var vv = triangle.vertices[ii];
  90714. while (ofs < vCount.length) {
  90715. if (vId[ofs] === vv.id)
  90716. break;
  90717. ++ofs;
  90718. }
  90719. if (ofs === vCount.length) {
  90720. vCount.push(1);
  90721. vId.push(vv.id);
  90722. }
  90723. else {
  90724. vCount[ofs]++;
  90725. }
  90726. }
  90727. }
  90728. for (j = 0; j < vCount.length; ++j) {
  90729. if (vCount[j] === 1) {
  90730. this.vertices[vId[j]].isBorder = true;
  90731. }
  90732. else {
  90733. this.vertices[vId[j]].isBorder = false;
  90734. }
  90735. }
  90736. }
  90737. };
  90738. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  90739. if (identifyBorders === void 0) { identifyBorders = false; }
  90740. var i;
  90741. if (!identifyBorders) {
  90742. var newTrianglesVector = [];
  90743. for (i = 0; i < this.triangles.length; ++i) {
  90744. if (!this.triangles[i].deleted) {
  90745. newTrianglesVector.push(this.triangles[i]);
  90746. }
  90747. }
  90748. this.triangles = newTrianglesVector;
  90749. }
  90750. for (i = 0; i < this.vertices.length; ++i) {
  90751. this.vertices[i].triangleCount = 0;
  90752. this.vertices[i].triangleStart = 0;
  90753. }
  90754. var t;
  90755. var j;
  90756. var v;
  90757. for (i = 0; i < this.triangles.length; ++i) {
  90758. t = this.triangles[i];
  90759. for (j = 0; j < 3; ++j) {
  90760. v = t.vertices[j];
  90761. v.triangleCount++;
  90762. }
  90763. }
  90764. var tStart = 0;
  90765. for (i = 0; i < this.vertices.length; ++i) {
  90766. this.vertices[i].triangleStart = tStart;
  90767. tStart += this.vertices[i].triangleCount;
  90768. this.vertices[i].triangleCount = 0;
  90769. }
  90770. var newReferences = new Array(this.triangles.length * 3);
  90771. for (i = 0; i < this.triangles.length; ++i) {
  90772. t = this.triangles[i];
  90773. for (j = 0; j < 3; ++j) {
  90774. v = t.vertices[j];
  90775. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  90776. v.triangleCount++;
  90777. }
  90778. }
  90779. this.references = newReferences;
  90780. if (identifyBorders) {
  90781. this.identifyBorder();
  90782. }
  90783. };
  90784. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  90785. var x = point.x;
  90786. var y = point.y;
  90787. var z = point.z;
  90788. 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
  90789. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  90790. };
  90791. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  90792. var q = vertex1.q.add(vertex2.q);
  90793. var border = vertex1.isBorder && vertex2.isBorder;
  90794. var error = 0;
  90795. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  90796. if (qDet !== 0 && !border) {
  90797. if (!pointResult) {
  90798. pointResult = BABYLON.Vector3.Zero();
  90799. }
  90800. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  90801. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  90802. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  90803. error = this.vertexError(q, pointResult);
  90804. }
  90805. else {
  90806. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  90807. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  90808. var error1 = this.vertexError(q, vertex1.position);
  90809. var error2 = this.vertexError(q, vertex2.position);
  90810. var error3 = this.vertexError(q, p3);
  90811. error = Math.min(error1, error2, error3);
  90812. if (error === error1) {
  90813. if (pointResult) {
  90814. pointResult.copyFrom(vertex1.position);
  90815. }
  90816. }
  90817. else if (error === error2) {
  90818. if (pointResult) {
  90819. pointResult.copyFrom(vertex2.position);
  90820. }
  90821. }
  90822. else {
  90823. if (pointResult) {
  90824. pointResult.copyFrom(p3);
  90825. }
  90826. }
  90827. }
  90828. return error;
  90829. };
  90830. return QuadraticErrorSimplification;
  90831. }());
  90832. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  90833. })(BABYLON || (BABYLON = {}));
  90834. //# sourceMappingURL=babylon.meshSimplification.js.map
  90835. var BABYLON;
  90836. (function (BABYLON) {
  90837. var MeshLODLevel = /** @class */ (function () {
  90838. function MeshLODLevel(distance, mesh) {
  90839. this.distance = distance;
  90840. this.mesh = mesh;
  90841. }
  90842. return MeshLODLevel;
  90843. }());
  90844. BABYLON.MeshLODLevel = MeshLODLevel;
  90845. })(BABYLON || (BABYLON = {}));
  90846. //# sourceMappingURL=babylon.meshLODLevel.js.map
  90847. var BABYLON;
  90848. (function (BABYLON) {
  90849. /**
  90850. * Defines the root class used to create scene optimization to use with SceneOptimizer
  90851. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  90852. */
  90853. var SceneOptimization = /** @class */ (function () {
  90854. /**
  90855. * Creates the SceneOptimization object
  90856. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  90857. * @param desc defines the description associated with the optimization
  90858. */
  90859. function SceneOptimization(
  90860. /**
  90861. * Defines the priority of this optimization (0 by default which means first in the list)
  90862. */
  90863. priority) {
  90864. if (priority === void 0) { priority = 0; }
  90865. this.priority = priority;
  90866. }
  90867. /**
  90868. * Gets a string describing the action executed by the current optimization
  90869. * @returns description string
  90870. */
  90871. SceneOptimization.prototype.getDescription = function () {
  90872. return "";
  90873. };
  90874. /**
  90875. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  90876. * @param scene defines the current scene where to apply this optimization
  90877. * @param optimizer defines the current optimizer
  90878. * @returns true if everything that can be done was applied
  90879. */
  90880. SceneOptimization.prototype.apply = function (scene, optimizer) {
  90881. return true;
  90882. };
  90883. ;
  90884. return SceneOptimization;
  90885. }());
  90886. BABYLON.SceneOptimization = SceneOptimization;
  90887. /**
  90888. * Defines an optimization used to reduce the size of render target textures
  90889. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  90890. */
  90891. var TextureOptimization = /** @class */ (function (_super) {
  90892. __extends(TextureOptimization, _super);
  90893. /**
  90894. * Creates the TextureOptimization object
  90895. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  90896. * @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
  90897. * @param step defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  90898. */
  90899. function TextureOptimization(
  90900. /**
  90901. * Defines the priority of this optimization (0 by default which means first in the list)
  90902. */
  90903. priority,
  90904. /**
  90905. * 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
  90906. */
  90907. maximumSize,
  90908. /**
  90909. * Defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  90910. */
  90911. step) {
  90912. if (priority === void 0) { priority = 0; }
  90913. if (maximumSize === void 0) { maximumSize = 1024; }
  90914. if (step === void 0) { step = 0.5; }
  90915. var _this = _super.call(this, priority) || this;
  90916. _this.priority = priority;
  90917. _this.maximumSize = maximumSize;
  90918. _this.step = step;
  90919. return _this;
  90920. }
  90921. /**
  90922. * Gets a string describing the action executed by the current optimization
  90923. * @returns description string
  90924. */
  90925. TextureOptimization.prototype.getDescription = function () {
  90926. return "Reducing render target texture size to " + this.maximumSize;
  90927. };
  90928. /**
  90929. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  90930. * @param scene defines the current scene where to apply this optimization
  90931. * @param optimizer defines the current optimizer
  90932. * @returns true if everything that can be done was applied
  90933. */
  90934. TextureOptimization.prototype.apply = function (scene, optimizer) {
  90935. var allDone = true;
  90936. for (var index = 0; index < scene.textures.length; index++) {
  90937. var texture = scene.textures[index];
  90938. if (!texture.canRescale || texture.getContext) {
  90939. continue;
  90940. }
  90941. var currentSize = texture.getSize();
  90942. var maxDimension = Math.max(currentSize.width, currentSize.height);
  90943. if (maxDimension > this.maximumSize) {
  90944. texture.scale(this.step);
  90945. allDone = false;
  90946. }
  90947. }
  90948. return allDone;
  90949. };
  90950. return TextureOptimization;
  90951. }(SceneOptimization));
  90952. BABYLON.TextureOptimization = TextureOptimization;
  90953. /**
  90954. * Defines an optimization used to increase or decrease the rendering resolution
  90955. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  90956. */
  90957. var HardwareScalingOptimization = /** @class */ (function (_super) {
  90958. __extends(HardwareScalingOptimization, _super);
  90959. /**
  90960. * Creates the HardwareScalingOptimization object
  90961. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  90962. * @param maximumScale defines the maximum scale to use (2 by default)
  90963. * @param step defines the step to use between two passes (0.5 by default)
  90964. */
  90965. function HardwareScalingOptimization(
  90966. /**
  90967. * Defines the priority of this optimization (0 by default which means first in the list)
  90968. */
  90969. priority,
  90970. /**
  90971. * Defines the maximum scale to use (2 by default)
  90972. */
  90973. maximumScale,
  90974. /**
  90975. * Defines the step to use between two passes (0.5 by default)
  90976. */
  90977. step) {
  90978. if (priority === void 0) { priority = 0; }
  90979. if (maximumScale === void 0) { maximumScale = 2; }
  90980. if (step === void 0) { step = 0.25; }
  90981. var _this = _super.call(this, priority) || this;
  90982. _this.priority = priority;
  90983. _this.maximumScale = maximumScale;
  90984. _this.step = step;
  90985. _this._currentScale = -1;
  90986. _this._directionOffset = 1;
  90987. return _this;
  90988. }
  90989. /**
  90990. * Gets a string describing the action executed by the current optimization
  90991. * @return description string
  90992. */
  90993. HardwareScalingOptimization.prototype.getDescription = function () {
  90994. return "Setting hardware scaling level to " + this._currentScale;
  90995. };
  90996. /**
  90997. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  90998. * @param scene defines the current scene where to apply this optimization
  90999. * @param optimizer defines the current optimizer
  91000. * @returns true if everything that can be done was applied
  91001. */
  91002. HardwareScalingOptimization.prototype.apply = function (scene, optimizer) {
  91003. if (this._currentScale === -1) {
  91004. this._currentScale = scene.getEngine().getHardwareScalingLevel();
  91005. if (this._currentScale > this.maximumScale) {
  91006. this._directionOffset = -1;
  91007. }
  91008. }
  91009. this._currentScale += this._directionOffset * this.step;
  91010. scene.getEngine().setHardwareScalingLevel(this._currentScale);
  91011. return this._directionOffset === 1 ? this._currentScale >= this.maximumScale : this._currentScale <= this.maximumScale;
  91012. };
  91013. ;
  91014. return HardwareScalingOptimization;
  91015. }(SceneOptimization));
  91016. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  91017. /**
  91018. * Defines an optimization used to remove shadows
  91019. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  91020. */
  91021. var ShadowsOptimization = /** @class */ (function (_super) {
  91022. __extends(ShadowsOptimization, _super);
  91023. function ShadowsOptimization() {
  91024. return _super !== null && _super.apply(this, arguments) || this;
  91025. }
  91026. /**
  91027. * Gets a string describing the action executed by the current optimization
  91028. * @return description string
  91029. */
  91030. ShadowsOptimization.prototype.getDescription = function () {
  91031. return "Turning shadows on/off";
  91032. };
  91033. /**
  91034. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  91035. * @param scene defines the current scene where to apply this optimization
  91036. * @param optimizer defines the current optimizer
  91037. * @returns true if everything that can be done was applied
  91038. */
  91039. ShadowsOptimization.prototype.apply = function (scene, optimizer) {
  91040. scene.shadowsEnabled = optimizer.isInImprovementMode;
  91041. return true;
  91042. };
  91043. ;
  91044. return ShadowsOptimization;
  91045. }(SceneOptimization));
  91046. BABYLON.ShadowsOptimization = ShadowsOptimization;
  91047. /**
  91048. * Defines an optimization used to turn post-processes off
  91049. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  91050. */
  91051. var PostProcessesOptimization = /** @class */ (function (_super) {
  91052. __extends(PostProcessesOptimization, _super);
  91053. function PostProcessesOptimization() {
  91054. return _super !== null && _super.apply(this, arguments) || this;
  91055. }
  91056. /**
  91057. * Gets a string describing the action executed by the current optimization
  91058. * @return description string
  91059. */
  91060. PostProcessesOptimization.prototype.getDescription = function () {
  91061. return "Turning post-processes on/off";
  91062. };
  91063. /**
  91064. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  91065. * @param scene defines the current scene where to apply this optimization
  91066. * @param optimizer defines the current optimizer
  91067. * @returns true if everything that can be done was applied
  91068. */
  91069. PostProcessesOptimization.prototype.apply = function (scene, optimizer) {
  91070. scene.postProcessesEnabled = optimizer.isInImprovementMode;
  91071. return true;
  91072. };
  91073. ;
  91074. return PostProcessesOptimization;
  91075. }(SceneOptimization));
  91076. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  91077. /**
  91078. * Defines an optimization used to turn lens flares off
  91079. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  91080. */
  91081. var LensFlaresOptimization = /** @class */ (function (_super) {
  91082. __extends(LensFlaresOptimization, _super);
  91083. function LensFlaresOptimization() {
  91084. return _super !== null && _super.apply(this, arguments) || this;
  91085. }
  91086. /**
  91087. * Gets a string describing the action executed by the current optimization
  91088. * @return description string
  91089. */
  91090. LensFlaresOptimization.prototype.getDescription = function () {
  91091. return "Turning lens flares on/off";
  91092. };
  91093. /**
  91094. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  91095. * @param scene defines the current scene where to apply this optimization
  91096. * @param optimizer defines the current optimizer
  91097. * @returns true if everything that can be done was applied
  91098. */
  91099. LensFlaresOptimization.prototype.apply = function (scene, optimizer) {
  91100. scene.lensFlaresEnabled = optimizer.isInImprovementMode;
  91101. return true;
  91102. };
  91103. ;
  91104. return LensFlaresOptimization;
  91105. }(SceneOptimization));
  91106. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  91107. /**
  91108. * Defines an optimization based on user defined callback.
  91109. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  91110. */
  91111. var CustomOptimization = /** @class */ (function (_super) {
  91112. __extends(CustomOptimization, _super);
  91113. function CustomOptimization() {
  91114. return _super !== null && _super.apply(this, arguments) || this;
  91115. }
  91116. /**
  91117. * Gets a string describing the action executed by the current optimization
  91118. * @returns description string
  91119. */
  91120. CustomOptimization.prototype.getDescription = function () {
  91121. if (this.onGetDescription) {
  91122. return this.onGetDescription();
  91123. }
  91124. return "Running user defined callback";
  91125. };
  91126. /**
  91127. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  91128. * @param scene defines the current scene where to apply this optimization
  91129. * @param optimizer defines the current optimizer
  91130. * @returns true if everything that can be done was applied
  91131. */
  91132. CustomOptimization.prototype.apply = function (scene, optimizer) {
  91133. if (this.onApply) {
  91134. return this.onApply(scene, optimizer);
  91135. }
  91136. return true;
  91137. };
  91138. ;
  91139. return CustomOptimization;
  91140. }(SceneOptimization));
  91141. BABYLON.CustomOptimization = CustomOptimization;
  91142. /**
  91143. * Defines an optimization used to turn particles off
  91144. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  91145. */
  91146. var ParticlesOptimization = /** @class */ (function (_super) {
  91147. __extends(ParticlesOptimization, _super);
  91148. function ParticlesOptimization() {
  91149. return _super !== null && _super.apply(this, arguments) || this;
  91150. }
  91151. /**
  91152. * Gets a string describing the action executed by the current optimization
  91153. * @return description string
  91154. */
  91155. ParticlesOptimization.prototype.getDescription = function () {
  91156. return "Turning particles on/off";
  91157. };
  91158. /**
  91159. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  91160. * @param scene defines the current scene where to apply this optimization
  91161. * @param optimizer defines the current optimizer
  91162. * @returns true if everything that can be done was applied
  91163. */
  91164. ParticlesOptimization.prototype.apply = function (scene, optimizer) {
  91165. scene.particlesEnabled = optimizer.isInImprovementMode;
  91166. return true;
  91167. };
  91168. ;
  91169. return ParticlesOptimization;
  91170. }(SceneOptimization));
  91171. BABYLON.ParticlesOptimization = ParticlesOptimization;
  91172. /**
  91173. * Defines an optimization used to turn render targets off
  91174. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  91175. */
  91176. var RenderTargetsOptimization = /** @class */ (function (_super) {
  91177. __extends(RenderTargetsOptimization, _super);
  91178. function RenderTargetsOptimization() {
  91179. return _super !== null && _super.apply(this, arguments) || this;
  91180. }
  91181. /**
  91182. * Gets a string describing the action executed by the current optimization
  91183. * @return description string
  91184. */
  91185. RenderTargetsOptimization.prototype.getDescription = function () {
  91186. return "Turning render targets off";
  91187. };
  91188. /**
  91189. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  91190. * @param scene defines the current scene where to apply this optimization
  91191. * @param optimizer defines the current optimizer
  91192. * @returns true if everything that can be done was applied
  91193. */
  91194. RenderTargetsOptimization.prototype.apply = function (scene, optimizer) {
  91195. scene.renderTargetsEnabled = optimizer.isInImprovementMode;
  91196. return true;
  91197. };
  91198. ;
  91199. return RenderTargetsOptimization;
  91200. }(SceneOptimization));
  91201. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  91202. /**
  91203. * Defines an optimization used to merge meshes with compatible materials
  91204. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  91205. */
  91206. var MergeMeshesOptimization = /** @class */ (function (_super) {
  91207. __extends(MergeMeshesOptimization, _super);
  91208. function MergeMeshesOptimization() {
  91209. var _this = _super !== null && _super.apply(this, arguments) || this;
  91210. _this._canBeMerged = function (abstractMesh) {
  91211. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  91212. return false;
  91213. }
  91214. var mesh = abstractMesh;
  91215. if (!mesh.isVisible || !mesh.isEnabled()) {
  91216. return false;
  91217. }
  91218. if (mesh.instances.length > 0) {
  91219. return false;
  91220. }
  91221. if (mesh.skeleton || mesh.hasLODLevels) {
  91222. return false;
  91223. }
  91224. if (mesh.parent) {
  91225. return false;
  91226. }
  91227. return true;
  91228. };
  91229. return _this;
  91230. }
  91231. Object.defineProperty(MergeMeshesOptimization, "UpdateSelectionTree", {
  91232. /**
  91233. * Gets or sets a boolean which defines if optimization octree has to be updated
  91234. */
  91235. get: function () {
  91236. return MergeMeshesOptimization._UpdateSelectionTree;
  91237. },
  91238. /**
  91239. * Gets or sets a boolean which defines if optimization octree has to be updated
  91240. */
  91241. set: function (value) {
  91242. MergeMeshesOptimization._UpdateSelectionTree = value;
  91243. },
  91244. enumerable: true,
  91245. configurable: true
  91246. });
  91247. /**
  91248. * Gets a string describing the action executed by the current optimization
  91249. * @return description string
  91250. */
  91251. MergeMeshesOptimization.prototype.getDescription = function () {
  91252. return "Merging similar meshes together";
  91253. };
  91254. /**
  91255. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  91256. * @param scene defines the current scene where to apply this optimization
  91257. * @param optimizer defines the current optimizer
  91258. * @param updateSelectionTree defines that the selection octree has to be updated (false by default)
  91259. * @returns true if everything that can be done was applied
  91260. */
  91261. MergeMeshesOptimization.prototype.apply = function (scene, optimizer, updateSelectionTree) {
  91262. var globalPool = scene.meshes.slice(0);
  91263. var globalLength = globalPool.length;
  91264. for (var index = 0; index < globalLength; index++) {
  91265. var currentPool = new Array();
  91266. var current = globalPool[index];
  91267. // Checks
  91268. if (!this._canBeMerged(current)) {
  91269. continue;
  91270. }
  91271. currentPool.push(current);
  91272. // Find compatible meshes
  91273. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  91274. var otherMesh = globalPool[subIndex];
  91275. if (!this._canBeMerged(otherMesh)) {
  91276. continue;
  91277. }
  91278. if (otherMesh.material !== current.material) {
  91279. continue;
  91280. }
  91281. if (otherMesh.checkCollisions !== current.checkCollisions) {
  91282. continue;
  91283. }
  91284. currentPool.push(otherMesh);
  91285. globalLength--;
  91286. globalPool.splice(subIndex, 1);
  91287. subIndex--;
  91288. }
  91289. if (currentPool.length < 2) {
  91290. continue;
  91291. }
  91292. // Merge meshes
  91293. BABYLON.Mesh.MergeMeshes(currentPool, undefined, true);
  91294. }
  91295. if (updateSelectionTree != undefined) {
  91296. if (updateSelectionTree) {
  91297. scene.createOrUpdateSelectionOctree();
  91298. }
  91299. }
  91300. else if (MergeMeshesOptimization.UpdateSelectionTree) {
  91301. scene.createOrUpdateSelectionOctree();
  91302. }
  91303. return true;
  91304. };
  91305. ;
  91306. MergeMeshesOptimization._UpdateSelectionTree = false;
  91307. return MergeMeshesOptimization;
  91308. }(SceneOptimization));
  91309. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  91310. /**
  91311. * Defines a list of options used by SceneOptimizer
  91312. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  91313. */
  91314. var SceneOptimizerOptions = /** @class */ (function () {
  91315. /**
  91316. * Creates a new list of options used by SceneOptimizer
  91317. * @param targetFrameRate defines the target frame rate to reach (60 by default)
  91318. * @param trackerDuration defines the interval between two checkes (2000ms by default)
  91319. */
  91320. function SceneOptimizerOptions(
  91321. /**
  91322. * Defines the target frame rate to reach (60 by default)
  91323. */
  91324. targetFrameRate,
  91325. /**
  91326. * Defines the interval between two checkes (2000ms by default)
  91327. */
  91328. trackerDuration) {
  91329. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  91330. if (trackerDuration === void 0) { trackerDuration = 2000; }
  91331. this.targetFrameRate = targetFrameRate;
  91332. this.trackerDuration = trackerDuration;
  91333. /**
  91334. * Gets the list of optimizations to apply
  91335. */
  91336. this.optimizations = new Array();
  91337. }
  91338. /**
  91339. * Add a new optimization
  91340. * @param optimization defines the SceneOptimization to add to the list of active optimizations
  91341. * @returns the current SceneOptimizerOptions
  91342. */
  91343. SceneOptimizerOptions.prototype.addOptimization = function (optimization) {
  91344. this.optimizations.push(optimization);
  91345. return this;
  91346. };
  91347. /**
  91348. * Add a new custom optimization
  91349. * @param onApply defines the callback called to apply the custom optimization (true if everything that can be done was applied)
  91350. * @param onGetDescription defines the callback called to get the description attached with the optimization.
  91351. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  91352. * @returns the current SceneOptimizerOptions
  91353. */
  91354. SceneOptimizerOptions.prototype.addCustomOptimization = function (onApply, onGetDescription, priority) {
  91355. if (priority === void 0) { priority = 0; }
  91356. var optimization = new CustomOptimization(priority);
  91357. optimization.onApply = onApply;
  91358. optimization.onGetDescription = onGetDescription;
  91359. this.optimizations.push(optimization);
  91360. return this;
  91361. };
  91362. /**
  91363. * Creates a list of pre-defined optimizations aimed to reduce the visual impact on the scene
  91364. * @param targetFrameRate defines the target frame rate (60 by default)
  91365. * @returns a SceneOptimizerOptions object
  91366. */
  91367. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  91368. var result = new SceneOptimizerOptions(targetFrameRate);
  91369. var priority = 0;
  91370. result.addOptimization(new MergeMeshesOptimization(priority));
  91371. result.addOptimization(new ShadowsOptimization(priority));
  91372. result.addOptimization(new LensFlaresOptimization(priority));
  91373. // Next priority
  91374. priority++;
  91375. result.addOptimization(new PostProcessesOptimization(priority));
  91376. result.addOptimization(new ParticlesOptimization(priority));
  91377. // Next priority
  91378. priority++;
  91379. result.addOptimization(new TextureOptimization(priority, 1024));
  91380. return result;
  91381. };
  91382. /**
  91383. * Creates a list of pre-defined optimizations aimed to have a moderate impact on the scene visual
  91384. * @param targetFrameRate defines the target frame rate (60 by default)
  91385. * @returns a SceneOptimizerOptions object
  91386. */
  91387. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  91388. var result = new SceneOptimizerOptions(targetFrameRate);
  91389. var priority = 0;
  91390. result.addOptimization(new MergeMeshesOptimization(priority));
  91391. result.addOptimization(new ShadowsOptimization(priority));
  91392. result.addOptimization(new LensFlaresOptimization(priority));
  91393. // Next priority
  91394. priority++;
  91395. result.addOptimization(new PostProcessesOptimization(priority));
  91396. result.addOptimization(new ParticlesOptimization(priority));
  91397. // Next priority
  91398. priority++;
  91399. result.addOptimization(new TextureOptimization(priority, 512));
  91400. // Next priority
  91401. priority++;
  91402. result.addOptimization(new RenderTargetsOptimization(priority));
  91403. // Next priority
  91404. priority++;
  91405. result.addOptimization(new HardwareScalingOptimization(priority, 2));
  91406. return result;
  91407. };
  91408. /**
  91409. * Creates a list of pre-defined optimizations aimed to have a big impact on the scene visual
  91410. * @param targetFrameRate defines the target frame rate (60 by default)
  91411. * @returns a SceneOptimizerOptions object
  91412. */
  91413. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  91414. var result = new SceneOptimizerOptions(targetFrameRate);
  91415. var priority = 0;
  91416. result.addOptimization(new MergeMeshesOptimization(priority));
  91417. result.addOptimization(new ShadowsOptimization(priority));
  91418. result.addOptimization(new LensFlaresOptimization(priority));
  91419. // Next priority
  91420. priority++;
  91421. result.addOptimization(new PostProcessesOptimization(priority));
  91422. result.addOptimization(new ParticlesOptimization(priority));
  91423. // Next priority
  91424. priority++;
  91425. result.addOptimization(new TextureOptimization(priority, 256));
  91426. // Next priority
  91427. priority++;
  91428. result.addOptimization(new RenderTargetsOptimization(priority));
  91429. // Next priority
  91430. priority++;
  91431. result.addOptimization(new HardwareScalingOptimization(priority, 4));
  91432. return result;
  91433. };
  91434. return SceneOptimizerOptions;
  91435. }());
  91436. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  91437. /**
  91438. * Class used to run optimizations in order to reach a target frame rate
  91439. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  91440. */
  91441. var SceneOptimizer = /** @class */ (function () {
  91442. /**
  91443. * Creates a new SceneOptimizer
  91444. * @param scene defines the scene to work on
  91445. * @param options defines the options to use with the SceneOptimizer
  91446. * @param autoGeneratePriorities defines if priorities must be generated and not read from SceneOptimization property (true by default)
  91447. * @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)
  91448. */
  91449. function SceneOptimizer(scene, options, autoGeneratePriorities, improvementMode) {
  91450. if (autoGeneratePriorities === void 0) { autoGeneratePriorities = true; }
  91451. if (improvementMode === void 0) { improvementMode = false; }
  91452. var _this = this;
  91453. this._isRunning = false;
  91454. this._currentPriorityLevel = 0;
  91455. this._targetFrameRate = 60;
  91456. this._trackerDuration = 2000;
  91457. this._currentFrameRate = 0;
  91458. this._improvementMode = false;
  91459. /**
  91460. * Defines an observable called when the optimizer reaches the target frame rate
  91461. */
  91462. this.onSuccessObservable = new BABYLON.Observable();
  91463. /**
  91464. * Defines an observable called when the optimizer enables an optimization
  91465. */
  91466. this.onNewOptimizationAppliedObservable = new BABYLON.Observable();
  91467. /**
  91468. * Defines an observable called when the optimizer is not able to reach the target frame rate
  91469. */
  91470. this.onFailureObservable = new BABYLON.Observable();
  91471. if (!options) {
  91472. this._options = new SceneOptimizerOptions();
  91473. }
  91474. else {
  91475. this._options = options;
  91476. }
  91477. if (this._options.targetFrameRate) {
  91478. this._targetFrameRate = this._options.targetFrameRate;
  91479. }
  91480. if (this._options.trackerDuration) {
  91481. this._trackerDuration = this._options.trackerDuration;
  91482. }
  91483. if (autoGeneratePriorities) {
  91484. var priority = 0;
  91485. for (var _i = 0, _a = this._options.optimizations; _i < _a.length; _i++) {
  91486. var optim = _a[_i];
  91487. optim.priority = priority++;
  91488. }
  91489. }
  91490. this._improvementMode = improvementMode;
  91491. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  91492. this._sceneDisposeObserver = this._scene.onDisposeObservable.add(function () {
  91493. _this._sceneDisposeObserver = null;
  91494. _this.dispose();
  91495. });
  91496. }
  91497. Object.defineProperty(SceneOptimizer.prototype, "isInImprovementMode", {
  91498. /**
  91499. * Gets a boolean indicating if the optimizer is in improvement mode
  91500. */
  91501. get: function () {
  91502. return this._improvementMode;
  91503. },
  91504. enumerable: true,
  91505. configurable: true
  91506. });
  91507. Object.defineProperty(SceneOptimizer.prototype, "currentPriorityLevel", {
  91508. /**
  91509. * Gets the current priority level (0 at start)
  91510. */
  91511. get: function () {
  91512. return this._currentPriorityLevel;
  91513. },
  91514. enumerable: true,
  91515. configurable: true
  91516. });
  91517. Object.defineProperty(SceneOptimizer.prototype, "currentFrameRate", {
  91518. /**
  91519. * Gets the current frame rate checked by the SceneOptimizer
  91520. */
  91521. get: function () {
  91522. return this._currentFrameRate;
  91523. },
  91524. enumerable: true,
  91525. configurable: true
  91526. });
  91527. Object.defineProperty(SceneOptimizer.prototype, "targetFrameRate", {
  91528. /**
  91529. * Gets or sets the current target frame rate (60 by default)
  91530. */
  91531. get: function () {
  91532. return this._targetFrameRate;
  91533. },
  91534. /**
  91535. * Gets or sets the current target frame rate (60 by default)
  91536. */
  91537. set: function (value) {
  91538. this._targetFrameRate = value;
  91539. },
  91540. enumerable: true,
  91541. configurable: true
  91542. });
  91543. Object.defineProperty(SceneOptimizer.prototype, "trackerDuration", {
  91544. /**
  91545. * Gets or sets the current interval between two checks (every 2000ms by default)
  91546. */
  91547. get: function () {
  91548. return this._trackerDuration;
  91549. },
  91550. /**
  91551. * Gets or sets the current interval between two checks (every 2000ms by default)
  91552. */
  91553. set: function (value) {
  91554. this._trackerDuration = value;
  91555. },
  91556. enumerable: true,
  91557. configurable: true
  91558. });
  91559. Object.defineProperty(SceneOptimizer.prototype, "optimizations", {
  91560. /**
  91561. * Gets the list of active optimizations
  91562. */
  91563. get: function () {
  91564. return this._options.optimizations;
  91565. },
  91566. enumerable: true,
  91567. configurable: true
  91568. });
  91569. /**
  91570. * Stops the current optimizer
  91571. */
  91572. SceneOptimizer.prototype.stop = function () {
  91573. this._isRunning = false;
  91574. };
  91575. /**
  91576. * Reset the optimizer to initial step (current priority level = 0)
  91577. */
  91578. SceneOptimizer.prototype.reset = function () {
  91579. this._currentPriorityLevel = 0;
  91580. };
  91581. /**
  91582. * Start the optimizer. By default it will try to reach a specific framerate
  91583. * but if the optimizer is set with improvementMode === true then it will run all optimiatiation while frame rate is above the target frame rate
  91584. */
  91585. SceneOptimizer.prototype.start = function () {
  91586. var _this = this;
  91587. if (this._isRunning) {
  91588. return;
  91589. }
  91590. this._isRunning = true;
  91591. // Let's wait for the scene to be ready before running our check
  91592. this._scene.executeWhenReady(function () {
  91593. setTimeout(function () {
  91594. _this._checkCurrentState();
  91595. }, _this._trackerDuration);
  91596. });
  91597. };
  91598. SceneOptimizer.prototype._checkCurrentState = function () {
  91599. var _this = this;
  91600. if (!this._isRunning) {
  91601. return;
  91602. }
  91603. var scene = this._scene;
  91604. var options = this._options;
  91605. this._currentFrameRate = Math.round(scene.getEngine().getFps());
  91606. if (this._improvementMode && this._currentFrameRate <= this._targetFrameRate ||
  91607. !this._improvementMode && this._currentFrameRate >= this._targetFrameRate) {
  91608. this._isRunning = false;
  91609. this.onSuccessObservable.notifyObservers(this);
  91610. return;
  91611. }
  91612. // Apply current level of optimizations
  91613. var allDone = true;
  91614. var noOptimizationApplied = true;
  91615. for (var index = 0; index < options.optimizations.length; index++) {
  91616. var optimization = options.optimizations[index];
  91617. if (optimization.priority === this._currentPriorityLevel) {
  91618. noOptimizationApplied = false;
  91619. allDone = allDone && optimization.apply(scene, this);
  91620. this.onNewOptimizationAppliedObservable.notifyObservers(optimization);
  91621. }
  91622. }
  91623. // If no optimization was applied, this is a failure :(
  91624. if (noOptimizationApplied) {
  91625. this._isRunning = false;
  91626. this.onFailureObservable.notifyObservers(this);
  91627. return;
  91628. }
  91629. // If all optimizations were done, move to next level
  91630. if (allDone) {
  91631. this._currentPriorityLevel++;
  91632. }
  91633. // Let's the system running for a specific amount of time before checking FPS
  91634. scene.executeWhenReady(function () {
  91635. setTimeout(function () {
  91636. _this._checkCurrentState();
  91637. }, _this._trackerDuration);
  91638. });
  91639. };
  91640. /**
  91641. * Release all resources
  91642. */
  91643. SceneOptimizer.prototype.dispose = function () {
  91644. this.stop();
  91645. this.onSuccessObservable.clear();
  91646. this.onFailureObservable.clear();
  91647. this.onNewOptimizationAppliedObservable.clear();
  91648. if (this._sceneDisposeObserver) {
  91649. this._scene.onDisposeObservable.remove(this._sceneDisposeObserver);
  91650. }
  91651. };
  91652. /**
  91653. * Helper function to create a SceneOptimizer with one single line of code
  91654. * @param scene defines the scene to work on
  91655. * @param options defines the options to use with the SceneOptimizer
  91656. * @param onSuccess defines a callback to call on success
  91657. * @param onFailure defines a callback to call on failure
  91658. * @returns the new SceneOptimizer object
  91659. */
  91660. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  91661. var optimizer = new SceneOptimizer(scene, options || SceneOptimizerOptions.ModerateDegradationAllowed(), false);
  91662. if (onSuccess) {
  91663. optimizer.onSuccessObservable.add(function () {
  91664. onSuccess();
  91665. });
  91666. }
  91667. if (onFailure) {
  91668. optimizer.onFailureObservable.add(function () {
  91669. onFailure();
  91670. });
  91671. }
  91672. optimizer.start();
  91673. return optimizer;
  91674. };
  91675. return SceneOptimizer;
  91676. }());
  91677. BABYLON.SceneOptimizer = SceneOptimizer;
  91678. })(BABYLON || (BABYLON = {}));
  91679. //# sourceMappingURL=babylon.sceneOptimizer.js.map
  91680. var BABYLON;
  91681. (function (BABYLON) {
  91682. var OutlineRenderer = /** @class */ (function () {
  91683. function OutlineRenderer(scene) {
  91684. this.zOffset = 1;
  91685. this._scene = scene;
  91686. }
  91687. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  91688. var _this = this;
  91689. if (useOverlay === void 0) { useOverlay = false; }
  91690. var scene = this._scene;
  91691. var engine = this._scene.getEngine();
  91692. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  91693. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  91694. return;
  91695. }
  91696. var mesh = subMesh.getRenderingMesh();
  91697. var material = subMesh.getMaterial();
  91698. if (!material || !scene.activeCamera) {
  91699. return;
  91700. }
  91701. engine.enableEffect(this._effect);
  91702. // Logarithmic depth
  91703. if (material.useLogarithmicDepth) {
  91704. this._effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  91705. }
  91706. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  91707. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : material.alpha);
  91708. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  91709. // Bones
  91710. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  91711. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  91712. }
  91713. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  91714. // Alpha test
  91715. if (material && material.needAlphaTesting()) {
  91716. var alphaTexture = material.getAlphaTestTexture();
  91717. if (alphaTexture) {
  91718. this._effect.setTexture("diffuseSampler", alphaTexture);
  91719. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  91720. }
  91721. }
  91722. engine.setZOffset(-this.zOffset);
  91723. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
  91724. engine.setZOffset(0);
  91725. };
  91726. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  91727. var defines = [];
  91728. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  91729. var mesh = subMesh.getMesh();
  91730. var material = subMesh.getMaterial();
  91731. if (material) {
  91732. // Alpha test
  91733. if (material.needAlphaTesting()) {
  91734. defines.push("#define ALPHATEST");
  91735. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  91736. attribs.push(BABYLON.VertexBuffer.UVKind);
  91737. defines.push("#define UV1");
  91738. }
  91739. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  91740. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  91741. defines.push("#define UV2");
  91742. }
  91743. }
  91744. //Logarithmic depth
  91745. if (material.useLogarithmicDepth) {
  91746. defines.push("#define LOGARITHMICDEPTH");
  91747. }
  91748. }
  91749. // Bones
  91750. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  91751. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  91752. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  91753. if (mesh.numBoneInfluencers > 4) {
  91754. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  91755. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  91756. }
  91757. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  91758. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  91759. }
  91760. else {
  91761. defines.push("#define NUM_BONE_INFLUENCERS 0");
  91762. }
  91763. // Instances
  91764. if (useInstances) {
  91765. defines.push("#define INSTANCES");
  91766. attribs.push("world0");
  91767. attribs.push("world1");
  91768. attribs.push("world2");
  91769. attribs.push("world3");
  91770. }
  91771. // Get correct effect
  91772. var join = defines.join("\n");
  91773. if (this._cachedDefines !== join) {
  91774. this._cachedDefines = join;
  91775. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color", "logarithmicDepthConstant"], ["diffuseSampler"], join);
  91776. }
  91777. return this._effect.isReady();
  91778. };
  91779. return OutlineRenderer;
  91780. }());
  91781. BABYLON.OutlineRenderer = OutlineRenderer;
  91782. })(BABYLON || (BABYLON = {}));
  91783. //# sourceMappingURL=babylon.outlineRenderer.js.map
  91784. var BABYLON;
  91785. (function (BABYLON) {
  91786. var FaceAdjacencies = /** @class */ (function () {
  91787. function FaceAdjacencies() {
  91788. this.edges = new Array();
  91789. this.edgesConnectedCount = 0;
  91790. }
  91791. return FaceAdjacencies;
  91792. }());
  91793. var EdgesRenderer = /** @class */ (function () {
  91794. // Beware when you use this class with complex objects as the adjacencies computation can be really long
  91795. function EdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices) {
  91796. if (epsilon === void 0) { epsilon = 0.95; }
  91797. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  91798. this.edgesWidthScalerForOrthographic = 1000.0;
  91799. this.edgesWidthScalerForPerspective = 50.0;
  91800. this._linesPositions = new Array();
  91801. this._linesNormals = new Array();
  91802. this._linesIndices = new Array();
  91803. this._buffers = {};
  91804. this._checkVerticesInsteadOfIndices = false;
  91805. /** Gets or sets a boolean indicating if the edgesRenderer is active */
  91806. this.isEnabled = true;
  91807. this._source = source;
  91808. this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices;
  91809. this._epsilon = epsilon;
  91810. this._prepareRessources();
  91811. this._generateEdgesLines();
  91812. }
  91813. EdgesRenderer.prototype._prepareRessources = function () {
  91814. if (this._lineShader) {
  91815. return;
  91816. }
  91817. this._lineShader = new BABYLON.ShaderMaterial("lineShader", this._source.getScene(), "line", {
  91818. attributes: ["position", "normal"],
  91819. uniforms: ["worldViewProjection", "color", "width", "aspectRatio"]
  91820. });
  91821. this._lineShader.disableDepthWrite = true;
  91822. this._lineShader.backFaceCulling = false;
  91823. };
  91824. EdgesRenderer.prototype._rebuild = function () {
  91825. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  91826. if (buffer) {
  91827. buffer._rebuild();
  91828. }
  91829. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  91830. if (buffer) {
  91831. buffer._rebuild();
  91832. }
  91833. var scene = this._source.getScene();
  91834. var engine = scene.getEngine();
  91835. this._ib = engine.createIndexBuffer(this._linesIndices);
  91836. };
  91837. EdgesRenderer.prototype.dispose = function () {
  91838. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  91839. if (buffer) {
  91840. buffer.dispose();
  91841. this._buffers[BABYLON.VertexBuffer.PositionKind] = null;
  91842. }
  91843. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  91844. if (buffer) {
  91845. buffer.dispose();
  91846. this._buffers[BABYLON.VertexBuffer.NormalKind] = null;
  91847. }
  91848. this._source.getScene().getEngine()._releaseBuffer(this._ib);
  91849. this._lineShader.dispose();
  91850. };
  91851. EdgesRenderer.prototype._processEdgeForAdjacencies = function (pa, pb, p0, p1, p2) {
  91852. if (pa === p0 && pb === p1 || pa === p1 && pb === p0) {
  91853. return 0;
  91854. }
  91855. if (pa === p1 && pb === p2 || pa === p2 && pb === p1) {
  91856. return 1;
  91857. }
  91858. if (pa === p2 && pb === p0 || pa === p0 && pb === p2) {
  91859. return 2;
  91860. }
  91861. return -1;
  91862. };
  91863. EdgesRenderer.prototype._processEdgeForAdjacenciesWithVertices = function (pa, pb, p0, p1, p2) {
  91864. if (pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p1) || pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p0)) {
  91865. return 0;
  91866. }
  91867. if (pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p2) || pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p1)) {
  91868. return 1;
  91869. }
  91870. if (pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p0) || pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p2)) {
  91871. return 2;
  91872. }
  91873. return -1;
  91874. };
  91875. EdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  91876. var needToCreateLine;
  91877. if (edge === undefined) {
  91878. needToCreateLine = true;
  91879. }
  91880. else {
  91881. var dotProduct = BABYLON.Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]);
  91882. needToCreateLine = dotProduct < this._epsilon;
  91883. }
  91884. if (needToCreateLine) {
  91885. var offset = this._linesPositions.length / 3;
  91886. var normal = p0.subtract(p1);
  91887. normal.normalize();
  91888. // Positions
  91889. this._linesPositions.push(p0.x);
  91890. this._linesPositions.push(p0.y);
  91891. this._linesPositions.push(p0.z);
  91892. this._linesPositions.push(p0.x);
  91893. this._linesPositions.push(p0.y);
  91894. this._linesPositions.push(p0.z);
  91895. this._linesPositions.push(p1.x);
  91896. this._linesPositions.push(p1.y);
  91897. this._linesPositions.push(p1.z);
  91898. this._linesPositions.push(p1.x);
  91899. this._linesPositions.push(p1.y);
  91900. this._linesPositions.push(p1.z);
  91901. // Normals
  91902. this._linesNormals.push(p1.x);
  91903. this._linesNormals.push(p1.y);
  91904. this._linesNormals.push(p1.z);
  91905. this._linesNormals.push(-1);
  91906. this._linesNormals.push(p1.x);
  91907. this._linesNormals.push(p1.y);
  91908. this._linesNormals.push(p1.z);
  91909. this._linesNormals.push(1);
  91910. this._linesNormals.push(p0.x);
  91911. this._linesNormals.push(p0.y);
  91912. this._linesNormals.push(p0.z);
  91913. this._linesNormals.push(-1);
  91914. this._linesNormals.push(p0.x);
  91915. this._linesNormals.push(p0.y);
  91916. this._linesNormals.push(p0.z);
  91917. this._linesNormals.push(1);
  91918. // Indices
  91919. this._linesIndices.push(offset);
  91920. this._linesIndices.push(offset + 1);
  91921. this._linesIndices.push(offset + 2);
  91922. this._linesIndices.push(offset);
  91923. this._linesIndices.push(offset + 2);
  91924. this._linesIndices.push(offset + 3);
  91925. }
  91926. };
  91927. EdgesRenderer.prototype._generateEdgesLines = function () {
  91928. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  91929. var indices = this._source.getIndices();
  91930. if (!indices || !positions) {
  91931. return;
  91932. }
  91933. // First let's find adjacencies
  91934. var adjacencies = new Array();
  91935. var faceNormals = new Array();
  91936. var index;
  91937. var faceAdjacencies;
  91938. // Prepare faces
  91939. for (index = 0; index < indices.length; index += 3) {
  91940. faceAdjacencies = new FaceAdjacencies();
  91941. var p0Index = indices[index];
  91942. var p1Index = indices[index + 1];
  91943. var p2Index = indices[index + 2];
  91944. faceAdjacencies.p0 = new BABYLON.Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);
  91945. faceAdjacencies.p1 = new BABYLON.Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);
  91946. faceAdjacencies.p2 = new BABYLON.Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);
  91947. var faceNormal = BABYLON.Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1));
  91948. faceNormal.normalize();
  91949. faceNormals.push(faceNormal);
  91950. adjacencies.push(faceAdjacencies);
  91951. }
  91952. // Scan
  91953. for (index = 0; index < adjacencies.length; index++) {
  91954. faceAdjacencies = adjacencies[index];
  91955. for (var otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) {
  91956. var otherFaceAdjacencies = adjacencies[otherIndex];
  91957. if (faceAdjacencies.edgesConnectedCount === 3) { // Full
  91958. break;
  91959. }
  91960. if (otherFaceAdjacencies.edgesConnectedCount === 3) { // Full
  91961. continue;
  91962. }
  91963. var otherP0 = indices[otherIndex * 3];
  91964. var otherP1 = indices[otherIndex * 3 + 1];
  91965. var otherP2 = indices[otherIndex * 3 + 2];
  91966. for (var edgeIndex = 0; edgeIndex < 3; edgeIndex++) {
  91967. var otherEdgeIndex = 0;
  91968. if (faceAdjacencies.edges[edgeIndex] !== undefined) {
  91969. continue;
  91970. }
  91971. switch (edgeIndex) {
  91972. case 0:
  91973. if (this._checkVerticesInsteadOfIndices) {
  91974. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  91975. }
  91976. else {
  91977. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2);
  91978. }
  91979. break;
  91980. case 1:
  91981. if (this._checkVerticesInsteadOfIndices) {
  91982. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  91983. }
  91984. else {
  91985. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2);
  91986. }
  91987. break;
  91988. case 2:
  91989. if (this._checkVerticesInsteadOfIndices) {
  91990. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  91991. }
  91992. else {
  91993. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2);
  91994. }
  91995. break;
  91996. }
  91997. if (otherEdgeIndex === -1) {
  91998. continue;
  91999. }
  92000. faceAdjacencies.edges[edgeIndex] = otherIndex;
  92001. otherFaceAdjacencies.edges[otherEdgeIndex] = index;
  92002. faceAdjacencies.edgesConnectedCount++;
  92003. otherFaceAdjacencies.edgesConnectedCount++;
  92004. if (faceAdjacencies.edgesConnectedCount === 3) {
  92005. break;
  92006. }
  92007. }
  92008. }
  92009. }
  92010. // Create lines
  92011. for (index = 0; index < adjacencies.length; index++) {
  92012. // 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
  92013. var current = adjacencies[index];
  92014. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  92015. this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2);
  92016. this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0);
  92017. }
  92018. // Merge into a single mesh
  92019. var engine = this._source.getScene().getEngine();
  92020. this._buffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  92021. this._buffers[BABYLON.VertexBuffer.NormalKind] = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  92022. this._ib = engine.createIndexBuffer(this._linesIndices);
  92023. this._indicesCount = this._linesIndices.length;
  92024. };
  92025. EdgesRenderer.prototype.render = function () {
  92026. var scene = this._source.getScene();
  92027. if (!this._lineShader.isReady() || !scene.activeCamera) {
  92028. return;
  92029. }
  92030. var engine = scene.getEngine();
  92031. this._lineShader._preBind();
  92032. // VBOs
  92033. engine.bindBuffers(this._buffers, this._ib, this._lineShader.getEffect());
  92034. scene.resetCachedMaterial();
  92035. this._lineShader.setColor4("color", this._source.edgesColor);
  92036. if (scene.activeCamera.mode === BABYLON.Camera.ORTHOGRAPHIC_CAMERA) {
  92037. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForOrthographic);
  92038. }
  92039. else {
  92040. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForPerspective);
  92041. }
  92042. this._lineShader.setFloat("aspectRatio", engine.getAspectRatio(scene.activeCamera));
  92043. this._lineShader.bind(this._source.getWorldMatrix());
  92044. // Draw order
  92045. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._indicesCount);
  92046. this._lineShader.unbind();
  92047. engine.setDepthWrite(true);
  92048. };
  92049. return EdgesRenderer;
  92050. }());
  92051. BABYLON.EdgesRenderer = EdgesRenderer;
  92052. })(BABYLON || (BABYLON = {}));
  92053. //# sourceMappingURL=babylon.edgesRenderer.js.map
  92054. var __assign = (this && this.__assign) || Object.assign || function(t) {
  92055. for (var s, i = 1, n = arguments.length; i < n; i++) {
  92056. s = arguments[i];
  92057. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  92058. t[p] = s[p];
  92059. }
  92060. return t;
  92061. };
  92062. var BABYLON;
  92063. (function (BABYLON) {
  92064. /**
  92065. * The effect layer Helps adding post process effect blended with the main pass.
  92066. *
  92067. * This can be for instance use to generate glow or higlight effects on the scene.
  92068. *
  92069. * The effect layer class can not be used directly and is intented to inherited from to be
  92070. * customized per effects.
  92071. */
  92072. var EffectLayer = /** @class */ (function () {
  92073. /**
  92074. * Instantiates a new effect Layer and references it in the scene.
  92075. * @param name The name of the layer
  92076. * @param scene The scene to use the layer in
  92077. */
  92078. function EffectLayer(
  92079. /** The Friendly of the effect in the scene */
  92080. name, scene) {
  92081. this._vertexBuffers = {};
  92082. this._maxSize = 0;
  92083. this._mainTextureDesiredSize = { width: 0, height: 0 };
  92084. this._shouldRender = true;
  92085. this._postProcesses = [];
  92086. this._textures = [];
  92087. this._emissiveTextureAndColor = { texture: null, color: new BABYLON.Color4() };
  92088. /**
  92089. * The clear color of the texture used to generate the glow map.
  92090. */
  92091. this.neutralColor = new BABYLON.Color4();
  92092. /**
  92093. * Specifies wether the highlight layer is enabled or not.
  92094. */
  92095. this.isEnabled = true;
  92096. /**
  92097. * An event triggered when the effect layer has been disposed.
  92098. */
  92099. this.onDisposeObservable = new BABYLON.Observable();
  92100. /**
  92101. * An event triggered when the effect layer is about rendering the main texture with the glowy parts.
  92102. */
  92103. this.onBeforeRenderMainTextureObservable = new BABYLON.Observable();
  92104. /**
  92105. * An event triggered when the generated texture is being merged in the scene.
  92106. */
  92107. this.onBeforeComposeObservable = new BABYLON.Observable();
  92108. /**
  92109. * An event triggered when the generated texture has been merged in the scene.
  92110. */
  92111. this.onAfterComposeObservable = new BABYLON.Observable();
  92112. /**
  92113. * An event triggered when the efffect layer changes its size.
  92114. */
  92115. this.onSizeChangedObservable = new BABYLON.Observable();
  92116. this.name = name;
  92117. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  92118. this._engine = scene.getEngine();
  92119. this._maxSize = this._engine.getCaps().maxTextureSize;
  92120. this._scene.effectLayers.push(this);
  92121. // Generate Buffers
  92122. this._generateIndexBuffer();
  92123. this._genrateVertexBuffer();
  92124. }
  92125. Object.defineProperty(EffectLayer.prototype, "camera", {
  92126. /**
  92127. * Gets the camera attached to the layer.
  92128. */
  92129. get: function () {
  92130. return this._effectLayerOptions.camera;
  92131. },
  92132. enumerable: true,
  92133. configurable: true
  92134. });
  92135. /**
  92136. * Initializes the effect layer with the required options.
  92137. * @param options Sets of none mandatory options to use with the layer (see IEffectLayerOptions for more information)
  92138. */
  92139. EffectLayer.prototype._init = function (options) {
  92140. // Adapt options
  92141. this._effectLayerOptions = __assign({ mainTextureRatio: 0.5, alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE, camera: null }, options);
  92142. this._setMainTextureSize();
  92143. this._createMainTexture();
  92144. this._createTextureAndPostProcesses();
  92145. this._mergeEffect = this._createMergeEffect();
  92146. };
  92147. /**
  92148. * Generates the index buffer of the full screen quad blending to the main canvas.
  92149. */
  92150. EffectLayer.prototype._generateIndexBuffer = function () {
  92151. // Indices
  92152. var indices = [];
  92153. indices.push(0);
  92154. indices.push(1);
  92155. indices.push(2);
  92156. indices.push(0);
  92157. indices.push(2);
  92158. indices.push(3);
  92159. this._indexBuffer = this._engine.createIndexBuffer(indices);
  92160. };
  92161. /**
  92162. * Generates the vertex buffer of the full screen quad blending to the main canvas.
  92163. */
  92164. EffectLayer.prototype._genrateVertexBuffer = function () {
  92165. // VBO
  92166. var vertices = [];
  92167. vertices.push(1, 1);
  92168. vertices.push(-1, 1);
  92169. vertices.push(-1, -1);
  92170. vertices.push(1, -1);
  92171. var vertexBuffer = new BABYLON.VertexBuffer(this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  92172. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  92173. };
  92174. /**
  92175. * Sets the main texture desired size which is the closest power of two
  92176. * of the engine canvas size.
  92177. */
  92178. EffectLayer.prototype._setMainTextureSize = function () {
  92179. if (this._effectLayerOptions.mainTextureFixedSize) {
  92180. this._mainTextureDesiredSize.width = this._effectLayerOptions.mainTextureFixedSize;
  92181. this._mainTextureDesiredSize.height = this._effectLayerOptions.mainTextureFixedSize;
  92182. }
  92183. else {
  92184. this._mainTextureDesiredSize.width = this._engine.getRenderWidth() * this._effectLayerOptions.mainTextureRatio;
  92185. this._mainTextureDesiredSize.height = this._engine.getRenderHeight() * this._effectLayerOptions.mainTextureRatio;
  92186. this._mainTextureDesiredSize.width = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.width, this._maxSize) : this._mainTextureDesiredSize.width;
  92187. this._mainTextureDesiredSize.height = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.height, this._maxSize) : this._mainTextureDesiredSize.height;
  92188. }
  92189. this._mainTextureDesiredSize.width = Math.floor(this._mainTextureDesiredSize.width);
  92190. this._mainTextureDesiredSize.height = Math.floor(this._mainTextureDesiredSize.height);
  92191. };
  92192. /**
  92193. * Creates the main texture for the effect layer.
  92194. */
  92195. EffectLayer.prototype._createMainTexture = function () {
  92196. var _this = this;
  92197. this._mainTexture = new BABYLON.RenderTargetTexture("HighlightLayerMainRTT", {
  92198. width: this._mainTextureDesiredSize.width,
  92199. height: this._mainTextureDesiredSize.height
  92200. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  92201. this._mainTexture.activeCamera = this._effectLayerOptions.camera;
  92202. this._mainTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  92203. this._mainTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  92204. this._mainTexture.anisotropicFilteringLevel = 1;
  92205. this._mainTexture.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  92206. this._mainTexture.renderParticles = false;
  92207. this._mainTexture.renderList = null;
  92208. this._mainTexture.ignoreCameraViewport = true;
  92209. // Custom render function
  92210. this._mainTexture.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  92211. _this.onBeforeRenderMainTextureObservable.notifyObservers(_this);
  92212. var index;
  92213. var engine = _this._scene.getEngine();
  92214. if (depthOnlySubMeshes.length) {
  92215. engine.setColorWrite(false);
  92216. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  92217. _this._renderSubMesh(depthOnlySubMeshes.data[index]);
  92218. }
  92219. engine.setColorWrite(true);
  92220. }
  92221. for (index = 0; index < opaqueSubMeshes.length; index++) {
  92222. _this._renderSubMesh(opaqueSubMeshes.data[index]);
  92223. }
  92224. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  92225. _this._renderSubMesh(alphaTestSubMeshes.data[index]);
  92226. }
  92227. for (index = 0; index < transparentSubMeshes.length; index++) {
  92228. _this._renderSubMesh(transparentSubMeshes.data[index]);
  92229. }
  92230. };
  92231. this._mainTexture.onClearObservable.add(function (engine) {
  92232. engine.clear(_this.neutralColor, true, true, true);
  92233. });
  92234. };
  92235. /**
  92236. * Checks for the readiness of the element composing the layer.
  92237. * @param subMesh the mesh to check for
  92238. * @param useInstances specify wether or not to use instances to render the mesh
  92239. * @param emissiveTexture the associated emissive texture used to generate the glow
  92240. * @return true if ready otherwise, false
  92241. */
  92242. EffectLayer.prototype._isReady = function (subMesh, useInstances, emissiveTexture) {
  92243. var material = subMesh.getMaterial();
  92244. if (!material) {
  92245. return false;
  92246. }
  92247. if (!material.isReady(subMesh.getMesh(), useInstances)) {
  92248. return false;
  92249. }
  92250. var defines = [];
  92251. var attribs = [BABYLON.VertexBuffer.PositionKind];
  92252. var mesh = subMesh.getMesh();
  92253. var uv1 = false;
  92254. var uv2 = false;
  92255. // Alpha test
  92256. if (material && material.needAlphaTesting()) {
  92257. var alphaTexture = material.getAlphaTestTexture();
  92258. if (alphaTexture) {
  92259. defines.push("#define ALPHATEST");
  92260. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  92261. alphaTexture.coordinatesIndex === 1) {
  92262. defines.push("#define DIFFUSEUV2");
  92263. uv2 = true;
  92264. }
  92265. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  92266. defines.push("#define DIFFUSEUV1");
  92267. uv1 = true;
  92268. }
  92269. }
  92270. }
  92271. // Emissive
  92272. if (emissiveTexture) {
  92273. defines.push("#define EMISSIVE");
  92274. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  92275. emissiveTexture.coordinatesIndex === 1) {
  92276. defines.push("#define EMISSIVEUV2");
  92277. uv2 = true;
  92278. }
  92279. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  92280. defines.push("#define EMISSIVEUV1");
  92281. uv1 = true;
  92282. }
  92283. }
  92284. if (uv1) {
  92285. attribs.push(BABYLON.VertexBuffer.UVKind);
  92286. defines.push("#define UV1");
  92287. }
  92288. if (uv2) {
  92289. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  92290. defines.push("#define UV2");
  92291. }
  92292. // Bones
  92293. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  92294. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  92295. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  92296. if (mesh.numBoneInfluencers > 4) {
  92297. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  92298. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  92299. }
  92300. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  92301. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  92302. }
  92303. else {
  92304. defines.push("#define NUM_BONE_INFLUENCERS 0");
  92305. }
  92306. // Morph targets
  92307. var manager = mesh.morphTargetManager;
  92308. var morphInfluencers = 0;
  92309. if (manager) {
  92310. if (manager.numInfluencers > 0) {
  92311. defines.push("#define MORPHTARGETS");
  92312. morphInfluencers = manager.numInfluencers;
  92313. defines.push("#define NUM_MORPH_INFLUENCERS " + morphInfluencers);
  92314. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, { "NUM_MORPH_INFLUENCERS": morphInfluencers });
  92315. }
  92316. }
  92317. // Instances
  92318. if (useInstances) {
  92319. defines.push("#define INSTANCES");
  92320. attribs.push("world0");
  92321. attribs.push("world1");
  92322. attribs.push("world2");
  92323. attribs.push("world3");
  92324. }
  92325. // Get correct effect
  92326. var join = defines.join("\n");
  92327. if (this._cachedDefines !== join) {
  92328. this._cachedDefines = join;
  92329. this._effectLayerMapGenerationEffect = this._scene.getEngine().createEffect("glowMapGeneration", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "color", "emissiveMatrix", "morphTargetInfluences"], ["diffuseSampler", "emissiveSampler"], join, undefined, undefined, undefined, { maxSimultaneousMorphTargets: morphInfluencers });
  92330. }
  92331. return this._effectLayerMapGenerationEffect.isReady();
  92332. };
  92333. /**
  92334. * Renders the glowing part of the scene by blending the blurred glowing meshes on top of the rendered scene.
  92335. */
  92336. EffectLayer.prototype.render = function () {
  92337. var currentEffect = this._mergeEffect;
  92338. // Check
  92339. if (!currentEffect.isReady())
  92340. return;
  92341. for (var i = 0; i < this._postProcesses.length; i++) {
  92342. if (!this._postProcesses[i].isReady()) {
  92343. return;
  92344. }
  92345. }
  92346. var engine = this._scene.getEngine();
  92347. this.onBeforeComposeObservable.notifyObservers(this);
  92348. // Render
  92349. engine.enableEffect(currentEffect);
  92350. engine.setState(false);
  92351. // VBOs
  92352. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  92353. // Cache
  92354. var previousAlphaMode = engine.getAlphaMode();
  92355. // Go Blend.
  92356. engine.setAlphaMode(this._effectLayerOptions.alphaBlendingMode);
  92357. // Blends the map on the main canvas.
  92358. this._internalRender(currentEffect);
  92359. // Restore Alpha
  92360. engine.setAlphaMode(previousAlphaMode);
  92361. this.onAfterComposeObservable.notifyObservers(this);
  92362. // Handle size changes.
  92363. var size = this._mainTexture.getSize();
  92364. this._setMainTextureSize();
  92365. if (size.width !== this._mainTextureDesiredSize.width || size.height !== this._mainTextureDesiredSize.height) {
  92366. // Recreate RTT and post processes on size change.
  92367. this.onSizeChangedObservable.notifyObservers(this);
  92368. this._disposeTextureAndPostProcesses();
  92369. this._createMainTexture();
  92370. this._createTextureAndPostProcesses();
  92371. }
  92372. };
  92373. /**
  92374. * Determine if a given mesh will be used in the current effect.
  92375. * @param mesh mesh to test
  92376. * @returns true if the mesh will be used
  92377. */
  92378. EffectLayer.prototype.hasMesh = function (mesh) {
  92379. return true;
  92380. };
  92381. /**
  92382. * Returns true if the layer contains information to display, otherwise false.
  92383. * @returns true if the glow layer should be rendered
  92384. */
  92385. EffectLayer.prototype.shouldRender = function () {
  92386. return this.isEnabled && this._shouldRender;
  92387. };
  92388. /**
  92389. * Returns true if the mesh should render, otherwise false.
  92390. * @param mesh The mesh to render
  92391. * @returns true if it should render otherwise false
  92392. */
  92393. EffectLayer.prototype._shouldRenderMesh = function (mesh) {
  92394. return true;
  92395. };
  92396. /**
  92397. * Returns true if the mesh should render, otherwise false.
  92398. * @param mesh The mesh to render
  92399. * @returns true if it should render otherwise false
  92400. */
  92401. EffectLayer.prototype._shouldRenderEmissiveTextureForMesh = function (mesh) {
  92402. return true;
  92403. };
  92404. /**
  92405. * Renders the submesh passed in parameter to the generation map.
  92406. */
  92407. EffectLayer.prototype._renderSubMesh = function (subMesh) {
  92408. var _this = this;
  92409. if (!this.shouldRender()) {
  92410. return;
  92411. }
  92412. var material = subMesh.getMaterial();
  92413. var mesh = subMesh.getRenderingMesh();
  92414. var scene = this._scene;
  92415. var engine = scene.getEngine();
  92416. if (!material) {
  92417. return;
  92418. }
  92419. // Do not block in blend mode.
  92420. if (material.needAlphaBlendingForMesh(mesh)) {
  92421. return;
  92422. }
  92423. // Culling
  92424. engine.setState(material.backFaceCulling);
  92425. // Managing instances
  92426. var batch = mesh._getInstancesRenderList(subMesh._id);
  92427. if (batch.mustReturn) {
  92428. return;
  92429. }
  92430. // Early Exit per mesh
  92431. if (!this._shouldRenderMesh(mesh)) {
  92432. return;
  92433. }
  92434. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  92435. this._setEmissiveTextureAndColor(mesh, subMesh, material);
  92436. if (this._isReady(subMesh, hardwareInstancedRendering, this._emissiveTextureAndColor.texture)) {
  92437. engine.enableEffect(this._effectLayerMapGenerationEffect);
  92438. mesh._bind(subMesh, this._effectLayerMapGenerationEffect, BABYLON.Material.TriangleFillMode);
  92439. this._effectLayerMapGenerationEffect.setMatrix("viewProjection", scene.getTransformMatrix());
  92440. this._effectLayerMapGenerationEffect.setFloat4("color", this._emissiveTextureAndColor.color.r, this._emissiveTextureAndColor.color.g, this._emissiveTextureAndColor.color.b, this._emissiveTextureAndColor.color.a);
  92441. // Alpha test
  92442. if (material && material.needAlphaTesting()) {
  92443. var alphaTexture = material.getAlphaTestTexture();
  92444. if (alphaTexture) {
  92445. this._effectLayerMapGenerationEffect.setTexture("diffuseSampler", alphaTexture);
  92446. var textureMatrix = alphaTexture.getTextureMatrix();
  92447. if (textureMatrix) {
  92448. this._effectLayerMapGenerationEffect.setMatrix("diffuseMatrix", textureMatrix);
  92449. }
  92450. }
  92451. }
  92452. // Glow emissive only
  92453. if (this._emissiveTextureAndColor.texture) {
  92454. this._effectLayerMapGenerationEffect.setTexture("emissiveSampler", this._emissiveTextureAndColor.texture);
  92455. this._effectLayerMapGenerationEffect.setMatrix("emissiveMatrix", this._emissiveTextureAndColor.texture.getTextureMatrix());
  92456. }
  92457. // Bones
  92458. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  92459. this._effectLayerMapGenerationEffect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  92460. }
  92461. // Morph targets
  92462. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._effectLayerMapGenerationEffect);
  92463. // Draw
  92464. mesh._processRendering(subMesh, this._effectLayerMapGenerationEffect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effectLayerMapGenerationEffect.setMatrix("world", world); });
  92465. }
  92466. else {
  92467. // Need to reset refresh rate of the shadowMap
  92468. this._mainTexture.resetRefreshCounter();
  92469. }
  92470. };
  92471. /**
  92472. * Rebuild the required buffers.
  92473. * @hidden Internal use only.
  92474. */
  92475. EffectLayer.prototype._rebuild = function () {
  92476. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  92477. if (vb) {
  92478. vb._rebuild();
  92479. }
  92480. this._generateIndexBuffer();
  92481. };
  92482. /**
  92483. * Dispose only the render target textures and post process.
  92484. */
  92485. EffectLayer.prototype._disposeTextureAndPostProcesses = function () {
  92486. this._mainTexture.dispose();
  92487. for (var i = 0; i < this._postProcesses.length; i++) {
  92488. if (this._postProcesses[i]) {
  92489. this._postProcesses[i].dispose();
  92490. }
  92491. }
  92492. this._postProcesses = [];
  92493. for (var i = 0; i < this._textures.length; i++) {
  92494. if (this._textures[i]) {
  92495. this._textures[i].dispose();
  92496. }
  92497. }
  92498. this._textures = [];
  92499. };
  92500. /**
  92501. * Dispose the highlight layer and free resources.
  92502. */
  92503. EffectLayer.prototype.dispose = function () {
  92504. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  92505. if (vertexBuffer) {
  92506. vertexBuffer.dispose();
  92507. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  92508. }
  92509. if (this._indexBuffer) {
  92510. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  92511. this._indexBuffer = null;
  92512. }
  92513. // Clean textures and post processes
  92514. this._disposeTextureAndPostProcesses();
  92515. // Remove from scene
  92516. var index = this._scene.effectLayers.indexOf(this, 0);
  92517. if (index > -1) {
  92518. this._scene.effectLayers.splice(index, 1);
  92519. }
  92520. // Callback
  92521. this.onDisposeObservable.notifyObservers(this);
  92522. this.onDisposeObservable.clear();
  92523. this.onBeforeRenderMainTextureObservable.clear();
  92524. this.onBeforeComposeObservable.clear();
  92525. this.onAfterComposeObservable.clear();
  92526. this.onSizeChangedObservable.clear();
  92527. };
  92528. /**
  92529. * Gets the class name of the effect layer
  92530. * @returns the string with the class name of the effect layer
  92531. */
  92532. EffectLayer.prototype.getClassName = function () {
  92533. return "EffectLayer";
  92534. };
  92535. /**
  92536. * Creates an effect layer from parsed effect layer data
  92537. * @param parsedEffectLayer defines effect layer data
  92538. * @param scene defines the current scene
  92539. * @param rootUrl defines the root URL containing the effect layer information
  92540. * @returns a parsed effect Layer
  92541. */
  92542. EffectLayer.Parse = function (parsedEffectLayer, scene, rootUrl) {
  92543. var effectLayerType = BABYLON.Tools.Instantiate(parsedEffectLayer.customType);
  92544. return effectLayerType.Parse(parsedEffectLayer, scene, rootUrl);
  92545. };
  92546. __decorate([
  92547. BABYLON.serialize()
  92548. ], EffectLayer.prototype, "name", void 0);
  92549. __decorate([
  92550. BABYLON.serializeAsColor4()
  92551. ], EffectLayer.prototype, "neutralColor", void 0);
  92552. __decorate([
  92553. BABYLON.serialize()
  92554. ], EffectLayer.prototype, "isEnabled", void 0);
  92555. __decorate([
  92556. BABYLON.serializeAsCameraReference()
  92557. ], EffectLayer.prototype, "camera", null);
  92558. return EffectLayer;
  92559. }());
  92560. BABYLON.EffectLayer = EffectLayer;
  92561. })(BABYLON || (BABYLON = {}));
  92562. //# sourceMappingURL=babylon.effectLayer.js.map
  92563. var BABYLON;
  92564. (function (BABYLON) {
  92565. /**
  92566. * Special Glow Blur post process only blurring the alpha channel
  92567. * It enforces keeping the most luminous color in the color channel.
  92568. */
  92569. var GlowBlurPostProcess = /** @class */ (function (_super) {
  92570. __extends(GlowBlurPostProcess, _super);
  92571. function GlowBlurPostProcess(name, direction, kernel, options, camera, samplingMode, engine, reusable) {
  92572. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  92573. var _this = _super.call(this, name, "glowBlurPostProcess", ["screenSize", "direction", "blurWidth"], null, options, camera, samplingMode, engine, reusable) || this;
  92574. _this.direction = direction;
  92575. _this.kernel = kernel;
  92576. _this.onApplyObservable.add(function (effect) {
  92577. effect.setFloat2("screenSize", _this.width, _this.height);
  92578. effect.setVector2("direction", _this.direction);
  92579. effect.setFloat("blurWidth", _this.kernel);
  92580. });
  92581. return _this;
  92582. }
  92583. return GlowBlurPostProcess;
  92584. }(BABYLON.PostProcess));
  92585. /**
  92586. * The highlight layer Helps adding a glow effect around a mesh.
  92587. *
  92588. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  92589. * glowy meshes to your scene.
  92590. *
  92591. * !!! THIS REQUIRES AN ACTIVE STENCIL BUFFER ON THE CANVAS !!!
  92592. */
  92593. var HighlightLayer = /** @class */ (function (_super) {
  92594. __extends(HighlightLayer, _super);
  92595. /**
  92596. * Instantiates a new highlight Layer and references it to the scene..
  92597. * @param name The name of the layer
  92598. * @param scene The scene to use the layer in
  92599. * @param options Sets of none mandatory options to use with the layer (see IHighlightLayerOptions for more information)
  92600. */
  92601. function HighlightLayer(name, scene, options) {
  92602. var _this = _super.call(this, name, scene) || this;
  92603. _this.name = name;
  92604. /**
  92605. * Specifies whether or not the inner glow is ACTIVE in the layer.
  92606. */
  92607. _this.innerGlow = true;
  92608. /**
  92609. * Specifies whether or not the outer glow is ACTIVE in the layer.
  92610. */
  92611. _this.outerGlow = true;
  92612. /**
  92613. * An event triggered when the highlight layer is being blurred.
  92614. */
  92615. _this.onBeforeBlurObservable = new BABYLON.Observable();
  92616. /**
  92617. * An event triggered when the highlight layer has been blurred.
  92618. */
  92619. _this.onAfterBlurObservable = new BABYLON.Observable();
  92620. _this._instanceGlowingMeshStencilReference = HighlightLayer.GlowingMeshStencilReference++;
  92621. _this._meshes = {};
  92622. _this._excludedMeshes = {};
  92623. _this.neutralColor = HighlightLayer.NeutralColor;
  92624. // Warn on stencil
  92625. if (!_this._engine.isStencilEnable) {
  92626. 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 }");
  92627. }
  92628. // Adapt options
  92629. _this._options = __assign({ mainTextureRatio: 0.5, blurTextureSizeRatio: 0.5, blurHorizontalSize: 1.0, blurVerticalSize: 1.0, alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE, camera: null }, options);
  92630. // Initialize the layer
  92631. _this._init({
  92632. alphaBlendingMode: _this._options.alphaBlendingMode,
  92633. camera: _this._options.camera,
  92634. mainTextureFixedSize: _this._options.mainTextureFixedSize,
  92635. mainTextureRatio: _this._options.mainTextureRatio
  92636. });
  92637. // Do not render as long as no meshes have been added
  92638. _this._shouldRender = false;
  92639. return _this;
  92640. }
  92641. Object.defineProperty(HighlightLayer.prototype, "blurHorizontalSize", {
  92642. /**
  92643. * Gets the horizontal size of the blur.
  92644. */
  92645. get: function () {
  92646. return this._horizontalBlurPostprocess.kernel;
  92647. },
  92648. /**
  92649. * Specifies the horizontal size of the blur.
  92650. */
  92651. set: function (value) {
  92652. this._horizontalBlurPostprocess.kernel = value;
  92653. },
  92654. enumerable: true,
  92655. configurable: true
  92656. });
  92657. Object.defineProperty(HighlightLayer.prototype, "blurVerticalSize", {
  92658. /**
  92659. * Gets the vertical size of the blur.
  92660. */
  92661. get: function () {
  92662. return this._verticalBlurPostprocess.kernel;
  92663. },
  92664. /**
  92665. * Specifies the vertical size of the blur.
  92666. */
  92667. set: function (value) {
  92668. this._verticalBlurPostprocess.kernel = value;
  92669. },
  92670. enumerable: true,
  92671. configurable: true
  92672. });
  92673. /**
  92674. * Get the effect name of the layer.
  92675. * @return The effect name
  92676. */
  92677. HighlightLayer.prototype.getEffectName = function () {
  92678. return HighlightLayer.EffectName;
  92679. };
  92680. /**
  92681. * Create the merge effect. This is the shader use to blit the information back
  92682. * to the main canvas at the end of the scene rendering.
  92683. */
  92684. HighlightLayer.prototype._createMergeEffect = function () {
  92685. // Effect
  92686. return this._engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler"], this._options.isStroke ? "#define STROKE \n" : undefined);
  92687. };
  92688. /**
  92689. * Creates the render target textures and post processes used in the highlight layer.
  92690. */
  92691. HighlightLayer.prototype._createTextureAndPostProcesses = function () {
  92692. var _this = this;
  92693. var blurTextureWidth = this._mainTextureDesiredSize.width * this._options.blurTextureSizeRatio;
  92694. var blurTextureHeight = this._mainTextureDesiredSize.height * this._options.blurTextureSizeRatio;
  92695. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  92696. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  92697. var textureType = 0;
  92698. if (this._engine.getCaps().textureHalfFloatRender) {
  92699. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  92700. }
  92701. else {
  92702. textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  92703. }
  92704. this._blurTexture = new BABYLON.RenderTargetTexture("HighlightLayerBlurRTT", {
  92705. width: blurTextureWidth,
  92706. height: blurTextureHeight
  92707. }, this._scene, false, true, textureType);
  92708. this._blurTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  92709. this._blurTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  92710. this._blurTexture.anisotropicFilteringLevel = 16;
  92711. this._blurTexture.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  92712. this._blurTexture.renderParticles = false;
  92713. this._blurTexture.ignoreCameraViewport = true;
  92714. this._textures = [this._blurTexture];
  92715. if (this._options.alphaBlendingMode === BABYLON.Engine.ALPHA_COMBINE) {
  92716. this._downSamplePostprocess = new BABYLON.PassPostProcess("HighlightLayerPPP", this._options.blurTextureSizeRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  92717. this._downSamplePostprocess.onApplyObservable.add(function (effect) {
  92718. effect.setTexture("textureSampler", _this._mainTexture);
  92719. });
  92720. this._horizontalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  92721. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  92722. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  92723. });
  92724. this._verticalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  92725. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  92726. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  92727. });
  92728. this._postProcesses = [this._downSamplePostprocess, this._horizontalBlurPostprocess, this._verticalBlurPostprocess];
  92729. }
  92730. else {
  92731. this._horizontalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize / 2, {
  92732. width: blurTextureWidth,
  92733. height: blurTextureHeight
  92734. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  92735. this._horizontalBlurPostprocess.width = blurTextureWidth;
  92736. this._horizontalBlurPostprocess.height = blurTextureHeight;
  92737. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  92738. effect.setTexture("textureSampler", _this._mainTexture);
  92739. });
  92740. this._verticalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize / 2, {
  92741. width: blurTextureWidth,
  92742. height: blurTextureHeight
  92743. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  92744. this._postProcesses = [this._horizontalBlurPostprocess, this._verticalBlurPostprocess];
  92745. }
  92746. this._mainTexture.onAfterUnbindObservable.add(function () {
  92747. _this.onBeforeBlurObservable.notifyObservers(_this);
  92748. var internalTexture = _this._blurTexture.getInternalTexture();
  92749. if (internalTexture) {
  92750. _this._scene.postProcessManager.directRender(_this._postProcesses, internalTexture, true);
  92751. }
  92752. _this.onAfterBlurObservable.notifyObservers(_this);
  92753. });
  92754. // Prevent autoClear.
  92755. this._postProcesses.map(function (pp) { pp.autoClear = false; });
  92756. };
  92757. /**
  92758. * Returns wether or nood the layer needs stencil enabled during the mesh rendering.
  92759. */
  92760. HighlightLayer.prototype.needStencil = function () {
  92761. return true;
  92762. };
  92763. /**
  92764. * Checks for the readiness of the element composing the layer.
  92765. * @param subMesh the mesh to check for
  92766. * @param useInstances specify wether or not to use instances to render the mesh
  92767. * @param emissiveTexture the associated emissive texture used to generate the glow
  92768. * @return true if ready otherwise, false
  92769. */
  92770. HighlightLayer.prototype.isReady = function (subMesh, useInstances) {
  92771. var material = subMesh.getMaterial();
  92772. var mesh = subMesh.getRenderingMesh();
  92773. if (!material || !mesh || !this._meshes) {
  92774. return false;
  92775. }
  92776. var emissiveTexture = null;
  92777. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  92778. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  92779. emissiveTexture = material.emissiveTexture;
  92780. }
  92781. return _super.prototype._isReady.call(this, subMesh, useInstances, emissiveTexture);
  92782. };
  92783. /**
  92784. * Implementation specific of rendering the generating effect on the main canvas.
  92785. * @param effect The effect used to render through
  92786. */
  92787. HighlightLayer.prototype._internalRender = function (effect) {
  92788. // Texture
  92789. effect.setTexture("textureSampler", this._blurTexture);
  92790. // Cache
  92791. var engine = this._engine;
  92792. var previousStencilBuffer = engine.getStencilBuffer();
  92793. var previousStencilFunction = engine.getStencilFunction();
  92794. var previousStencilMask = engine.getStencilMask();
  92795. var previousStencilOperationPass = engine.getStencilOperationPass();
  92796. var previousStencilOperationFail = engine.getStencilOperationFail();
  92797. var previousStencilOperationDepthFail = engine.getStencilOperationDepthFail();
  92798. var previousStencilReference = engine.getStencilFunctionReference();
  92799. // Stencil operations
  92800. engine.setStencilOperationPass(BABYLON.Engine.REPLACE);
  92801. engine.setStencilOperationFail(BABYLON.Engine.KEEP);
  92802. engine.setStencilOperationDepthFail(BABYLON.Engine.KEEP);
  92803. // Draw order
  92804. engine.setStencilMask(0x00);
  92805. engine.setStencilBuffer(true);
  92806. engine.setStencilFunctionReference(this._instanceGlowingMeshStencilReference);
  92807. // 2 passes inner outer
  92808. if (this.outerGlow) {
  92809. effect.setFloat("offset", 0);
  92810. engine.setStencilFunction(BABYLON.Engine.NOTEQUAL);
  92811. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  92812. }
  92813. if (this.innerGlow) {
  92814. effect.setFloat("offset", 1);
  92815. engine.setStencilFunction(BABYLON.Engine.EQUAL);
  92816. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  92817. }
  92818. // Restore Cache
  92819. engine.setStencilFunction(previousStencilFunction);
  92820. engine.setStencilMask(previousStencilMask);
  92821. engine.setStencilBuffer(previousStencilBuffer);
  92822. engine.setStencilOperationPass(previousStencilOperationPass);
  92823. engine.setStencilOperationFail(previousStencilOperationFail);
  92824. engine.setStencilOperationDepthFail(previousStencilOperationDepthFail);
  92825. engine.setStencilFunctionReference(previousStencilReference);
  92826. };
  92827. /**
  92828. * Returns true if the layer contains information to display, otherwise false.
  92829. */
  92830. HighlightLayer.prototype.shouldRender = function () {
  92831. if (_super.prototype.shouldRender.call(this)) {
  92832. return this._meshes ? true : false;
  92833. }
  92834. return false;
  92835. };
  92836. /**
  92837. * Returns true if the mesh should render, otherwise false.
  92838. * @param mesh The mesh to render
  92839. * @returns true if it should render otherwise false
  92840. */
  92841. HighlightLayer.prototype._shouldRenderMesh = function (mesh) {
  92842. // Excluded Mesh
  92843. if (this._excludedMeshes && this._excludedMeshes[mesh.uniqueId]) {
  92844. return false;
  92845. }
  92846. ;
  92847. return true;
  92848. };
  92849. /**
  92850. * Sets the required values for both the emissive texture and and the main color.
  92851. */
  92852. HighlightLayer.prototype._setEmissiveTextureAndColor = function (mesh, subMesh, material) {
  92853. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  92854. if (highlightLayerMesh) {
  92855. this._emissiveTextureAndColor.color.set(highlightLayerMesh.color.r, highlightLayerMesh.color.g, highlightLayerMesh.color.b, 1.0);
  92856. }
  92857. else {
  92858. this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);
  92859. }
  92860. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  92861. this._emissiveTextureAndColor.texture = material.emissiveTexture;
  92862. this._emissiveTextureAndColor.color.set(1.0, 1.0, 1.0, 1.0);
  92863. }
  92864. else {
  92865. this._emissiveTextureAndColor.texture = null;
  92866. }
  92867. };
  92868. /**
  92869. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the highlight layer.
  92870. * @param mesh The mesh to exclude from the highlight layer
  92871. */
  92872. HighlightLayer.prototype.addExcludedMesh = function (mesh) {
  92873. if (!this._excludedMeshes) {
  92874. return;
  92875. }
  92876. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  92877. if (!meshExcluded) {
  92878. this._excludedMeshes[mesh.uniqueId] = {
  92879. mesh: mesh,
  92880. beforeRender: mesh.onBeforeRenderObservable.add(function (mesh) {
  92881. mesh.getEngine().setStencilBuffer(false);
  92882. }),
  92883. afterRender: mesh.onAfterRenderObservable.add(function (mesh) {
  92884. mesh.getEngine().setStencilBuffer(true);
  92885. }),
  92886. };
  92887. }
  92888. };
  92889. /**
  92890. * Remove a mesh from the exclusion list to let it impact or being impacted by the highlight layer.
  92891. * @param mesh The mesh to highlight
  92892. */
  92893. HighlightLayer.prototype.removeExcludedMesh = function (mesh) {
  92894. if (!this._excludedMeshes) {
  92895. return;
  92896. }
  92897. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  92898. if (meshExcluded) {
  92899. if (meshExcluded.beforeRender) {
  92900. mesh.onBeforeRenderObservable.remove(meshExcluded.beforeRender);
  92901. }
  92902. if (meshExcluded.afterRender) {
  92903. mesh.onAfterRenderObservable.remove(meshExcluded.afterRender);
  92904. }
  92905. }
  92906. this._excludedMeshes[mesh.uniqueId] = null;
  92907. };
  92908. /**
  92909. * Determine if a given mesh will be highlighted by the current HighlightLayer
  92910. * @param mesh mesh to test
  92911. * @returns true if the mesh will be highlighted by the current HighlightLayer
  92912. */
  92913. HighlightLayer.prototype.hasMesh = function (mesh) {
  92914. if (!this._meshes) {
  92915. return false;
  92916. }
  92917. return this._meshes[mesh.uniqueId] !== undefined && this._meshes[mesh.uniqueId] !== null;
  92918. };
  92919. /**
  92920. * Add a mesh in the highlight layer in order to make it glow with the chosen color.
  92921. * @param mesh The mesh to highlight
  92922. * @param color The color of the highlight
  92923. * @param glowEmissiveOnly Extract the glow from the emissive texture
  92924. */
  92925. HighlightLayer.prototype.addMesh = function (mesh, color, glowEmissiveOnly) {
  92926. var _this = this;
  92927. if (glowEmissiveOnly === void 0) { glowEmissiveOnly = false; }
  92928. if (!this._meshes) {
  92929. return;
  92930. }
  92931. var meshHighlight = this._meshes[mesh.uniqueId];
  92932. if (meshHighlight) {
  92933. meshHighlight.color = color;
  92934. }
  92935. else {
  92936. this._meshes[mesh.uniqueId] = {
  92937. mesh: mesh,
  92938. color: color,
  92939. // Lambda required for capture due to Observable this context
  92940. observerHighlight: mesh.onBeforeRenderObservable.add(function (mesh) {
  92941. if (_this._excludedMeshes && _this._excludedMeshes[mesh.uniqueId]) {
  92942. _this._defaultStencilReference(mesh);
  92943. }
  92944. else {
  92945. mesh.getScene().getEngine().setStencilFunctionReference(_this._instanceGlowingMeshStencilReference);
  92946. }
  92947. }),
  92948. observerDefault: mesh.onAfterRenderObservable.add(this._defaultStencilReference),
  92949. glowEmissiveOnly: glowEmissiveOnly
  92950. };
  92951. }
  92952. this._shouldRender = true;
  92953. };
  92954. /**
  92955. * Remove a mesh from the highlight layer in order to make it stop glowing.
  92956. * @param mesh The mesh to highlight
  92957. */
  92958. HighlightLayer.prototype.removeMesh = function (mesh) {
  92959. if (!this._meshes) {
  92960. return;
  92961. }
  92962. var meshHighlight = this._meshes[mesh.uniqueId];
  92963. if (meshHighlight) {
  92964. if (meshHighlight.observerHighlight) {
  92965. mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  92966. }
  92967. if (meshHighlight.observerDefault) {
  92968. mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  92969. }
  92970. delete this._meshes[mesh.uniqueId];
  92971. }
  92972. this._shouldRender = false;
  92973. for (var meshHighlightToCheck in this._meshes) {
  92974. if (this._meshes[meshHighlightToCheck]) {
  92975. this._shouldRender = true;
  92976. break;
  92977. }
  92978. }
  92979. };
  92980. /**
  92981. * Force the stencil to the normal expected value for none glowing parts
  92982. */
  92983. HighlightLayer.prototype._defaultStencilReference = function (mesh) {
  92984. mesh.getScene().getEngine().setStencilFunctionReference(HighlightLayer.NormalMeshStencilReference);
  92985. };
  92986. /**
  92987. * Free any resources and references associated to a mesh.
  92988. * Internal use
  92989. * @param mesh The mesh to free.
  92990. */
  92991. HighlightLayer.prototype._disposeMesh = function (mesh) {
  92992. this.removeMesh(mesh);
  92993. this.removeExcludedMesh(mesh);
  92994. };
  92995. /**
  92996. * Dispose the highlight layer and free resources.
  92997. */
  92998. HighlightLayer.prototype.dispose = function () {
  92999. if (this._meshes) {
  93000. // Clean mesh references
  93001. for (var id in this._meshes) {
  93002. var meshHighlight = this._meshes[id];
  93003. if (meshHighlight && meshHighlight.mesh) {
  93004. if (meshHighlight.observerHighlight) {
  93005. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  93006. }
  93007. if (meshHighlight.observerDefault) {
  93008. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  93009. }
  93010. }
  93011. }
  93012. this._meshes = null;
  93013. }
  93014. if (this._excludedMeshes) {
  93015. for (var id in this._excludedMeshes) {
  93016. var meshHighlight = this._excludedMeshes[id];
  93017. if (meshHighlight) {
  93018. if (meshHighlight.beforeRender) {
  93019. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.beforeRender);
  93020. }
  93021. if (meshHighlight.afterRender) {
  93022. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.afterRender);
  93023. }
  93024. }
  93025. }
  93026. this._excludedMeshes = null;
  93027. }
  93028. _super.prototype.dispose.call(this);
  93029. };
  93030. /**
  93031. * Gets the class name of the effect layer
  93032. * @returns the string with the class name of the effect layer
  93033. */
  93034. HighlightLayer.prototype.getClassName = function () {
  93035. return "HighlightLayer";
  93036. };
  93037. /**
  93038. * Serializes this Highlight layer
  93039. * @returns a serialized Highlight layer object
  93040. */
  93041. HighlightLayer.prototype.serialize = function () {
  93042. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  93043. serializationObject.customType = "BABYLON.HighlightLayer";
  93044. // Highlighted meshes
  93045. serializationObject.meshes = [];
  93046. if (this._meshes) {
  93047. for (var m in this._meshes) {
  93048. var mesh = this._meshes[m];
  93049. if (mesh) {
  93050. serializationObject.meshes.push({
  93051. glowEmissiveOnly: mesh.glowEmissiveOnly,
  93052. color: mesh.color.asArray(),
  93053. meshId: mesh.mesh.id
  93054. });
  93055. }
  93056. }
  93057. }
  93058. // Excluded meshes
  93059. serializationObject.excludedMeshes = [];
  93060. if (this._excludedMeshes) {
  93061. for (var e in this._excludedMeshes) {
  93062. var excludedMesh = this._excludedMeshes[e];
  93063. if (excludedMesh) {
  93064. serializationObject.excludedMeshes.push(excludedMesh.mesh.id);
  93065. }
  93066. }
  93067. }
  93068. return serializationObject;
  93069. };
  93070. /**
  93071. * Creates a Highlight layer from parsed Highlight layer data
  93072. * @param parsedHightlightLayer defines the Highlight layer data
  93073. * @param scene defines the current scene
  93074. * @param rootUrl defines the root URL containing the Highlight layer information
  93075. * @returns a parsed Highlight layer
  93076. */
  93077. HighlightLayer.Parse = function (parsedHightlightLayer, scene, rootUrl) {
  93078. var hl = BABYLON.SerializationHelper.Parse(function () { return new HighlightLayer(parsedHightlightLayer.name, scene, parsedHightlightLayer.options); }, parsedHightlightLayer, scene, rootUrl);
  93079. var index;
  93080. // Excluded meshes
  93081. for (index = 0; index < parsedHightlightLayer.excludedMeshes.length; index++) {
  93082. var mesh = scene.getMeshByID(parsedHightlightLayer.excludedMeshes[index]);
  93083. if (mesh) {
  93084. hl.addExcludedMesh(mesh);
  93085. }
  93086. }
  93087. // Included meshes
  93088. for (index = 0; index < parsedHightlightLayer.meshes.length; index++) {
  93089. var highlightedMesh = parsedHightlightLayer.meshes[index];
  93090. var mesh = scene.getMeshByID(highlightedMesh.meshId);
  93091. if (mesh) {
  93092. hl.addMesh(mesh, BABYLON.Color3.FromArray(highlightedMesh.color), highlightedMesh.glowEmissiveOnly);
  93093. }
  93094. }
  93095. return hl;
  93096. };
  93097. /**
  93098. * Effect Name of the highlight layer.
  93099. */
  93100. HighlightLayer.EffectName = "HighlightLayer";
  93101. /**
  93102. * The neutral color used during the preparation of the glow effect.
  93103. * This is black by default as the blend operation is a blend operation.
  93104. */
  93105. HighlightLayer.NeutralColor = new BABYLON.Color4(0, 0, 0, 0);
  93106. /**
  93107. * Stencil value used for glowing meshes.
  93108. */
  93109. HighlightLayer.GlowingMeshStencilReference = 0x02;
  93110. /**
  93111. * Stencil value used for the other meshes in the scene.
  93112. */
  93113. HighlightLayer.NormalMeshStencilReference = 0x01;
  93114. __decorate([
  93115. BABYLON.serialize()
  93116. ], HighlightLayer.prototype, "innerGlow", void 0);
  93117. __decorate([
  93118. BABYLON.serialize()
  93119. ], HighlightLayer.prototype, "outerGlow", void 0);
  93120. __decorate([
  93121. BABYLON.serialize()
  93122. ], HighlightLayer.prototype, "blurHorizontalSize", null);
  93123. __decorate([
  93124. BABYLON.serialize()
  93125. ], HighlightLayer.prototype, "blurVerticalSize", null);
  93126. __decorate([
  93127. BABYLON.serialize("options")
  93128. ], HighlightLayer.prototype, "_options", void 0);
  93129. return HighlightLayer;
  93130. }(BABYLON.EffectLayer));
  93131. BABYLON.HighlightLayer = HighlightLayer;
  93132. })(BABYLON || (BABYLON = {}));
  93133. //# sourceMappingURL=babylon.highlightLayer.js.map
  93134. var BABYLON;
  93135. (function (BABYLON) {
  93136. /**
  93137. * The glow layer Helps adding a glow effect around the emissive parts of a mesh.
  93138. *
  93139. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  93140. * glowy meshes to your scene.
  93141. *
  93142. * Documentation: https://doc.babylonjs.com/how_to/glow_layer
  93143. */
  93144. var GlowLayer = /** @class */ (function (_super) {
  93145. __extends(GlowLayer, _super);
  93146. /**
  93147. * Instantiates a new glow Layer and references it to the scene.
  93148. * @param name The name of the layer
  93149. * @param scene The scene to use the layer in
  93150. * @param options Sets of none mandatory options to use with the layer (see IGlowLayerOptions for more information)
  93151. */
  93152. function GlowLayer(name, scene, options) {
  93153. var _this = _super.call(this, name, scene) || this;
  93154. _this._intensity = 1.0;
  93155. _this._includedOnlyMeshes = [];
  93156. _this._excludedMeshes = [];
  93157. _this.neutralColor = new BABYLON.Color4(0, 0, 0, 1);
  93158. // Adapt options
  93159. _this._options = __assign({ mainTextureRatio: GlowLayer.DefaultTextureRatio, blurKernelSize: 32, mainTextureFixedSize: undefined, camera: null, mainTextureSamples: 1 }, options);
  93160. // Initialize the layer
  93161. _this._init({
  93162. alphaBlendingMode: BABYLON.Engine.ALPHA_ADD,
  93163. camera: _this._options.camera,
  93164. mainTextureFixedSize: _this._options.mainTextureFixedSize,
  93165. mainTextureRatio: _this._options.mainTextureRatio
  93166. });
  93167. return _this;
  93168. }
  93169. Object.defineProperty(GlowLayer.prototype, "blurKernelSize", {
  93170. /**
  93171. * Gets the kernel size of the blur.
  93172. */
  93173. get: function () {
  93174. return this._horizontalBlurPostprocess1.kernel;
  93175. },
  93176. /**
  93177. * Sets the kernel size of the blur.
  93178. */
  93179. set: function (value) {
  93180. this._horizontalBlurPostprocess1.kernel = value;
  93181. this._verticalBlurPostprocess1.kernel = value;
  93182. this._horizontalBlurPostprocess2.kernel = value;
  93183. this._verticalBlurPostprocess2.kernel = value;
  93184. },
  93185. enumerable: true,
  93186. configurable: true
  93187. });
  93188. Object.defineProperty(GlowLayer.prototype, "intensity", {
  93189. /**
  93190. * Gets the glow intensity.
  93191. */
  93192. get: function () {
  93193. return this._intensity;
  93194. },
  93195. /**
  93196. * Sets the glow intensity.
  93197. */
  93198. set: function (value) {
  93199. this._intensity = value;
  93200. },
  93201. enumerable: true,
  93202. configurable: true
  93203. });
  93204. /**
  93205. * Get the effect name of the layer.
  93206. * @return The effect name
  93207. */
  93208. GlowLayer.prototype.getEffectName = function () {
  93209. return GlowLayer.EffectName;
  93210. };
  93211. /**
  93212. * Create the merge effect. This is the shader use to blit the information back
  93213. * to the main canvas at the end of the scene rendering.
  93214. */
  93215. GlowLayer.prototype._createMergeEffect = function () {
  93216. // Effect
  93217. return this._engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler", "textureSampler2"], "#define EMISSIVE \n");
  93218. };
  93219. /**
  93220. * Creates the render target textures and post processes used in the glow layer.
  93221. */
  93222. GlowLayer.prototype._createTextureAndPostProcesses = function () {
  93223. var _this = this;
  93224. var blurTextureWidth = this._mainTextureDesiredSize.width;
  93225. var blurTextureHeight = this._mainTextureDesiredSize.height;
  93226. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  93227. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  93228. var textureType = 0;
  93229. if (this._engine.getCaps().textureHalfFloatRender) {
  93230. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  93231. }
  93232. else {
  93233. textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  93234. }
  93235. this._blurTexture1 = new BABYLON.RenderTargetTexture("GlowLayerBlurRTT", {
  93236. width: blurTextureWidth,
  93237. height: blurTextureHeight
  93238. }, this._scene, false, true, textureType);
  93239. this._blurTexture1.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  93240. this._blurTexture1.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  93241. this._blurTexture1.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  93242. this._blurTexture1.renderParticles = false;
  93243. this._blurTexture1.ignoreCameraViewport = true;
  93244. var blurTextureWidth2 = Math.floor(blurTextureWidth / 2);
  93245. var blurTextureHeight2 = Math.floor(blurTextureHeight / 2);
  93246. this._blurTexture2 = new BABYLON.RenderTargetTexture("GlowLayerBlurRTT2", {
  93247. width: blurTextureWidth2,
  93248. height: blurTextureHeight2
  93249. }, this._scene, false, true, textureType);
  93250. this._blurTexture2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  93251. this._blurTexture2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  93252. this._blurTexture2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  93253. this._blurTexture2.renderParticles = false;
  93254. this._blurTexture2.ignoreCameraViewport = true;
  93255. this._textures = [this._blurTexture1, this._blurTexture2];
  93256. this._horizontalBlurPostprocess1 = new BABYLON.BlurPostProcess("GlowLayerHBP1", new BABYLON.Vector2(1.0, 0), this._options.blurKernelSize / 2, {
  93257. width: blurTextureWidth,
  93258. height: blurTextureHeight
  93259. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  93260. this._horizontalBlurPostprocess1.width = blurTextureWidth;
  93261. this._horizontalBlurPostprocess1.height = blurTextureHeight;
  93262. this._horizontalBlurPostprocess1.onApplyObservable.add(function (effect) {
  93263. effect.setTexture("textureSampler", _this._mainTexture);
  93264. });
  93265. this._verticalBlurPostprocess1 = new BABYLON.BlurPostProcess("GlowLayerVBP1", new BABYLON.Vector2(0, 1.0), this._options.blurKernelSize / 2, {
  93266. width: blurTextureWidth,
  93267. height: blurTextureHeight
  93268. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  93269. this._horizontalBlurPostprocess2 = new BABYLON.BlurPostProcess("GlowLayerHBP2", new BABYLON.Vector2(1.0, 0), this._options.blurKernelSize / 2, {
  93270. width: blurTextureWidth2,
  93271. height: blurTextureHeight2
  93272. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  93273. this._horizontalBlurPostprocess2.width = blurTextureWidth2;
  93274. this._horizontalBlurPostprocess2.height = blurTextureHeight2;
  93275. this._horizontalBlurPostprocess2.onApplyObservable.add(function (effect) {
  93276. effect.setTexture("textureSampler", _this._blurTexture1);
  93277. });
  93278. this._verticalBlurPostprocess2 = new BABYLON.BlurPostProcess("GlowLayerVBP2", new BABYLON.Vector2(0, 1.0), this._options.blurKernelSize / 2, {
  93279. width: blurTextureWidth2,
  93280. height: blurTextureHeight2
  93281. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  93282. this._postProcesses = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1, this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];
  93283. this._postProcesses1 = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1];
  93284. this._postProcesses2 = [this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];
  93285. this._mainTexture.samples = this._options.mainTextureSamples;
  93286. this._mainTexture.onAfterUnbindObservable.add(function () {
  93287. var internalTexture = _this._blurTexture1.getInternalTexture();
  93288. if (internalTexture) {
  93289. _this._scene.postProcessManager.directRender(_this._postProcesses1, internalTexture, true);
  93290. internalTexture = _this._blurTexture2.getInternalTexture();
  93291. if (internalTexture) {
  93292. _this._scene.postProcessManager.directRender(_this._postProcesses2, internalTexture, true);
  93293. }
  93294. }
  93295. });
  93296. // Prevent autoClear.
  93297. this._postProcesses.map(function (pp) { pp.autoClear = false; });
  93298. };
  93299. /**
  93300. * Checks for the readiness of the element composing the layer.
  93301. * @param subMesh the mesh to check for
  93302. * @param useInstances specify wether or not to use instances to render the mesh
  93303. * @param emissiveTexture the associated emissive texture used to generate the glow
  93304. * @return true if ready otherwise, false
  93305. */
  93306. GlowLayer.prototype.isReady = function (subMesh, useInstances) {
  93307. var material = subMesh.getMaterial();
  93308. var mesh = subMesh.getRenderingMesh();
  93309. if (!material || !mesh) {
  93310. return false;
  93311. }
  93312. var emissiveTexture = material.emissiveTexture;
  93313. return _super.prototype._isReady.call(this, subMesh, useInstances, emissiveTexture);
  93314. };
  93315. /**
  93316. * Returns wether or nood the layer needs stencil enabled during the mesh rendering.
  93317. */
  93318. GlowLayer.prototype.needStencil = function () {
  93319. return false;
  93320. };
  93321. /**
  93322. * Implementation specific of rendering the generating effect on the main canvas.
  93323. * @param effect The effect used to render through
  93324. */
  93325. GlowLayer.prototype._internalRender = function (effect) {
  93326. // Texture
  93327. effect.setTexture("textureSampler", this._blurTexture1);
  93328. effect.setTexture("textureSampler2", this._blurTexture2);
  93329. effect.setFloat("offset", this._intensity);
  93330. // Cache
  93331. var engine = this._engine;
  93332. var previousStencilBuffer = engine.getStencilBuffer();
  93333. // Draw order
  93334. engine.setStencilBuffer(false);
  93335. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  93336. // Draw order
  93337. engine.setStencilBuffer(previousStencilBuffer);
  93338. };
  93339. /**
  93340. * Sets the required values for both the emissive texture and and the main color.
  93341. */
  93342. GlowLayer.prototype._setEmissiveTextureAndColor = function (mesh, subMesh, material) {
  93343. var textureLevel = 1.0;
  93344. if (this.customEmissiveTextureSelector) {
  93345. this._emissiveTextureAndColor.texture = this.customEmissiveTextureSelector(mesh, subMesh, material);
  93346. }
  93347. else {
  93348. if (material) {
  93349. this._emissiveTextureAndColor.texture = material.emissiveTexture;
  93350. if (this._emissiveTextureAndColor.texture) {
  93351. textureLevel = this._emissiveTextureAndColor.texture.level;
  93352. }
  93353. }
  93354. else {
  93355. this._emissiveTextureAndColor.texture = null;
  93356. }
  93357. }
  93358. if (this.customEmissiveColorSelector) {
  93359. this.customEmissiveColorSelector(mesh, subMesh, material, this._emissiveTextureAndColor.color);
  93360. }
  93361. else {
  93362. if (material.emissiveColor) {
  93363. this._emissiveTextureAndColor.color.set(material.emissiveColor.r * textureLevel, material.emissiveColor.g * textureLevel, material.emissiveColor.b * textureLevel, 1.0);
  93364. }
  93365. else {
  93366. this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);
  93367. }
  93368. }
  93369. };
  93370. /**
  93371. * Returns true if the mesh should render, otherwise false.
  93372. * @param mesh The mesh to render
  93373. * @returns true if it should render otherwise false
  93374. */
  93375. GlowLayer.prototype._shouldRenderMesh = function (mesh) {
  93376. return this.hasMesh(mesh);
  93377. };
  93378. /**
  93379. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the glow layer.
  93380. * @param mesh The mesh to exclude from the glow layer
  93381. */
  93382. GlowLayer.prototype.addExcludedMesh = function (mesh) {
  93383. if (this._excludedMeshes.indexOf(mesh.uniqueId) === -1) {
  93384. this._excludedMeshes.push(mesh.uniqueId);
  93385. }
  93386. };
  93387. /**
  93388. * Remove a mesh from the exclusion list to let it impact or being impacted by the glow layer.
  93389. * @param mesh The mesh to remove
  93390. */
  93391. GlowLayer.prototype.removeExcludedMesh = function (mesh) {
  93392. var index = this._excludedMeshes.indexOf(mesh.uniqueId);
  93393. if (index !== -1) {
  93394. this._excludedMeshes.splice(index, 1);
  93395. }
  93396. };
  93397. /**
  93398. * Add a mesh in the inclusion list to impact or being impacted by the glow layer.
  93399. * @param mesh The mesh to include in the glow layer
  93400. */
  93401. GlowLayer.prototype.addIncludedOnlyMesh = function (mesh) {
  93402. if (this._includedOnlyMeshes.indexOf(mesh.uniqueId) === -1) {
  93403. this._includedOnlyMeshes.push(mesh.uniqueId);
  93404. }
  93405. };
  93406. /**
  93407. * Remove a mesh from the Inclusion list to prevent it to impact or being impacted by the glow layer.
  93408. * @param mesh The mesh to remove
  93409. */
  93410. GlowLayer.prototype.removeIncludedOnlyMesh = function (mesh) {
  93411. var index = this._includedOnlyMeshes.indexOf(mesh.uniqueId);
  93412. if (index !== -1) {
  93413. this._includedOnlyMeshes.splice(index, 1);
  93414. }
  93415. };
  93416. /**
  93417. * Determine if a given mesh will be used in the glow layer
  93418. * @param mesh The mesh to test
  93419. * @returns true if the mesh will be highlighted by the current glow layer
  93420. */
  93421. GlowLayer.prototype.hasMesh = function (mesh) {
  93422. // Included Mesh
  93423. if (this._includedOnlyMeshes.length) {
  93424. return this._includedOnlyMeshes.indexOf(mesh.uniqueId) !== -1;
  93425. }
  93426. ;
  93427. // Excluded Mesh
  93428. if (this._excludedMeshes.length) {
  93429. return this._excludedMeshes.indexOf(mesh.uniqueId) === -1;
  93430. }
  93431. ;
  93432. return true;
  93433. };
  93434. /**
  93435. * Free any resources and references associated to a mesh.
  93436. * Internal use
  93437. * @param mesh The mesh to free.
  93438. */
  93439. GlowLayer.prototype._disposeMesh = function (mesh) {
  93440. this.removeIncludedOnlyMesh(mesh);
  93441. this.removeExcludedMesh(mesh);
  93442. };
  93443. /**
  93444. * Gets the class name of the effect layer
  93445. * @returns the string with the class name of the effect layer
  93446. */
  93447. GlowLayer.prototype.getClassName = function () {
  93448. return "GlowLayer";
  93449. };
  93450. /**
  93451. * Serializes this glow layer
  93452. * @returns a serialized glow layer object
  93453. */
  93454. GlowLayer.prototype.serialize = function () {
  93455. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  93456. serializationObject.customType = "BABYLON.GlowLayer";
  93457. var index;
  93458. // Included meshes
  93459. serializationObject.includedMeshes = [];
  93460. if (this._includedOnlyMeshes.length) {
  93461. for (index = 0; index < this._includedOnlyMeshes.length; index++) {
  93462. var mesh = this._scene.getMeshByUniqueID(this._includedOnlyMeshes[index]);
  93463. if (mesh) {
  93464. serializationObject.includedMeshes.push(mesh.id);
  93465. }
  93466. }
  93467. }
  93468. // Excluded meshes
  93469. serializationObject.excludedMeshes = [];
  93470. if (this._excludedMeshes.length) {
  93471. for (index = 0; index < this._excludedMeshes.length; index++) {
  93472. var mesh = this._scene.getMeshByUniqueID(this._excludedMeshes[index]);
  93473. if (mesh) {
  93474. serializationObject.excludedMeshes.push(mesh.id);
  93475. }
  93476. }
  93477. }
  93478. return serializationObject;
  93479. };
  93480. /**
  93481. * Creates a Glow Layer from parsed glow layer data
  93482. * @param parsedGlowLayer defines glow layer data
  93483. * @param scene defines the current scene
  93484. * @param rootUrl defines the root URL containing the glow layer information
  93485. * @returns a parsed Glow Layer
  93486. */
  93487. GlowLayer.Parse = function (parsedGlowLayer, scene, rootUrl) {
  93488. var gl = BABYLON.SerializationHelper.Parse(function () { return new GlowLayer(parsedGlowLayer.name, scene, parsedGlowLayer.options); }, parsedGlowLayer, scene, rootUrl);
  93489. var index;
  93490. // Excluded meshes
  93491. for (index = 0; index < parsedGlowLayer.excludedMeshes.length; index++) {
  93492. var mesh = scene.getMeshByID(parsedGlowLayer.excludedMeshes[index]);
  93493. if (mesh) {
  93494. gl.addExcludedMesh(mesh);
  93495. }
  93496. }
  93497. // Included meshes
  93498. for (index = 0; index < parsedGlowLayer.includedMeshes.length; index++) {
  93499. var mesh = scene.getMeshByID(parsedGlowLayer.includedMeshes[index]);
  93500. if (mesh) {
  93501. gl.addIncludedOnlyMesh(mesh);
  93502. }
  93503. }
  93504. return gl;
  93505. };
  93506. /**
  93507. * Effect Name of the layer.
  93508. */
  93509. GlowLayer.EffectName = "GlowLayer";
  93510. /**
  93511. * The default blur kernel size used for the glow.
  93512. */
  93513. GlowLayer.DefaultBlurKernelSize = 32;
  93514. /**
  93515. * The default texture size ratio used for the glow.
  93516. */
  93517. GlowLayer.DefaultTextureRatio = 0.5;
  93518. __decorate([
  93519. BABYLON.serialize()
  93520. ], GlowLayer.prototype, "blurKernelSize", null);
  93521. __decorate([
  93522. BABYLON.serialize()
  93523. ], GlowLayer.prototype, "intensity", null);
  93524. __decorate([
  93525. BABYLON.serialize("options")
  93526. ], GlowLayer.prototype, "_options", void 0);
  93527. return GlowLayer;
  93528. }(BABYLON.EffectLayer));
  93529. BABYLON.GlowLayer = GlowLayer;
  93530. })(BABYLON || (BABYLON = {}));
  93531. //# sourceMappingURL=babylon.glowLayer.js.map
  93532. var BABYLON;
  93533. (function (BABYLON) {
  93534. /**
  93535. * Defines the list of states available for a task inside a {BABYLON.AssetsManager}
  93536. */
  93537. var AssetTaskState;
  93538. (function (AssetTaskState) {
  93539. /**
  93540. * Initialization
  93541. */
  93542. AssetTaskState[AssetTaskState["INIT"] = 0] = "INIT";
  93543. /**
  93544. * Running
  93545. */
  93546. AssetTaskState[AssetTaskState["RUNNING"] = 1] = "RUNNING";
  93547. /**
  93548. * Done
  93549. */
  93550. AssetTaskState[AssetTaskState["DONE"] = 2] = "DONE";
  93551. /**
  93552. * Error
  93553. */
  93554. AssetTaskState[AssetTaskState["ERROR"] = 3] = "ERROR";
  93555. })(AssetTaskState = BABYLON.AssetTaskState || (BABYLON.AssetTaskState = {}));
  93556. /**
  93557. * Define an abstract asset task used with a {BABYLON.AssetsManager} class to load assets into a scene
  93558. */
  93559. var AbstractAssetTask = /** @class */ (function () {
  93560. /**
  93561. * Creates a new {BABYLON.AssetsManager}
  93562. * @param name defines the name of the task
  93563. */
  93564. function AbstractAssetTask(
  93565. /**
  93566. * Task name
  93567. */ name) {
  93568. this.name = name;
  93569. this._isCompleted = false;
  93570. this._taskState = AssetTaskState.INIT;
  93571. }
  93572. Object.defineProperty(AbstractAssetTask.prototype, "isCompleted", {
  93573. /**
  93574. * Get if the task is completed
  93575. */
  93576. get: function () {
  93577. return this._isCompleted;
  93578. },
  93579. enumerable: true,
  93580. configurable: true
  93581. });
  93582. Object.defineProperty(AbstractAssetTask.prototype, "taskState", {
  93583. /**
  93584. * Gets the current state of the task
  93585. */
  93586. get: function () {
  93587. return this._taskState;
  93588. },
  93589. enumerable: true,
  93590. configurable: true
  93591. });
  93592. Object.defineProperty(AbstractAssetTask.prototype, "errorObject", {
  93593. /**
  93594. * Gets the current error object (if task is in error)
  93595. */
  93596. get: function () {
  93597. return this._errorObject;
  93598. },
  93599. enumerable: true,
  93600. configurable: true
  93601. });
  93602. /**
  93603. * Internal only
  93604. * @hidden
  93605. */
  93606. AbstractAssetTask.prototype._setErrorObject = function (message, exception) {
  93607. if (this._errorObject) {
  93608. return;
  93609. }
  93610. this._errorObject = {
  93611. message: message,
  93612. exception: exception
  93613. };
  93614. };
  93615. /**
  93616. * Execute the current task
  93617. * @param scene defines the scene where you want your assets to be loaded
  93618. * @param onSuccess is a callback called when the task is successfully executed
  93619. * @param onError is a callback called if an error occurs
  93620. */
  93621. AbstractAssetTask.prototype.run = function (scene, onSuccess, onError) {
  93622. var _this = this;
  93623. this._taskState = AssetTaskState.RUNNING;
  93624. this.runTask(scene, function () {
  93625. _this.onDoneCallback(onSuccess, onError);
  93626. }, function (msg, exception) {
  93627. _this.onErrorCallback(onError, msg, exception);
  93628. });
  93629. };
  93630. /**
  93631. * Execute the current task
  93632. * @param scene defines the scene where you want your assets to be loaded
  93633. * @param onSuccess is a callback called when the task is successfully executed
  93634. * @param onError is a callback called if an error occurs
  93635. */
  93636. AbstractAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  93637. throw new Error("runTask is not implemented");
  93638. };
  93639. AbstractAssetTask.prototype.onErrorCallback = function (onError, message, exception) {
  93640. this._taskState = AssetTaskState.ERROR;
  93641. this._errorObject = {
  93642. message: message,
  93643. exception: exception
  93644. };
  93645. if (this.onError) {
  93646. this.onError(this, message, exception);
  93647. }
  93648. onError();
  93649. };
  93650. AbstractAssetTask.prototype.onDoneCallback = function (onSuccess, onError) {
  93651. try {
  93652. this._taskState = AssetTaskState.DONE;
  93653. this._isCompleted = true;
  93654. if (this.onSuccess) {
  93655. this.onSuccess(this);
  93656. }
  93657. onSuccess();
  93658. }
  93659. catch (e) {
  93660. this.onErrorCallback(onError, "Task is done, error executing success callback(s)", e);
  93661. }
  93662. };
  93663. return AbstractAssetTask;
  93664. }());
  93665. BABYLON.AbstractAssetTask = AbstractAssetTask;
  93666. /**
  93667. * Class used to share progress information about assets loading
  93668. */
  93669. var AssetsProgressEvent = /** @class */ (function () {
  93670. /**
  93671. * Creates a {BABYLON.AssetsProgressEvent}
  93672. * @param remainingCount defines the number of remaining tasks to process
  93673. * @param totalCount defines the total number of tasks
  93674. * @param task defines the task that was just processed
  93675. */
  93676. function AssetsProgressEvent(remainingCount, totalCount, task) {
  93677. this.remainingCount = remainingCount;
  93678. this.totalCount = totalCount;
  93679. this.task = task;
  93680. }
  93681. return AssetsProgressEvent;
  93682. }());
  93683. BABYLON.AssetsProgressEvent = AssetsProgressEvent;
  93684. /**
  93685. * Define a task used by {BABYLON.AssetsManager} to load meshes
  93686. */
  93687. var MeshAssetTask = /** @class */ (function (_super) {
  93688. __extends(MeshAssetTask, _super);
  93689. /**
  93690. * Creates a new {BABYLON.MeshAssetTask}
  93691. * @param name defines the name of the task
  93692. * @param meshesNames defines the list of mesh's names you want to load
  93693. * @param rootUrl defines the root url to use as a base to load your meshes and associated resources
  93694. * @param sceneFilename defines the filename of the scene to load from
  93695. */
  93696. function MeshAssetTask(
  93697. /**
  93698. * Defines the name of the task
  93699. */
  93700. name,
  93701. /**
  93702. * Defines the list of mesh's names you want to load
  93703. */
  93704. meshesNames,
  93705. /**
  93706. * Defines the root url to use as a base to load your meshes and associated resources
  93707. */
  93708. rootUrl,
  93709. /**
  93710. * Defines the filename of the scene to load from
  93711. */
  93712. sceneFilename) {
  93713. var _this = _super.call(this, name) || this;
  93714. _this.name = name;
  93715. _this.meshesNames = meshesNames;
  93716. _this.rootUrl = rootUrl;
  93717. _this.sceneFilename = sceneFilename;
  93718. return _this;
  93719. }
  93720. /**
  93721. * Execute the current task
  93722. * @param scene defines the scene where you want your assets to be loaded
  93723. * @param onSuccess is a callback called when the task is successfully executed
  93724. * @param onError is a callback called if an error occurs
  93725. */
  93726. MeshAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  93727. var _this = this;
  93728. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  93729. _this.loadedMeshes = meshes;
  93730. _this.loadedParticleSystems = particleSystems;
  93731. _this.loadedSkeletons = skeletons;
  93732. onSuccess();
  93733. }, null, function (scene, message, exception) {
  93734. onError(message, exception);
  93735. });
  93736. };
  93737. return MeshAssetTask;
  93738. }(AbstractAssetTask));
  93739. BABYLON.MeshAssetTask = MeshAssetTask;
  93740. /**
  93741. * Define a task used by {BABYLON.AssetsManager} to load text content
  93742. */
  93743. var TextFileAssetTask = /** @class */ (function (_super) {
  93744. __extends(TextFileAssetTask, _super);
  93745. /**
  93746. * Creates a new TextFileAssetTask object
  93747. * @param name defines the name of the task
  93748. * @param url defines the location of the file to load
  93749. */
  93750. function TextFileAssetTask(
  93751. /**
  93752. * Defines the name of the task
  93753. */
  93754. name,
  93755. /**
  93756. * Defines the location of the file to load
  93757. */
  93758. url) {
  93759. var _this = _super.call(this, name) || this;
  93760. _this.name = name;
  93761. _this.url = url;
  93762. return _this;
  93763. }
  93764. /**
  93765. * Execute the current task
  93766. * @param scene defines the scene where you want your assets to be loaded
  93767. * @param onSuccess is a callback called when the task is successfully executed
  93768. * @param onError is a callback called if an error occurs
  93769. */
  93770. TextFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  93771. var _this = this;
  93772. scene._loadFile(this.url, function (data) {
  93773. _this.text = data;
  93774. onSuccess();
  93775. }, undefined, false, false, function (request, exception) {
  93776. if (request) {
  93777. onError(request.status + " " + request.statusText, exception);
  93778. }
  93779. });
  93780. };
  93781. return TextFileAssetTask;
  93782. }(AbstractAssetTask));
  93783. BABYLON.TextFileAssetTask = TextFileAssetTask;
  93784. /**
  93785. * Define a task used by {BABYLON.AssetsManager} to load binary data
  93786. */
  93787. var BinaryFileAssetTask = /** @class */ (function (_super) {
  93788. __extends(BinaryFileAssetTask, _super);
  93789. /**
  93790. * Creates a new BinaryFileAssetTask object
  93791. * @param name defines the name of the new task
  93792. * @param url defines the location of the file to load
  93793. */
  93794. function BinaryFileAssetTask(
  93795. /**
  93796. * Defines the name of the task
  93797. */
  93798. name,
  93799. /**
  93800. * Defines the location of the file to load
  93801. */
  93802. url) {
  93803. var _this = _super.call(this, name) || this;
  93804. _this.name = name;
  93805. _this.url = url;
  93806. return _this;
  93807. }
  93808. /**
  93809. * Execute the current task
  93810. * @param scene defines the scene where you want your assets to be loaded
  93811. * @param onSuccess is a callback called when the task is successfully executed
  93812. * @param onError is a callback called if an error occurs
  93813. */
  93814. BinaryFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  93815. var _this = this;
  93816. scene._loadFile(this.url, function (data) {
  93817. _this.data = data;
  93818. onSuccess();
  93819. }, undefined, true, true, function (request, exception) {
  93820. if (request) {
  93821. onError(request.status + " " + request.statusText, exception);
  93822. }
  93823. });
  93824. };
  93825. return BinaryFileAssetTask;
  93826. }(AbstractAssetTask));
  93827. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  93828. /**
  93829. * Define a task used by {BABYLON.AssetsManager} to load images
  93830. */
  93831. var ImageAssetTask = /** @class */ (function (_super) {
  93832. __extends(ImageAssetTask, _super);
  93833. /**
  93834. * Creates a new ImageAssetTask
  93835. * @param name defines the name of the task
  93836. * @param url defines the location of the image to load
  93837. */
  93838. function ImageAssetTask(
  93839. /**
  93840. * Defines the name of the task
  93841. */
  93842. name,
  93843. /**
  93844. * Defines the location of the image to load
  93845. */
  93846. url) {
  93847. var _this = _super.call(this, name) || this;
  93848. _this.name = name;
  93849. _this.url = url;
  93850. return _this;
  93851. }
  93852. /**
  93853. * Execute the current task
  93854. * @param scene defines the scene where you want your assets to be loaded
  93855. * @param onSuccess is a callback called when the task is successfully executed
  93856. * @param onError is a callback called if an error occurs
  93857. */
  93858. ImageAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  93859. var _this = this;
  93860. var img = new Image();
  93861. BABYLON.Tools.SetCorsBehavior(this.url, img);
  93862. img.onload = function () {
  93863. _this.image = img;
  93864. onSuccess();
  93865. };
  93866. img.onerror = function (err) {
  93867. onError("Error loading image", err);
  93868. };
  93869. img.src = this.url;
  93870. };
  93871. return ImageAssetTask;
  93872. }(AbstractAssetTask));
  93873. BABYLON.ImageAssetTask = ImageAssetTask;
  93874. /**
  93875. * Define a task used by {BABYLON.AssetsManager} to load 2D textures
  93876. */
  93877. var TextureAssetTask = /** @class */ (function (_super) {
  93878. __extends(TextureAssetTask, _super);
  93879. /**
  93880. * Creates a new TextureAssetTask object
  93881. * @param name defines the name of the task
  93882. * @param url defines the location of the file to load
  93883. * @param noMipmap defines if mipmap should not be generated (default is false)
  93884. * @param invertY defines if texture must be inverted on Y axis (default is false)
  93885. * @param samplingMode defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  93886. */
  93887. function TextureAssetTask(
  93888. /**
  93889. * Defines the name of the task
  93890. */
  93891. name,
  93892. /**
  93893. * Defines the location of the file to load
  93894. */
  93895. url,
  93896. /**
  93897. * Defines if mipmap should not be generated (default is false)
  93898. */
  93899. noMipmap,
  93900. /**
  93901. * Defines if texture must be inverted on Y axis (default is false)
  93902. */
  93903. invertY,
  93904. /**
  93905. * Defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  93906. */
  93907. samplingMode) {
  93908. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  93909. var _this = _super.call(this, name) || this;
  93910. _this.name = name;
  93911. _this.url = url;
  93912. _this.noMipmap = noMipmap;
  93913. _this.invertY = invertY;
  93914. _this.samplingMode = samplingMode;
  93915. return _this;
  93916. }
  93917. /**
  93918. * Execute the current task
  93919. * @param scene defines the scene where you want your assets to be loaded
  93920. * @param onSuccess is a callback called when the task is successfully executed
  93921. * @param onError is a callback called if an error occurs
  93922. */
  93923. TextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  93924. var onload = function () {
  93925. onSuccess();
  93926. };
  93927. var onerror = function (message, exception) {
  93928. onError(message, exception);
  93929. };
  93930. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onerror);
  93931. };
  93932. return TextureAssetTask;
  93933. }(AbstractAssetTask));
  93934. BABYLON.TextureAssetTask = TextureAssetTask;
  93935. /**
  93936. * Define a task used by {BABYLON.AssetsManager} to load cube textures
  93937. */
  93938. var CubeTextureAssetTask = /** @class */ (function (_super) {
  93939. __extends(CubeTextureAssetTask, _super);
  93940. /**
  93941. * Creates a new CubeTextureAssetTask
  93942. * @param name defines the name of the task
  93943. * @param url defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  93944. * @param extensions defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  93945. * @param noMipmap defines if mipmaps should not be generated (default is false)
  93946. * @param files defines the explicit list of files (undefined by default)
  93947. */
  93948. function CubeTextureAssetTask(
  93949. /**
  93950. * Defines the name of the task
  93951. */
  93952. name,
  93953. /**
  93954. * Defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  93955. */
  93956. url,
  93957. /**
  93958. * Defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  93959. */
  93960. extensions,
  93961. /**
  93962. * Defines if mipmaps should not be generated (default is false)
  93963. */
  93964. noMipmap,
  93965. /**
  93966. * Defines the explicit list of files (undefined by default)
  93967. */
  93968. files) {
  93969. var _this = _super.call(this, name) || this;
  93970. _this.name = name;
  93971. _this.url = url;
  93972. _this.extensions = extensions;
  93973. _this.noMipmap = noMipmap;
  93974. _this.files = files;
  93975. return _this;
  93976. }
  93977. /**
  93978. * Execute the current task
  93979. * @param scene defines the scene where you want your assets to be loaded
  93980. * @param onSuccess is a callback called when the task is successfully executed
  93981. * @param onError is a callback called if an error occurs
  93982. */
  93983. CubeTextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  93984. var onload = function () {
  93985. onSuccess();
  93986. };
  93987. var onerror = function (message, exception) {
  93988. onError(message, exception);
  93989. };
  93990. this.texture = new BABYLON.CubeTexture(this.url, scene, this.extensions, this.noMipmap, this.files, onload, onerror);
  93991. };
  93992. return CubeTextureAssetTask;
  93993. }(AbstractAssetTask));
  93994. BABYLON.CubeTextureAssetTask = CubeTextureAssetTask;
  93995. /**
  93996. * Define a task used by {BABYLON.AssetsManager} to load HDR cube textures
  93997. */
  93998. var HDRCubeTextureAssetTask = /** @class */ (function (_super) {
  93999. __extends(HDRCubeTextureAssetTask, _super);
  94000. /**
  94001. * Creates a new HDRCubeTextureAssetTask object
  94002. * @param name defines the name of the task
  94003. * @param url defines the location of the file to load
  94004. * @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.
  94005. * @param noMipmap defines if mipmaps should not be generated (default is false)
  94006. * @param generateHarmonics specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  94007. * @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)
  94008. * @param reserved Internal use only
  94009. */
  94010. function HDRCubeTextureAssetTask(
  94011. /**
  94012. * Defines the name of the task
  94013. */
  94014. name,
  94015. /**
  94016. * Defines the location of the file to load
  94017. */
  94018. url,
  94019. /**
  94020. * Defines the desired size (the more it increases the longer the generation will be)
  94021. */
  94022. size,
  94023. /**
  94024. * Defines if mipmaps should not be generated (default is false)
  94025. */
  94026. noMipmap,
  94027. /**
  94028. * Specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  94029. */
  94030. generateHarmonics,
  94031. /**
  94032. * 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)
  94033. */
  94034. gammaSpace,
  94035. /**
  94036. * Internal Use Only
  94037. */
  94038. reserved) {
  94039. if (noMipmap === void 0) { noMipmap = false; }
  94040. if (generateHarmonics === void 0) { generateHarmonics = true; }
  94041. if (gammaSpace === void 0) { gammaSpace = false; }
  94042. if (reserved === void 0) { reserved = false; }
  94043. var _this = _super.call(this, name) || this;
  94044. _this.name = name;
  94045. _this.url = url;
  94046. _this.size = size;
  94047. _this.noMipmap = noMipmap;
  94048. _this.generateHarmonics = generateHarmonics;
  94049. _this.gammaSpace = gammaSpace;
  94050. _this.reserved = reserved;
  94051. return _this;
  94052. }
  94053. /**
  94054. * Execute the current task
  94055. * @param scene defines the scene where you want your assets to be loaded
  94056. * @param onSuccess is a callback called when the task is successfully executed
  94057. * @param onError is a callback called if an error occurs
  94058. */
  94059. HDRCubeTextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  94060. var onload = function () {
  94061. onSuccess();
  94062. };
  94063. var onerror = function (message, exception) {
  94064. onError(message, exception);
  94065. };
  94066. this.texture = new BABYLON.HDRCubeTexture(this.url, scene, this.size, this.noMipmap, this.generateHarmonics, this.gammaSpace, this.reserved, onload, onerror);
  94067. };
  94068. return HDRCubeTextureAssetTask;
  94069. }(AbstractAssetTask));
  94070. BABYLON.HDRCubeTextureAssetTask = HDRCubeTextureAssetTask;
  94071. /**
  94072. * This class can be used to easily import assets into a scene
  94073. * @see http://doc.babylonjs.com/how_to/how_to_use_assetsmanager
  94074. */
  94075. var AssetsManager = /** @class */ (function () {
  94076. /**
  94077. * Creates a new AssetsManager
  94078. * @param scene defines the scene to work on
  94079. */
  94080. function AssetsManager(scene) {
  94081. this._isLoading = false;
  94082. this._tasks = new Array();
  94083. this._waitingTasksCount = 0;
  94084. this._totalTasksCount = 0;
  94085. /**
  94086. * Observable called when all tasks are processed
  94087. */
  94088. this.onTaskSuccessObservable = new BABYLON.Observable();
  94089. /**
  94090. * Observable called when a task had an error
  94091. */
  94092. this.onTaskErrorObservable = new BABYLON.Observable();
  94093. /**
  94094. * Observable called when a task is successful
  94095. */
  94096. this.onTasksDoneObservable = new BABYLON.Observable();
  94097. /**
  94098. * Observable called when a task is done (whatever the result is)
  94099. */
  94100. this.onProgressObservable = new BABYLON.Observable();
  94101. /**
  94102. * Gets or sets a boolean defining if the {BABYLON.AssetsManager} should use the default loading screen
  94103. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  94104. */
  94105. this.useDefaultLoadingScreen = true;
  94106. this._scene = scene;
  94107. }
  94108. /**
  94109. * Add a {BABYLON.MeshAssetTask} to the list of active tasks
  94110. * @param taskName defines the name of the new task
  94111. * @param meshesNames defines the name of meshes to load
  94112. * @param rootUrl defines the root url to use to locate files
  94113. * @param sceneFilename defines the filename of the scene file
  94114. * @returns a new {BABYLON.MeshAssetTask} object
  94115. */
  94116. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  94117. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  94118. this._tasks.push(task);
  94119. return task;
  94120. };
  94121. /**
  94122. * Add a {BABYLON.TextFileAssetTask} to the list of active tasks
  94123. * @param taskName defines the name of the new task
  94124. * @param url defines the url of the file to load
  94125. * @returns a new {BABYLON.TextFileAssetTask} object
  94126. */
  94127. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  94128. var task = new TextFileAssetTask(taskName, url);
  94129. this._tasks.push(task);
  94130. return task;
  94131. };
  94132. /**
  94133. * Add a {BABYLON.BinaryFileAssetTask} to the list of active tasks
  94134. * @param taskName defines the name of the new task
  94135. * @param url defines the url of the file to load
  94136. * @returns a new {BABYLON.BinaryFileAssetTask} object
  94137. */
  94138. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  94139. var task = new BinaryFileAssetTask(taskName, url);
  94140. this._tasks.push(task);
  94141. return task;
  94142. };
  94143. /**
  94144. * Add a {BABYLON.ImageAssetTask} to the list of active tasks
  94145. * @param taskName defines the name of the new task
  94146. * @param url defines the url of the file to load
  94147. * @returns a new {BABYLON.ImageAssetTask} object
  94148. */
  94149. AssetsManager.prototype.addImageTask = function (taskName, url) {
  94150. var task = new ImageAssetTask(taskName, url);
  94151. this._tasks.push(task);
  94152. return task;
  94153. };
  94154. /**
  94155. * Add a {BABYLON.TextureAssetTask} to the list of active tasks
  94156. * @param taskName defines the name of the new task
  94157. * @param url defines the url of the file to load
  94158. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  94159. * @param invertY defines if you want to invert Y axis of the loaded texture (false by default)
  94160. * @param samplingMode defines the sampling mode to use (BABYLON.Texture.TRILINEAR_SAMPLINGMODE by default)
  94161. * @returns a new {BABYLON.TextureAssetTask} object
  94162. */
  94163. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  94164. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  94165. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  94166. this._tasks.push(task);
  94167. return task;
  94168. };
  94169. /**
  94170. * Add a {BABYLON.CubeTextureAssetTask} to the list of active tasks
  94171. * @param taskName defines the name of the new task
  94172. * @param url defines the url of the file to load
  94173. * @param extensions defines the extension to use to load the cube map (can be null)
  94174. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  94175. * @param files defines the list of files to load (can be null)
  94176. * @returns a new {BABYLON.CubeTextureAssetTask} object
  94177. */
  94178. AssetsManager.prototype.addCubeTextureTask = function (taskName, url, extensions, noMipmap, files) {
  94179. var task = new CubeTextureAssetTask(taskName, url, extensions, noMipmap, files);
  94180. this._tasks.push(task);
  94181. return task;
  94182. };
  94183. /**
  94184. *
  94185. * Add a {BABYLON.HDRCubeTextureAssetTask} to the list of active tasks
  94186. * @param taskName defines the name of the new task
  94187. * @param url defines the url of the file to load
  94188. * @param size defines the size you want for the cubemap (can be null)
  94189. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  94190. * @param generateHarmonics defines if you want to automatically generate (true by default)
  94191. * @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)
  94192. * @param reserved Internal use only
  94193. * @returns a new {BABYLON.HDRCubeTextureAssetTask} object
  94194. */
  94195. AssetsManager.prototype.addHDRCubeTextureTask = function (taskName, url, size, noMipmap, generateHarmonics, gammaSpace, reserved) {
  94196. if (noMipmap === void 0) { noMipmap = false; }
  94197. if (generateHarmonics === void 0) { generateHarmonics = true; }
  94198. if (gammaSpace === void 0) { gammaSpace = false; }
  94199. if (reserved === void 0) { reserved = false; }
  94200. var task = new HDRCubeTextureAssetTask(taskName, url, size, noMipmap, generateHarmonics, gammaSpace, reserved);
  94201. this._tasks.push(task);
  94202. return task;
  94203. };
  94204. AssetsManager.prototype._decreaseWaitingTasksCount = function (task) {
  94205. this._waitingTasksCount--;
  94206. try {
  94207. if (this.onProgress) {
  94208. this.onProgress(this._waitingTasksCount, this._totalTasksCount, task);
  94209. }
  94210. this.onProgressObservable.notifyObservers(new AssetsProgressEvent(this._waitingTasksCount, this._totalTasksCount, task));
  94211. }
  94212. catch (e) {
  94213. BABYLON.Tools.Error("Error running progress callbacks.");
  94214. console.log(e);
  94215. }
  94216. if (this._waitingTasksCount === 0) {
  94217. try {
  94218. if (this.onFinish) {
  94219. this.onFinish(this._tasks);
  94220. }
  94221. // Let's remove successfull tasks
  94222. var currentTasks = this._tasks.slice();
  94223. for (var _i = 0, currentTasks_1 = currentTasks; _i < currentTasks_1.length; _i++) {
  94224. var task = currentTasks_1[_i];
  94225. if (task.taskState === AssetTaskState.DONE) {
  94226. var index = this._tasks.indexOf(task);
  94227. if (index > -1) {
  94228. this._tasks.splice(index, 1);
  94229. }
  94230. }
  94231. }
  94232. this.onTasksDoneObservable.notifyObservers(this._tasks);
  94233. }
  94234. catch (e) {
  94235. BABYLON.Tools.Error("Error running tasks-done callbacks.");
  94236. console.log(e);
  94237. }
  94238. this._isLoading = false;
  94239. this._scene.getEngine().hideLoadingUI();
  94240. }
  94241. };
  94242. AssetsManager.prototype._runTask = function (task) {
  94243. var _this = this;
  94244. var done = function () {
  94245. try {
  94246. if (_this.onTaskSuccess) {
  94247. _this.onTaskSuccess(task);
  94248. }
  94249. _this.onTaskSuccessObservable.notifyObservers(task);
  94250. _this._decreaseWaitingTasksCount(task);
  94251. }
  94252. catch (e) {
  94253. error("Error executing task success callbacks", e);
  94254. }
  94255. };
  94256. var error = function (message, exception) {
  94257. task._setErrorObject(message, exception);
  94258. if (_this.onTaskError) {
  94259. _this.onTaskError(task);
  94260. }
  94261. _this.onTaskErrorObservable.notifyObservers(task);
  94262. _this._decreaseWaitingTasksCount(task);
  94263. };
  94264. task.run(this._scene, done, error);
  94265. };
  94266. /**
  94267. * Reset the {BABYLON.AssetsManager} and remove all tasks
  94268. * @return the current instance of the {BABYLON.AssetsManager}
  94269. */
  94270. AssetsManager.prototype.reset = function () {
  94271. this._isLoading = false;
  94272. this._tasks = new Array();
  94273. return this;
  94274. };
  94275. /**
  94276. * Start the loading process
  94277. * @return the current instance of the {BABYLON.AssetsManager}
  94278. */
  94279. AssetsManager.prototype.load = function () {
  94280. if (this._isLoading) {
  94281. return this;
  94282. }
  94283. this._isLoading = true;
  94284. this._waitingTasksCount = this._tasks.length;
  94285. this._totalTasksCount = this._tasks.length;
  94286. if (this._waitingTasksCount === 0) {
  94287. this._isLoading = false;
  94288. if (this.onFinish) {
  94289. this.onFinish(this._tasks);
  94290. }
  94291. this.onTasksDoneObservable.notifyObservers(this._tasks);
  94292. return this;
  94293. }
  94294. if (this.useDefaultLoadingScreen) {
  94295. this._scene.getEngine().displayLoadingUI();
  94296. }
  94297. for (var index = 0; index < this._tasks.length; index++) {
  94298. var task = this._tasks[index];
  94299. this._runTask(task);
  94300. }
  94301. return this;
  94302. };
  94303. return AssetsManager;
  94304. }());
  94305. BABYLON.AssetsManager = AssetsManager;
  94306. })(BABYLON || (BABYLON = {}));
  94307. //# sourceMappingURL=babylon.assetsManager.js.map
  94308. var BABYLON;
  94309. (function (BABYLON) {
  94310. var serializedGeometries = [];
  94311. var serializeGeometry = function (geometry, serializationGeometries) {
  94312. if (serializedGeometries[geometry.id]) {
  94313. return;
  94314. }
  94315. if (geometry.doNotSerialize) {
  94316. return;
  94317. }
  94318. if (geometry instanceof BABYLON.BoxGeometry) {
  94319. serializationGeometries.boxes.push(geometry.serialize());
  94320. }
  94321. else if (geometry instanceof BABYLON.SphereGeometry) {
  94322. serializationGeometries.spheres.push(geometry.serialize());
  94323. }
  94324. else if (geometry instanceof BABYLON.CylinderGeometry) {
  94325. serializationGeometries.cylinders.push(geometry.serialize());
  94326. }
  94327. else if (geometry instanceof BABYLON.TorusGeometry) {
  94328. serializationGeometries.toruses.push(geometry.serialize());
  94329. }
  94330. else if (geometry instanceof BABYLON.GroundGeometry) {
  94331. serializationGeometries.grounds.push(geometry.serialize());
  94332. }
  94333. else if (geometry instanceof BABYLON.Plane) {
  94334. serializationGeometries.planes.push(geometry.serialize());
  94335. }
  94336. else if (geometry instanceof BABYLON.TorusKnotGeometry) {
  94337. serializationGeometries.torusKnots.push(geometry.serialize());
  94338. }
  94339. else if (geometry instanceof BABYLON._PrimitiveGeometry) {
  94340. throw new Error("Unknown primitive type");
  94341. }
  94342. else {
  94343. serializationGeometries.vertexData.push(geometry.serializeVerticeData());
  94344. }
  94345. serializedGeometries[geometry.id] = true;
  94346. };
  94347. var serializeMesh = function (mesh, serializationScene) {
  94348. var serializationObject = {};
  94349. // Geometry
  94350. var geometry = mesh._geometry;
  94351. if (geometry) {
  94352. if (!mesh.getScene().getGeometryByID(geometry.id)) {
  94353. // 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
  94354. serializeGeometry(geometry, serializationScene.geometries);
  94355. }
  94356. }
  94357. // Custom
  94358. if (mesh.serialize) {
  94359. mesh.serialize(serializationObject);
  94360. }
  94361. return serializationObject;
  94362. };
  94363. var finalizeSingleMesh = function (mesh, serializationObject) {
  94364. //only works if the mesh is already loaded
  94365. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  94366. //serialize material
  94367. if (mesh.material) {
  94368. if (mesh.material instanceof BABYLON.StandardMaterial) {
  94369. serializationObject.materials = serializationObject.materials || [];
  94370. if (!serializationObject.materials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  94371. serializationObject.materials.push(mesh.material.serialize());
  94372. }
  94373. }
  94374. else if (mesh.material instanceof BABYLON.MultiMaterial) {
  94375. serializationObject.multiMaterials = serializationObject.multiMaterials || [];
  94376. if (!serializationObject.multiMaterials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  94377. serializationObject.multiMaterials.push(mesh.material.serialize());
  94378. }
  94379. }
  94380. }
  94381. //serialize geometry
  94382. var geometry = mesh._geometry;
  94383. if (geometry) {
  94384. if (!serializationObject.geometries) {
  94385. serializationObject.geometries = {};
  94386. serializationObject.geometries.boxes = [];
  94387. serializationObject.geometries.spheres = [];
  94388. serializationObject.geometries.cylinders = [];
  94389. serializationObject.geometries.toruses = [];
  94390. serializationObject.geometries.grounds = [];
  94391. serializationObject.geometries.planes = [];
  94392. serializationObject.geometries.torusKnots = [];
  94393. serializationObject.geometries.vertexData = [];
  94394. }
  94395. serializeGeometry(geometry, serializationObject.geometries);
  94396. }
  94397. // Skeletons
  94398. if (mesh.skeleton) {
  94399. serializationObject.skeletons = serializationObject.skeletons || [];
  94400. serializationObject.skeletons.push(mesh.skeleton.serialize());
  94401. }
  94402. //serialize the actual mesh
  94403. serializationObject.meshes = serializationObject.meshes || [];
  94404. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  94405. }
  94406. };
  94407. var SceneSerializer = /** @class */ (function () {
  94408. function SceneSerializer() {
  94409. }
  94410. SceneSerializer.ClearCache = function () {
  94411. serializedGeometries = [];
  94412. };
  94413. SceneSerializer.Serialize = function (scene) {
  94414. var serializationObject = {};
  94415. SceneSerializer.ClearCache();
  94416. // Scene
  94417. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  94418. serializationObject.autoClear = scene.autoClear;
  94419. serializationObject.clearColor = scene.clearColor.asArray();
  94420. serializationObject.ambientColor = scene.ambientColor.asArray();
  94421. serializationObject.gravity = scene.gravity.asArray();
  94422. serializationObject.collisionsEnabled = scene.collisionsEnabled;
  94423. serializationObject.workerCollisions = scene.workerCollisions;
  94424. // Fog
  94425. if (scene.fogMode && scene.fogMode !== 0) {
  94426. serializationObject.fogMode = scene.fogMode;
  94427. serializationObject.fogColor = scene.fogColor.asArray();
  94428. serializationObject.fogStart = scene.fogStart;
  94429. serializationObject.fogEnd = scene.fogEnd;
  94430. serializationObject.fogDensity = scene.fogDensity;
  94431. }
  94432. //Physics
  94433. if (scene.isPhysicsEnabled()) {
  94434. var physicEngine = scene.getPhysicsEngine();
  94435. if (physicEngine) {
  94436. serializationObject.physicsEnabled = true;
  94437. serializationObject.physicsGravity = physicEngine.gravity.asArray();
  94438. serializationObject.physicsEngine = physicEngine.getPhysicsPluginName();
  94439. }
  94440. }
  94441. // Metadata
  94442. if (scene.metadata) {
  94443. serializationObject.metadata = scene.metadata;
  94444. }
  94445. // Morph targets
  94446. serializationObject.morphTargetManagers = [];
  94447. for (var _i = 0, _a = scene.meshes; _i < _a.length; _i++) {
  94448. var abstractMesh = _a[_i];
  94449. var manager = abstractMesh.morphTargetManager;
  94450. if (manager) {
  94451. serializationObject.morphTargetManagers.push(manager.serialize());
  94452. }
  94453. }
  94454. // Lights
  94455. serializationObject.lights = [];
  94456. var index;
  94457. var light;
  94458. for (index = 0; index < scene.lights.length; index++) {
  94459. light = scene.lights[index];
  94460. if (!light.doNotSerialize) {
  94461. serializationObject.lights.push(light.serialize());
  94462. }
  94463. }
  94464. // Cameras
  94465. serializationObject.cameras = [];
  94466. for (index = 0; index < scene.cameras.length; index++) {
  94467. var camera = scene.cameras[index];
  94468. if (!camera.doNotSerialize) {
  94469. serializationObject.cameras.push(camera.serialize());
  94470. }
  94471. }
  94472. if (scene.activeCamera) {
  94473. serializationObject.activeCameraID = scene.activeCamera.id;
  94474. }
  94475. // Animations
  94476. BABYLON.Animation.AppendSerializedAnimations(scene, serializationObject);
  94477. // Materials
  94478. serializationObject.materials = [];
  94479. serializationObject.multiMaterials = [];
  94480. var material;
  94481. for (index = 0; index < scene.materials.length; index++) {
  94482. material = scene.materials[index];
  94483. if (!material.doNotSerialize) {
  94484. serializationObject.materials.push(material.serialize());
  94485. }
  94486. }
  94487. // MultiMaterials
  94488. serializationObject.multiMaterials = [];
  94489. for (index = 0; index < scene.multiMaterials.length; index++) {
  94490. var multiMaterial = scene.multiMaterials[index];
  94491. serializationObject.multiMaterials.push(multiMaterial.serialize());
  94492. }
  94493. // Environment texture
  94494. if (scene.environmentTexture) {
  94495. serializationObject.environmentTexture = scene.environmentTexture.name;
  94496. }
  94497. // Skeletons
  94498. serializationObject.skeletons = [];
  94499. for (index = 0; index < scene.skeletons.length; index++) {
  94500. var skeleton = scene.skeletons[index];
  94501. if (!skeleton.doNotSerialize) {
  94502. serializationObject.skeletons.push(skeleton.serialize());
  94503. }
  94504. }
  94505. // Transform nodes
  94506. serializationObject.transformNodes = [];
  94507. for (index = 0; index < scene.transformNodes.length; index++) {
  94508. serializationObject.transformNodes.push(scene.transformNodes[index].serialize());
  94509. }
  94510. // Geometries
  94511. serializationObject.geometries = {};
  94512. serializationObject.geometries.boxes = [];
  94513. serializationObject.geometries.spheres = [];
  94514. serializationObject.geometries.cylinders = [];
  94515. serializationObject.geometries.toruses = [];
  94516. serializationObject.geometries.grounds = [];
  94517. serializationObject.geometries.planes = [];
  94518. serializationObject.geometries.torusKnots = [];
  94519. serializationObject.geometries.vertexData = [];
  94520. serializedGeometries = [];
  94521. var geometries = scene.getGeometries();
  94522. for (index = 0; index < geometries.length; index++) {
  94523. var geometry = geometries[index];
  94524. if (geometry.isReady()) {
  94525. serializeGeometry(geometry, serializationObject.geometries);
  94526. }
  94527. }
  94528. // Meshes
  94529. serializationObject.meshes = [];
  94530. for (index = 0; index < scene.meshes.length; index++) {
  94531. var abstractMesh = scene.meshes[index];
  94532. if (abstractMesh instanceof BABYLON.Mesh) {
  94533. var mesh = abstractMesh;
  94534. if (!mesh.doNotSerialize) {
  94535. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  94536. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  94537. }
  94538. }
  94539. }
  94540. }
  94541. // Particles Systems
  94542. serializationObject.particleSystems = [];
  94543. for (index = 0; index < scene.particleSystems.length; index++) {
  94544. serializationObject.particleSystems.push(scene.particleSystems[index].serialize());
  94545. }
  94546. // Lens flares
  94547. serializationObject.lensFlareSystems = [];
  94548. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  94549. serializationObject.lensFlareSystems.push(scene.lensFlareSystems[index].serialize());
  94550. }
  94551. // Shadows
  94552. serializationObject.shadowGenerators = [];
  94553. for (index = 0; index < scene.lights.length; index++) {
  94554. light = scene.lights[index];
  94555. var shadowGenerator = light.getShadowGenerator();
  94556. if (shadowGenerator) {
  94557. serializationObject.shadowGenerators.push(shadowGenerator.serialize());
  94558. }
  94559. }
  94560. // Action Manager
  94561. if (scene.actionManager) {
  94562. serializationObject.actions = scene.actionManager.serialize("scene");
  94563. }
  94564. // Audio
  94565. serializationObject.sounds = [];
  94566. for (index = 0; index < scene.soundTracks.length; index++) {
  94567. var soundtrack = scene.soundTracks[index];
  94568. for (var soundId = 0; soundId < soundtrack.soundCollection.length; soundId++) {
  94569. serializationObject.sounds.push(soundtrack.soundCollection[soundId].serialize());
  94570. }
  94571. }
  94572. // Effect layers
  94573. serializationObject.effectLayers = [];
  94574. for (index = 0; index < scene.effectLayers.length; index++) {
  94575. var layer = scene.effectLayers[index];
  94576. if (layer.serialize) {
  94577. serializationObject.effectLayers.push(layer.serialize());
  94578. }
  94579. }
  94580. return serializationObject;
  94581. };
  94582. SceneSerializer.SerializeMesh = function (toSerialize /* Mesh || Mesh[] */, withParents, withChildren) {
  94583. if (withParents === void 0) { withParents = false; }
  94584. if (withChildren === void 0) { withChildren = false; }
  94585. var serializationObject = {};
  94586. SceneSerializer.ClearCache();
  94587. toSerialize = (toSerialize instanceof Array) ? toSerialize : [toSerialize];
  94588. if (withParents || withChildren) {
  94589. //deliberate for loop! not for each, appended should be processed as well.
  94590. for (var i = 0; i < toSerialize.length; ++i) {
  94591. if (withChildren) {
  94592. toSerialize[i].getDescendants().forEach(function (node) {
  94593. if (node instanceof BABYLON.Mesh && (toSerialize.indexOf(node) < 0)) {
  94594. toSerialize.push(node);
  94595. }
  94596. });
  94597. }
  94598. //make sure the array doesn't contain the object already
  94599. if (withParents && toSerialize[i].parent && (toSerialize.indexOf(toSerialize[i].parent) < 0)) {
  94600. toSerialize.push(toSerialize[i].parent);
  94601. }
  94602. }
  94603. }
  94604. toSerialize.forEach(function (mesh) {
  94605. finalizeSingleMesh(mesh, serializationObject);
  94606. });
  94607. return serializationObject;
  94608. };
  94609. return SceneSerializer;
  94610. }());
  94611. BABYLON.SceneSerializer = SceneSerializer;
  94612. })(BABYLON || (BABYLON = {}));
  94613. //# sourceMappingURL=babylon.sceneSerializer.js.map
  94614. var BABYLON;
  94615. (function (BABYLON) {
  94616. var ReflectionProbe = /** @class */ (function () {
  94617. function ReflectionProbe(name, size, scene, generateMipMaps) {
  94618. if (generateMipMaps === void 0) { generateMipMaps = true; }
  94619. var _this = this;
  94620. this.name = name;
  94621. this._viewMatrix = BABYLON.Matrix.Identity();
  94622. this._target = BABYLON.Vector3.Zero();
  94623. this._add = BABYLON.Vector3.Zero();
  94624. this._invertYAxis = false;
  94625. this.position = BABYLON.Vector3.Zero();
  94626. this._scene = scene;
  94627. this._scene.reflectionProbes.push(this);
  94628. this._renderTargetTexture = new BABYLON.RenderTargetTexture(name, size, scene, generateMipMaps, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, true);
  94629. this._renderTargetTexture.onBeforeRenderObservable.add(function (faceIndex) {
  94630. switch (faceIndex) {
  94631. case 0:
  94632. _this._add.copyFromFloats(1, 0, 0);
  94633. break;
  94634. case 1:
  94635. _this._add.copyFromFloats(-1, 0, 0);
  94636. break;
  94637. case 2:
  94638. _this._add.copyFromFloats(0, _this._invertYAxis ? 1 : -1, 0);
  94639. break;
  94640. case 3:
  94641. _this._add.copyFromFloats(0, _this._invertYAxis ? -1 : 1, 0);
  94642. break;
  94643. case 4:
  94644. _this._add.copyFromFloats(0, 0, 1);
  94645. break;
  94646. case 5:
  94647. _this._add.copyFromFloats(0, 0, -1);
  94648. break;
  94649. }
  94650. if (_this._attachedMesh) {
  94651. _this.position.copyFrom(_this._attachedMesh.getAbsolutePosition());
  94652. }
  94653. _this.position.addToRef(_this._add, _this._target);
  94654. BABYLON.Matrix.LookAtLHToRef(_this.position, _this._target, BABYLON.Vector3.Up(), _this._viewMatrix);
  94655. scene.setTransformMatrix(_this._viewMatrix, _this._projectionMatrix);
  94656. scene._forcedViewPosition = _this.position;
  94657. });
  94658. this._renderTargetTexture.onAfterUnbindObservable.add(function () {
  94659. scene._forcedViewPosition = null;
  94660. scene.updateTransformMatrix(true);
  94661. });
  94662. if (scene.activeCamera) {
  94663. this._projectionMatrix = BABYLON.Matrix.PerspectiveFovLH(Math.PI / 2, 1, scene.activeCamera.minZ, scene.activeCamera.maxZ);
  94664. }
  94665. }
  94666. Object.defineProperty(ReflectionProbe.prototype, "samples", {
  94667. get: function () {
  94668. return this._renderTargetTexture.samples;
  94669. },
  94670. set: function (value) {
  94671. this._renderTargetTexture.samples = value;
  94672. },
  94673. enumerable: true,
  94674. configurable: true
  94675. });
  94676. Object.defineProperty(ReflectionProbe.prototype, "refreshRate", {
  94677. get: function () {
  94678. return this._renderTargetTexture.refreshRate;
  94679. },
  94680. set: function (value) {
  94681. this._renderTargetTexture.refreshRate = value;
  94682. },
  94683. enumerable: true,
  94684. configurable: true
  94685. });
  94686. ReflectionProbe.prototype.getScene = function () {
  94687. return this._scene;
  94688. };
  94689. Object.defineProperty(ReflectionProbe.prototype, "cubeTexture", {
  94690. get: function () {
  94691. return this._renderTargetTexture;
  94692. },
  94693. enumerable: true,
  94694. configurable: true
  94695. });
  94696. Object.defineProperty(ReflectionProbe.prototype, "renderList", {
  94697. get: function () {
  94698. return this._renderTargetTexture.renderList;
  94699. },
  94700. enumerable: true,
  94701. configurable: true
  94702. });
  94703. ReflectionProbe.prototype.attachToMesh = function (mesh) {
  94704. this._attachedMesh = mesh;
  94705. };
  94706. /**
  94707. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  94708. *
  94709. * @param renderingGroupId The rendering group id corresponding to its index
  94710. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  94711. */
  94712. ReflectionProbe.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  94713. this._renderTargetTexture.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  94714. };
  94715. ReflectionProbe.prototype.dispose = function () {
  94716. var index = this._scene.reflectionProbes.indexOf(this);
  94717. if (index !== -1) {
  94718. // Remove from the scene if found
  94719. this._scene.reflectionProbes.splice(index, 1);
  94720. }
  94721. if (this._renderTargetTexture) {
  94722. this._renderTargetTexture.dispose();
  94723. this._renderTargetTexture = null;
  94724. }
  94725. };
  94726. return ReflectionProbe;
  94727. }());
  94728. BABYLON.ReflectionProbe = ReflectionProbe;
  94729. })(BABYLON || (BABYLON = {}));
  94730. //# sourceMappingURL=babylon.reflectionProbe.js.map
  94731. var BABYLON;
  94732. (function (BABYLON) {
  94733. var Layer = /** @class */ (function () {
  94734. function Layer(name, imgUrl, scene, isBackground, color) {
  94735. this.name = name;
  94736. this.scale = new BABYLON.Vector2(1, 1);
  94737. this.offset = new BABYLON.Vector2(0, 0);
  94738. this.alphaBlendingMode = BABYLON.Engine.ALPHA_COMBINE;
  94739. this.layerMask = 0x0FFFFFFF;
  94740. this._vertexBuffers = {};
  94741. // Events
  94742. /**
  94743. * An event triggered when the layer is disposed.
  94744. */
  94745. this.onDisposeObservable = new BABYLON.Observable();
  94746. /**
  94747. * An event triggered before rendering the scene
  94748. */
  94749. this.onBeforeRenderObservable = new BABYLON.Observable();
  94750. /**
  94751. * An event triggered after rendering the scene
  94752. */
  94753. this.onAfterRenderObservable = new BABYLON.Observable();
  94754. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  94755. this.isBackground = isBackground === undefined ? true : isBackground;
  94756. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  94757. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  94758. this._scene.layers.push(this);
  94759. var engine = this._scene.getEngine();
  94760. // VBO
  94761. var vertices = [];
  94762. vertices.push(1, 1);
  94763. vertices.push(-1, 1);
  94764. vertices.push(-1, -1);
  94765. vertices.push(1, -1);
  94766. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  94767. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  94768. this._createIndexBuffer();
  94769. // Effects
  94770. this._effect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "");
  94771. this._alphaTestEffect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "#define ALPHATEST");
  94772. }
  94773. Object.defineProperty(Layer.prototype, "onDispose", {
  94774. set: function (callback) {
  94775. if (this._onDisposeObserver) {
  94776. this.onDisposeObservable.remove(this._onDisposeObserver);
  94777. }
  94778. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  94779. },
  94780. enumerable: true,
  94781. configurable: true
  94782. });
  94783. Object.defineProperty(Layer.prototype, "onBeforeRender", {
  94784. set: function (callback) {
  94785. if (this._onBeforeRenderObserver) {
  94786. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  94787. }
  94788. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  94789. },
  94790. enumerable: true,
  94791. configurable: true
  94792. });
  94793. Object.defineProperty(Layer.prototype, "onAfterRender", {
  94794. set: function (callback) {
  94795. if (this._onAfterRenderObserver) {
  94796. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  94797. }
  94798. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  94799. },
  94800. enumerable: true,
  94801. configurable: true
  94802. });
  94803. Layer.prototype._createIndexBuffer = function () {
  94804. var engine = this._scene.getEngine();
  94805. // Indices
  94806. var indices = [];
  94807. indices.push(0);
  94808. indices.push(1);
  94809. indices.push(2);
  94810. indices.push(0);
  94811. indices.push(2);
  94812. indices.push(3);
  94813. this._indexBuffer = engine.createIndexBuffer(indices);
  94814. };
  94815. Layer.prototype._rebuild = function () {
  94816. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  94817. if (vb) {
  94818. vb._rebuild();
  94819. }
  94820. this._createIndexBuffer();
  94821. };
  94822. Layer.prototype.render = function () {
  94823. var currentEffect = this.alphaTest ? this._alphaTestEffect : this._effect;
  94824. // Check
  94825. if (!currentEffect.isReady() || !this.texture || !this.texture.isReady())
  94826. return;
  94827. var engine = this._scene.getEngine();
  94828. this.onBeforeRenderObservable.notifyObservers(this);
  94829. // Render
  94830. engine.enableEffect(currentEffect);
  94831. engine.setState(false);
  94832. // Texture
  94833. currentEffect.setTexture("textureSampler", this.texture);
  94834. currentEffect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  94835. // Color
  94836. currentEffect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  94837. // Scale / offset
  94838. currentEffect.setVector2("offset", this.offset);
  94839. currentEffect.setVector2("scale", this.scale);
  94840. // VBOs
  94841. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  94842. // Draw order
  94843. if (!this.alphaTest) {
  94844. engine.setAlphaMode(this.alphaBlendingMode);
  94845. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  94846. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  94847. }
  94848. else {
  94849. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  94850. }
  94851. this.onAfterRenderObservable.notifyObservers(this);
  94852. };
  94853. Layer.prototype.dispose = function () {
  94854. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  94855. if (vertexBuffer) {
  94856. vertexBuffer.dispose();
  94857. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  94858. }
  94859. if (this._indexBuffer) {
  94860. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  94861. this._indexBuffer = null;
  94862. }
  94863. if (this.texture) {
  94864. this.texture.dispose();
  94865. this.texture = null;
  94866. }
  94867. // Remove from scene
  94868. var index = this._scene.layers.indexOf(this);
  94869. this._scene.layers.splice(index, 1);
  94870. // Callback
  94871. this.onDisposeObservable.notifyObservers(this);
  94872. this.onDisposeObservable.clear();
  94873. this.onAfterRenderObservable.clear();
  94874. this.onBeforeRenderObservable.clear();
  94875. };
  94876. return Layer;
  94877. }());
  94878. BABYLON.Layer = Layer;
  94879. })(BABYLON || (BABYLON = {}));
  94880. //# sourceMappingURL=babylon.layer.js.map
  94881. var BABYLON;
  94882. (function (BABYLON) {
  94883. var TextureTools = /** @class */ (function () {
  94884. function TextureTools() {
  94885. }
  94886. /**
  94887. * Uses the GPU to create a copy texture rescaled at a given size
  94888. * @param texture Texture to copy from
  94889. * @param width Desired width
  94890. * @param height Desired height
  94891. * @return Generated texture
  94892. */
  94893. TextureTools.CreateResizedCopy = function (texture, width, height, useBilinearMode) {
  94894. if (useBilinearMode === void 0) { useBilinearMode = true; }
  94895. var scene = texture.getScene();
  94896. var engine = scene.getEngine();
  94897. var rtt = new BABYLON.RenderTargetTexture('resized' + texture.name, { width: width, height: height }, scene, !texture.noMipmap, true, texture._texture.type, false, texture._samplingMode, false);
  94898. rtt.wrapU = texture.wrapU;
  94899. rtt.wrapV = texture.wrapV;
  94900. rtt.uOffset = texture.uOffset;
  94901. rtt.vOffset = texture.vOffset;
  94902. rtt.uScale = texture.uScale;
  94903. rtt.vScale = texture.vScale;
  94904. rtt.uAng = texture.uAng;
  94905. rtt.vAng = texture.vAng;
  94906. rtt.wAng = texture.wAng;
  94907. rtt.coordinatesIndex = texture.coordinatesIndex;
  94908. rtt.level = texture.level;
  94909. rtt.anisotropicFilteringLevel = texture.anisotropicFilteringLevel;
  94910. rtt._texture.isReady = false;
  94911. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  94912. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  94913. var passPostProcess = new BABYLON.PassPostProcess("pass", 1, null, useBilinearMode ? BABYLON.Texture.BILINEAR_SAMPLINGMODE : BABYLON.Texture.NEAREST_SAMPLINGMODE, engine, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  94914. passPostProcess.getEffect().executeWhenCompiled(function () {
  94915. passPostProcess.onApply = function (effect) {
  94916. effect.setTexture("textureSampler", texture);
  94917. };
  94918. var internalTexture = rtt.getInternalTexture();
  94919. if (internalTexture) {
  94920. scene.postProcessManager.directRender([passPostProcess], internalTexture);
  94921. engine.unBindFramebuffer(internalTexture);
  94922. rtt.disposeFramebufferObjects();
  94923. passPostProcess.dispose();
  94924. internalTexture.isReady = true;
  94925. }
  94926. });
  94927. return rtt;
  94928. };
  94929. TextureTools.GetEnvironmentBRDFTexture = function (scene) {
  94930. if (!scene._environmentBRDFTexture) {
  94931. var texture = BABYLON.Texture.CreateFromBase64String(this._environmentBRDFBase64Texture, "EnvironmentBRDFTexture", scene, true, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  94932. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  94933. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  94934. scene._environmentBRDFTexture = texture;
  94935. }
  94936. return scene._environmentBRDFTexture;
  94937. };
  94938. 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=";
  94939. return TextureTools;
  94940. }());
  94941. BABYLON.TextureTools = TextureTools;
  94942. })(BABYLON || (BABYLON = {}));
  94943. //# sourceMappingURL=babylon.textureTools.js.map
  94944. var BABYLON;
  94945. (function (BABYLON) {
  94946. var FramingBehavior = /** @class */ (function () {
  94947. function FramingBehavior() {
  94948. this._mode = FramingBehavior.FitFrustumSidesMode;
  94949. this._radiusScale = 1.0;
  94950. this._positionScale = 0.5;
  94951. this._defaultElevation = 0.3;
  94952. this._elevationReturnTime = 1500;
  94953. this._elevationReturnWaitTime = 1000;
  94954. this._zoomStopsAnimation = false;
  94955. this._framingTime = 1500;
  94956. this._isPointerDown = false;
  94957. this._lastInteractionTime = -Infinity;
  94958. // Framing control
  94959. this._animatables = new Array();
  94960. this._betaIsAnimating = false;
  94961. }
  94962. Object.defineProperty(FramingBehavior.prototype, "name", {
  94963. get: function () {
  94964. return "Framing";
  94965. },
  94966. enumerable: true,
  94967. configurable: true
  94968. });
  94969. Object.defineProperty(FramingBehavior.prototype, "mode", {
  94970. /**
  94971. * Gets current mode used by the behavior.
  94972. */
  94973. get: function () {
  94974. return this._mode;
  94975. },
  94976. /**
  94977. * Sets the current mode used by the behavior
  94978. */
  94979. set: function (mode) {
  94980. this._mode = mode;
  94981. },
  94982. enumerable: true,
  94983. configurable: true
  94984. });
  94985. Object.defineProperty(FramingBehavior.prototype, "radiusScale", {
  94986. /**
  94987. * Gets the scale applied to the radius
  94988. */
  94989. get: function () {
  94990. return this._radiusScale;
  94991. },
  94992. /**
  94993. * Sets the scale applied to the radius (1 by default)
  94994. */
  94995. set: function (radius) {
  94996. this._radiusScale = radius;
  94997. },
  94998. enumerable: true,
  94999. configurable: true
  95000. });
  95001. Object.defineProperty(FramingBehavior.prototype, "positionScale", {
  95002. /**
  95003. * Gets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  95004. */
  95005. get: function () {
  95006. return this._positionScale;
  95007. },
  95008. /**
  95009. * Sets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  95010. */
  95011. set: function (scale) {
  95012. this._positionScale = scale;
  95013. },
  95014. enumerable: true,
  95015. configurable: true
  95016. });
  95017. Object.defineProperty(FramingBehavior.prototype, "defaultElevation", {
  95018. /**
  95019. * Gets the angle above/below the horizontal plane to return to when the return to default elevation idle
  95020. * behaviour is triggered, in radians.
  95021. */
  95022. get: function () {
  95023. return this._defaultElevation;
  95024. },
  95025. /**
  95026. * Sets the angle above/below the horizontal plane to return to when the return to default elevation idle
  95027. * behaviour is triggered, in radians.
  95028. */
  95029. set: function (elevation) {
  95030. this._defaultElevation = elevation;
  95031. },
  95032. enumerable: true,
  95033. configurable: true
  95034. });
  95035. Object.defineProperty(FramingBehavior.prototype, "elevationReturnTime", {
  95036. /**
  95037. * Gets the time (in milliseconds) taken to return to the default beta position.
  95038. * Negative value indicates camera should not return to default.
  95039. */
  95040. get: function () {
  95041. return this._elevationReturnTime;
  95042. },
  95043. /**
  95044. * Sets the time (in milliseconds) taken to return to the default beta position.
  95045. * Negative value indicates camera should not return to default.
  95046. */
  95047. set: function (speed) {
  95048. this._elevationReturnTime = speed;
  95049. },
  95050. enumerable: true,
  95051. configurable: true
  95052. });
  95053. Object.defineProperty(FramingBehavior.prototype, "elevationReturnWaitTime", {
  95054. /**
  95055. * Gets the delay (in milliseconds) taken before the camera returns to the default beta position.
  95056. */
  95057. get: function () {
  95058. return this._elevationReturnWaitTime;
  95059. },
  95060. /**
  95061. * Sets the delay (in milliseconds) taken before the camera returns to the default beta position.
  95062. */
  95063. set: function (time) {
  95064. this._elevationReturnWaitTime = time;
  95065. },
  95066. enumerable: true,
  95067. configurable: true
  95068. });
  95069. Object.defineProperty(FramingBehavior.prototype, "zoomStopsAnimation", {
  95070. /**
  95071. * Gets the flag that indicates if user zooming should stop animation.
  95072. */
  95073. get: function () {
  95074. return this._zoomStopsAnimation;
  95075. },
  95076. /**
  95077. * Sets the flag that indicates if user zooming should stop animation.
  95078. */
  95079. set: function (flag) {
  95080. this._zoomStopsAnimation = flag;
  95081. },
  95082. enumerable: true,
  95083. configurable: true
  95084. });
  95085. Object.defineProperty(FramingBehavior.prototype, "framingTime", {
  95086. /**
  95087. * Gets the transition time when framing the mesh, in milliseconds
  95088. */
  95089. get: function () {
  95090. return this._framingTime;
  95091. },
  95092. /**
  95093. * Sets the transition time when framing the mesh, in milliseconds
  95094. */
  95095. set: function (time) {
  95096. this._framingTime = time;
  95097. },
  95098. enumerable: true,
  95099. configurable: true
  95100. });
  95101. FramingBehavior.prototype.init = function () {
  95102. // Do notihng
  95103. };
  95104. FramingBehavior.prototype.attach = function (camera) {
  95105. var _this = this;
  95106. this._attachedCamera = camera;
  95107. var scene = this._attachedCamera.getScene();
  95108. FramingBehavior.EasingFunction.setEasingMode(FramingBehavior.EasingMode);
  95109. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  95110. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  95111. _this._isPointerDown = true;
  95112. return;
  95113. }
  95114. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  95115. _this._isPointerDown = false;
  95116. }
  95117. });
  95118. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  95119. if (mesh) {
  95120. _this.zoomOnMesh(mesh);
  95121. }
  95122. });
  95123. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  95124. // Stop the animation if there is user interaction and the animation should stop for this interaction
  95125. _this._applyUserInteraction();
  95126. // Maintain the camera above the ground. If the user pulls the camera beneath the ground plane, lift it
  95127. // back to the default position after a given timeout
  95128. _this._maintainCameraAboveGround();
  95129. });
  95130. };
  95131. FramingBehavior.prototype.detach = function () {
  95132. if (!this._attachedCamera) {
  95133. return;
  95134. }
  95135. var scene = this._attachedCamera.getScene();
  95136. if (this._onPrePointerObservableObserver) {
  95137. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  95138. }
  95139. if (this._onAfterCheckInputsObserver) {
  95140. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  95141. }
  95142. if (this._onMeshTargetChangedObserver) {
  95143. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  95144. }
  95145. this._attachedCamera = null;
  95146. };
  95147. /**
  95148. * Targets the given mesh and updates zoom level accordingly.
  95149. * @param mesh The mesh to target.
  95150. * @param radius Optional. If a cached radius position already exists, overrides default.
  95151. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  95152. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  95153. * @param onAnimationEnd Callback triggered at the end of the framing animation
  95154. */
  95155. FramingBehavior.prototype.zoomOnMesh = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  95156. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  95157. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  95158. mesh.computeWorldMatrix(true);
  95159. var boundingBox = mesh.getBoundingInfo().boundingBox;
  95160. this.zoomOnBoundingInfo(boundingBox.minimumWorld, boundingBox.maximumWorld, focusOnOriginXZ, onAnimationEnd);
  95161. };
  95162. /**
  95163. * Targets the given mesh with its children and updates zoom level accordingly.
  95164. * @param mesh The mesh to target.
  95165. * @param radius Optional. If a cached radius position already exists, overrides default.
  95166. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  95167. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  95168. * @param onAnimationEnd Callback triggered at the end of the framing animation
  95169. */
  95170. FramingBehavior.prototype.zoomOnMeshHierarchy = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  95171. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  95172. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  95173. mesh.computeWorldMatrix(true);
  95174. var boundingBox = mesh.getHierarchyBoundingVectors(true);
  95175. this.zoomOnBoundingInfo(boundingBox.min, boundingBox.max, focusOnOriginXZ, onAnimationEnd);
  95176. };
  95177. /**
  95178. * Targets the given meshes with their children and updates zoom level accordingly.
  95179. * @param meshes The mesh to target.
  95180. * @param radius Optional. If a cached radius position already exists, overrides default.
  95181. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  95182. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  95183. * @param onAnimationEnd Callback triggered at the end of the framing animation
  95184. */
  95185. FramingBehavior.prototype.zoomOnMeshesHierarchy = function (meshes, focusOnOriginXZ, onAnimationEnd) {
  95186. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  95187. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  95188. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  95189. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  95190. for (var i = 0; i < meshes.length; i++) {
  95191. var boundingInfo = meshes[i].getHierarchyBoundingVectors(true);
  95192. BABYLON.Tools.CheckExtends(boundingInfo.min, min, max);
  95193. BABYLON.Tools.CheckExtends(boundingInfo.max, min, max);
  95194. }
  95195. this.zoomOnBoundingInfo(min, max, focusOnOriginXZ, onAnimationEnd);
  95196. };
  95197. /**
  95198. * Targets the given mesh and updates zoom level accordingly.
  95199. * @param mesh The mesh to target.
  95200. * @param radius Optional. If a cached radius position already exists, overrides default.
  95201. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  95202. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  95203. * @param onAnimationEnd Callback triggered at the end of the framing animation
  95204. */
  95205. FramingBehavior.prototype.zoomOnBoundingInfo = function (minimumWorld, maximumWorld, focusOnOriginXZ, onAnimationEnd) {
  95206. var _this = this;
  95207. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  95208. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  95209. var zoomTarget;
  95210. if (!this._attachedCamera) {
  95211. return;
  95212. }
  95213. // Find target by interpolating from bottom of bounding box in world-space to top via framingPositionY
  95214. var bottom = minimumWorld.y;
  95215. var top = maximumWorld.y;
  95216. var zoomTargetY = bottom + (top - bottom) * this._positionScale;
  95217. var radiusWorld = maximumWorld.subtract(minimumWorld).scale(0.5);
  95218. if (focusOnOriginXZ) {
  95219. zoomTarget = new BABYLON.Vector3(0, zoomTargetY, 0);
  95220. }
  95221. else {
  95222. var centerWorld = minimumWorld.add(radiusWorld);
  95223. zoomTarget = new BABYLON.Vector3(centerWorld.x, zoomTargetY, centerWorld.z);
  95224. }
  95225. if (!this._vectorTransition) {
  95226. this._vectorTransition = BABYLON.Animation.CreateAnimation("target", BABYLON.Animation.ANIMATIONTYPE_VECTOR3, 60, FramingBehavior.EasingFunction);
  95227. }
  95228. this._betaIsAnimating = true;
  95229. var animatable = BABYLON.Animation.TransitionTo("target", zoomTarget, this._attachedCamera, this._attachedCamera.getScene(), 60, this._vectorTransition, this._framingTime);
  95230. if (animatable) {
  95231. this._animatables.push(animatable);
  95232. }
  95233. // sets the radius and lower radius bounds
  95234. // Small delta ensures camera is not always at lower zoom limit.
  95235. var radius = 0;
  95236. if (this._mode === FramingBehavior.FitFrustumSidesMode) {
  95237. var position = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  95238. this._attachedCamera.lowerRadiusLimit = radiusWorld.length() + this._attachedCamera.minZ;
  95239. radius = position;
  95240. }
  95241. else if (this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  95242. radius = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  95243. if (this._attachedCamera.lowerRadiusLimit === null) {
  95244. this._attachedCamera.lowerRadiusLimit = this._attachedCamera.minZ;
  95245. }
  95246. }
  95247. // Set sensibilities
  95248. var extend = maximumWorld.subtract(minimumWorld).length();
  95249. this._attachedCamera.panningSensibility = 5000 / extend;
  95250. this._attachedCamera.wheelPrecision = 100 / radius;
  95251. // transition to new radius
  95252. if (!this._radiusTransition) {
  95253. this._radiusTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  95254. }
  95255. animatable = BABYLON.Animation.TransitionTo("radius", radius, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusTransition, this._framingTime, function () {
  95256. _this.stopAllAnimations();
  95257. if (onAnimationEnd) {
  95258. onAnimationEnd();
  95259. }
  95260. if (_this._attachedCamera) {
  95261. _this._attachedCamera.storeState();
  95262. }
  95263. });
  95264. if (animatable) {
  95265. this._animatables.push(animatable);
  95266. }
  95267. };
  95268. /**
  95269. * Calculates the lowest radius for the camera based on the bounding box of the mesh.
  95270. * @param mesh The mesh on which to base the calculation. mesh boundingInfo used to estimate necessary
  95271. * frustum width.
  95272. * @return The minimum distance from the primary mesh's center point at which the camera must be kept in order
  95273. * to fully enclose the mesh in the viewing frustum.
  95274. */
  95275. FramingBehavior.prototype._calculateLowerRadiusFromModelBoundingSphere = function (minimumWorld, maximumWorld) {
  95276. var size = maximumWorld.subtract(minimumWorld);
  95277. var boxVectorGlobalDiagonal = size.length();
  95278. var frustumSlope = this._getFrustumSlope();
  95279. // Formula for setting distance
  95280. // (Good explanation: http://stackoverflow.com/questions/2866350/move-camera-to-fit-3d-scene)
  95281. var radiusWithoutFraming = boxVectorGlobalDiagonal * 0.5;
  95282. // Horizon distance
  95283. var radius = radiusWithoutFraming * this._radiusScale;
  95284. var distanceForHorizontalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.x * frustumSlope.x));
  95285. var distanceForVerticalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.y * frustumSlope.y));
  95286. var distance = Math.max(distanceForHorizontalFrustum, distanceForVerticalFrustum);
  95287. var camera = this._attachedCamera;
  95288. if (!camera) {
  95289. return 0;
  95290. }
  95291. if (camera.lowerRadiusLimit && this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  95292. // Don't exceed the requested limit
  95293. distance = distance < camera.lowerRadiusLimit ? camera.lowerRadiusLimit : distance;
  95294. }
  95295. // Don't exceed the upper radius limit
  95296. if (camera.upperRadiusLimit) {
  95297. distance = distance > camera.upperRadiusLimit ? camera.upperRadiusLimit : distance;
  95298. }
  95299. return distance;
  95300. };
  95301. /**
  95302. * Keeps the camera above the ground plane. If the user pulls the camera below the ground plane, the camera
  95303. * is automatically returned to its default position (expected to be above ground plane).
  95304. */
  95305. FramingBehavior.prototype._maintainCameraAboveGround = function () {
  95306. var _this = this;
  95307. if (this._elevationReturnTime < 0) {
  95308. return;
  95309. }
  95310. var timeSinceInteraction = BABYLON.Tools.Now - this._lastInteractionTime;
  95311. var defaultBeta = Math.PI * 0.5 - this._defaultElevation;
  95312. var limitBeta = Math.PI * 0.5;
  95313. // Bring the camera back up if below the ground plane
  95314. if (this._attachedCamera && !this._betaIsAnimating && this._attachedCamera.beta > limitBeta && timeSinceInteraction >= this._elevationReturnWaitTime) {
  95315. this._betaIsAnimating = true;
  95316. //Transition to new position
  95317. this.stopAllAnimations();
  95318. if (!this._betaTransition) {
  95319. this._betaTransition = BABYLON.Animation.CreateAnimation("beta", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  95320. }
  95321. var animatabe = BABYLON.Animation.TransitionTo("beta", defaultBeta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._betaTransition, this._elevationReturnTime, function () {
  95322. _this._clearAnimationLocks();
  95323. _this.stopAllAnimations();
  95324. });
  95325. if (animatabe) {
  95326. this._animatables.push(animatabe);
  95327. }
  95328. }
  95329. };
  95330. /**
  95331. * Returns the frustum slope based on the canvas ratio and camera FOV
  95332. * @returns The frustum slope represented as a Vector2 with X and Y slopes
  95333. */
  95334. FramingBehavior.prototype._getFrustumSlope = function () {
  95335. // Calculate the viewport ratio
  95336. // Aspect Ratio is Height/Width.
  95337. var camera = this._attachedCamera;
  95338. if (!camera) {
  95339. return BABYLON.Vector2.Zero();
  95340. }
  95341. var engine = camera.getScene().getEngine();
  95342. var aspectRatio = engine.getAspectRatio(camera);
  95343. // Camera FOV is the vertical field of view (top-bottom) in radians.
  95344. // Slope of the frustum top/bottom planes in view space, relative to the forward vector.
  95345. var frustumSlopeY = Math.tan(camera.fov / 2);
  95346. // Slope of the frustum left/right planes in view space, relative to the forward vector.
  95347. // Provides the amount that one side (e.g. left) of the frustum gets wider for every unit
  95348. // along the forward vector.
  95349. var frustumSlopeX = frustumSlopeY * aspectRatio;
  95350. return new BABYLON.Vector2(frustumSlopeX, frustumSlopeY);
  95351. };
  95352. /**
  95353. * Removes all animation locks. Allows new animations to be added to any of the arcCamera properties.
  95354. */
  95355. FramingBehavior.prototype._clearAnimationLocks = function () {
  95356. this._betaIsAnimating = false;
  95357. };
  95358. /**
  95359. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  95360. */
  95361. FramingBehavior.prototype._applyUserInteraction = function () {
  95362. if (this.isUserIsMoving) {
  95363. this._lastInteractionTime = BABYLON.Tools.Now;
  95364. this.stopAllAnimations();
  95365. this._clearAnimationLocks();
  95366. }
  95367. };
  95368. /**
  95369. * Stops and removes all animations that have been applied to the camera
  95370. */
  95371. FramingBehavior.prototype.stopAllAnimations = function () {
  95372. if (this._attachedCamera) {
  95373. this._attachedCamera.animations = [];
  95374. }
  95375. while (this._animatables.length) {
  95376. if (this._animatables[0]) {
  95377. this._animatables[0].onAnimationEnd = null;
  95378. this._animatables[0].stop();
  95379. }
  95380. this._animatables.shift();
  95381. }
  95382. };
  95383. Object.defineProperty(FramingBehavior.prototype, "isUserIsMoving", {
  95384. /**
  95385. * Gets a value indicating if the user is moving the camera
  95386. */
  95387. get: function () {
  95388. if (!this._attachedCamera) {
  95389. return false;
  95390. }
  95391. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  95392. this._attachedCamera.inertialBetaOffset !== 0 ||
  95393. this._attachedCamera.inertialRadiusOffset !== 0 ||
  95394. this._attachedCamera.inertialPanningX !== 0 ||
  95395. this._attachedCamera.inertialPanningY !== 0 ||
  95396. this._isPointerDown;
  95397. },
  95398. enumerable: true,
  95399. configurable: true
  95400. });
  95401. /**
  95402. * The easing function used by animations
  95403. */
  95404. FramingBehavior.EasingFunction = new BABYLON.ExponentialEase();
  95405. /**
  95406. * The easing mode used by animations
  95407. */
  95408. FramingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEINOUT;
  95409. // Statics
  95410. /**
  95411. * The camera can move all the way towards the mesh.
  95412. */
  95413. FramingBehavior.IgnoreBoundsSizeMode = 0;
  95414. /**
  95415. * The camera is not allowed to zoom closer to the mesh than the point at which the adjusted bounding sphere touches the frustum sides
  95416. */
  95417. FramingBehavior.FitFrustumSidesMode = 1;
  95418. return FramingBehavior;
  95419. }());
  95420. BABYLON.FramingBehavior = FramingBehavior;
  95421. })(BABYLON || (BABYLON = {}));
  95422. //# sourceMappingURL=babylon.framingBehavior.js.map
  95423. var BABYLON;
  95424. (function (BABYLON) {
  95425. /**
  95426. * Add a bouncing effect to an ArcRotateCamera when reaching a specified minimum and maximum radius
  95427. */
  95428. var BouncingBehavior = /** @class */ (function () {
  95429. function BouncingBehavior() {
  95430. /**
  95431. * The duration of the animation, in milliseconds
  95432. */
  95433. this.transitionDuration = 450;
  95434. /**
  95435. * Length of the distance animated by the transition when lower radius is reached
  95436. */
  95437. this.lowerRadiusTransitionRange = 2;
  95438. /**
  95439. * Length of the distance animated by the transition when upper radius is reached
  95440. */
  95441. this.upperRadiusTransitionRange = -2;
  95442. this._autoTransitionRange = false;
  95443. // Animations
  95444. this._radiusIsAnimating = false;
  95445. this._radiusBounceTransition = null;
  95446. this._animatables = new Array();
  95447. }
  95448. Object.defineProperty(BouncingBehavior.prototype, "name", {
  95449. get: function () {
  95450. return "Bouncing";
  95451. },
  95452. enumerable: true,
  95453. configurable: true
  95454. });
  95455. Object.defineProperty(BouncingBehavior.prototype, "autoTransitionRange", {
  95456. /**
  95457. * Gets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  95458. */
  95459. get: function () {
  95460. return this._autoTransitionRange;
  95461. },
  95462. /**
  95463. * Sets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  95464. * Transition ranges will be set to 5% of the bounding box diagonal in world space
  95465. */
  95466. set: function (value) {
  95467. var _this = this;
  95468. if (this._autoTransitionRange === value) {
  95469. return;
  95470. }
  95471. this._autoTransitionRange = value;
  95472. var camera = this._attachedCamera;
  95473. if (!camera) {
  95474. return;
  95475. }
  95476. if (value) {
  95477. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  95478. if (!mesh) {
  95479. return;
  95480. }
  95481. mesh.computeWorldMatrix(true);
  95482. var diagonal = mesh.getBoundingInfo().diagonalLength;
  95483. _this.lowerRadiusTransitionRange = diagonal * 0.05;
  95484. _this.upperRadiusTransitionRange = diagonal * 0.05;
  95485. });
  95486. }
  95487. else if (this._onMeshTargetChangedObserver) {
  95488. camera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  95489. }
  95490. },
  95491. enumerable: true,
  95492. configurable: true
  95493. });
  95494. BouncingBehavior.prototype.init = function () {
  95495. // Do notihng
  95496. };
  95497. BouncingBehavior.prototype.attach = function (camera) {
  95498. var _this = this;
  95499. this._attachedCamera = camera;
  95500. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  95501. if (!_this._attachedCamera) {
  95502. return;
  95503. }
  95504. // Add the bounce animation to the lower radius limit
  95505. if (_this._isRadiusAtLimit(_this._attachedCamera.lowerRadiusLimit)) {
  95506. _this._applyBoundRadiusAnimation(_this.lowerRadiusTransitionRange);
  95507. }
  95508. // Add the bounce animation to the upper radius limit
  95509. if (_this._isRadiusAtLimit(_this._attachedCamera.upperRadiusLimit)) {
  95510. _this._applyBoundRadiusAnimation(_this.upperRadiusTransitionRange);
  95511. }
  95512. });
  95513. };
  95514. BouncingBehavior.prototype.detach = function () {
  95515. if (!this._attachedCamera) {
  95516. return;
  95517. }
  95518. if (this._onAfterCheckInputsObserver) {
  95519. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  95520. }
  95521. if (this._onMeshTargetChangedObserver) {
  95522. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  95523. }
  95524. this._attachedCamera = null;
  95525. };
  95526. /**
  95527. * Checks if the camera radius is at the specified limit. Takes into account animation locks.
  95528. * @param radiusLimit The limit to check against.
  95529. * @return Bool to indicate if at limit.
  95530. */
  95531. BouncingBehavior.prototype._isRadiusAtLimit = function (radiusLimit) {
  95532. if (!this._attachedCamera) {
  95533. return false;
  95534. }
  95535. if (this._attachedCamera.radius === radiusLimit && !this._radiusIsAnimating) {
  95536. return true;
  95537. }
  95538. return false;
  95539. };
  95540. /**
  95541. * Applies an animation to the radius of the camera, extending by the radiusDelta.
  95542. * @param radiusDelta The delta by which to animate to. Can be negative.
  95543. */
  95544. BouncingBehavior.prototype._applyBoundRadiusAnimation = function (radiusDelta) {
  95545. var _this = this;
  95546. if (!this._attachedCamera) {
  95547. return;
  95548. }
  95549. if (!this._radiusBounceTransition) {
  95550. BouncingBehavior.EasingFunction.setEasingMode(BouncingBehavior.EasingMode);
  95551. this._radiusBounceTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, BouncingBehavior.EasingFunction);
  95552. }
  95553. // Prevent zoom until bounce has completed
  95554. this._cachedWheelPrecision = this._attachedCamera.wheelPrecision;
  95555. this._attachedCamera.wheelPrecision = Infinity;
  95556. this._attachedCamera.inertialRadiusOffset = 0;
  95557. // Animate to the radius limit
  95558. this.stopAllAnimations();
  95559. this._radiusIsAnimating = true;
  95560. var animatable = BABYLON.Animation.TransitionTo("radius", this._attachedCamera.radius + radiusDelta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusBounceTransition, this.transitionDuration, function () { return _this._clearAnimationLocks(); });
  95561. if (animatable) {
  95562. this._animatables.push(animatable);
  95563. }
  95564. };
  95565. /**
  95566. * Removes all animation locks. Allows new animations to be added to any of the camera properties.
  95567. */
  95568. BouncingBehavior.prototype._clearAnimationLocks = function () {
  95569. this._radiusIsAnimating = false;
  95570. if (this._attachedCamera) {
  95571. this._attachedCamera.wheelPrecision = this._cachedWheelPrecision;
  95572. }
  95573. };
  95574. /**
  95575. * Stops and removes all animations that have been applied to the camera
  95576. */
  95577. BouncingBehavior.prototype.stopAllAnimations = function () {
  95578. if (this._attachedCamera) {
  95579. this._attachedCamera.animations = [];
  95580. }
  95581. while (this._animatables.length) {
  95582. this._animatables[0].onAnimationEnd = null;
  95583. this._animatables[0].stop();
  95584. this._animatables.shift();
  95585. }
  95586. };
  95587. /**
  95588. * The easing function used by animations
  95589. */
  95590. BouncingBehavior.EasingFunction = new BABYLON.BackEase(0.3);
  95591. /**
  95592. * The easing mode used by animations
  95593. */
  95594. BouncingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEOUT;
  95595. return BouncingBehavior;
  95596. }());
  95597. BABYLON.BouncingBehavior = BouncingBehavior;
  95598. })(BABYLON || (BABYLON = {}));
  95599. //# sourceMappingURL=babylon.bouncingBehavior.js.map
  95600. var BABYLON;
  95601. (function (BABYLON) {
  95602. var AutoRotationBehavior = /** @class */ (function () {
  95603. function AutoRotationBehavior() {
  95604. this._zoomStopsAnimation = false;
  95605. this._idleRotationSpeed = 0.05;
  95606. this._idleRotationWaitTime = 2000;
  95607. this._idleRotationSpinupTime = 2000;
  95608. this._isPointerDown = false;
  95609. this._lastFrameTime = null;
  95610. this._lastInteractionTime = -Infinity;
  95611. this._cameraRotationSpeed = 0;
  95612. this._lastFrameRadius = 0;
  95613. }
  95614. Object.defineProperty(AutoRotationBehavior.prototype, "name", {
  95615. get: function () {
  95616. return "AutoRotation";
  95617. },
  95618. enumerable: true,
  95619. configurable: true
  95620. });
  95621. Object.defineProperty(AutoRotationBehavior.prototype, "zoomStopsAnimation", {
  95622. /**
  95623. * Gets the flag that indicates if user zooming should stop animation.
  95624. */
  95625. get: function () {
  95626. return this._zoomStopsAnimation;
  95627. },
  95628. /**
  95629. * Sets the flag that indicates if user zooming should stop animation.
  95630. */
  95631. set: function (flag) {
  95632. this._zoomStopsAnimation = flag;
  95633. },
  95634. enumerable: true,
  95635. configurable: true
  95636. });
  95637. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpeed", {
  95638. /**
  95639. * Gets the default speed at which the camera rotates around the model.
  95640. */
  95641. get: function () {
  95642. return this._idleRotationSpeed;
  95643. },
  95644. /**
  95645. * Sets the default speed at which the camera rotates around the model.
  95646. */
  95647. set: function (speed) {
  95648. this._idleRotationSpeed = speed;
  95649. },
  95650. enumerable: true,
  95651. configurable: true
  95652. });
  95653. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationWaitTime", {
  95654. /**
  95655. * Gets the time (milliseconds) to wait after user interaction before the camera starts rotating.
  95656. */
  95657. get: function () {
  95658. return this._idleRotationWaitTime;
  95659. },
  95660. /**
  95661. * Sets the time (in milliseconds) to wait after user interaction before the camera starts rotating.
  95662. */
  95663. set: function (time) {
  95664. this._idleRotationWaitTime = time;
  95665. },
  95666. enumerable: true,
  95667. configurable: true
  95668. });
  95669. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpinupTime", {
  95670. /**
  95671. * Gets the time (milliseconds) to take to spin up to the full idle rotation speed.
  95672. */
  95673. get: function () {
  95674. return this._idleRotationSpinupTime;
  95675. },
  95676. /**
  95677. * Sets the time (milliseconds) to take to spin up to the full idle rotation speed.
  95678. */
  95679. set: function (time) {
  95680. this._idleRotationSpinupTime = time;
  95681. },
  95682. enumerable: true,
  95683. configurable: true
  95684. });
  95685. Object.defineProperty(AutoRotationBehavior.prototype, "rotationInProgress", {
  95686. /**
  95687. * Gets a value indicating if the camera is currently rotating because of this behavior
  95688. */
  95689. get: function () {
  95690. return Math.abs(this._cameraRotationSpeed) > 0;
  95691. },
  95692. enumerable: true,
  95693. configurable: true
  95694. });
  95695. AutoRotationBehavior.prototype.init = function () {
  95696. // Do notihng
  95697. };
  95698. AutoRotationBehavior.prototype.attach = function (camera) {
  95699. var _this = this;
  95700. this._attachedCamera = camera;
  95701. var scene = this._attachedCamera.getScene();
  95702. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  95703. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  95704. _this._isPointerDown = true;
  95705. return;
  95706. }
  95707. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  95708. _this._isPointerDown = false;
  95709. }
  95710. });
  95711. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  95712. var now = BABYLON.Tools.Now;
  95713. var dt = 0;
  95714. if (_this._lastFrameTime != null) {
  95715. dt = now - _this._lastFrameTime;
  95716. }
  95717. _this._lastFrameTime = now;
  95718. // Stop the animation if there is user interaction and the animation should stop for this interaction
  95719. _this._applyUserInteraction();
  95720. var timeToRotation = now - _this._lastInteractionTime - _this._idleRotationWaitTime;
  95721. var scale = Math.max(Math.min(timeToRotation / (_this._idleRotationSpinupTime), 1), 0);
  95722. _this._cameraRotationSpeed = _this._idleRotationSpeed * scale;
  95723. // Step camera rotation by rotation speed
  95724. if (_this._attachedCamera) {
  95725. _this._attachedCamera.alpha -= _this._cameraRotationSpeed * (dt / 1000);
  95726. }
  95727. });
  95728. };
  95729. AutoRotationBehavior.prototype.detach = function () {
  95730. if (!this._attachedCamera) {
  95731. return;
  95732. }
  95733. var scene = this._attachedCamera.getScene();
  95734. if (this._onPrePointerObservableObserver) {
  95735. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  95736. }
  95737. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  95738. this._attachedCamera = null;
  95739. };
  95740. /**
  95741. * Returns true if user is scrolling.
  95742. * @return true if user is scrolling.
  95743. */
  95744. AutoRotationBehavior.prototype._userIsZooming = function () {
  95745. if (!this._attachedCamera) {
  95746. return false;
  95747. }
  95748. return this._attachedCamera.inertialRadiusOffset !== 0;
  95749. };
  95750. AutoRotationBehavior.prototype._shouldAnimationStopForInteraction = function () {
  95751. if (!this._attachedCamera) {
  95752. return false;
  95753. }
  95754. var zoomHasHitLimit = false;
  95755. if (this._lastFrameRadius === this._attachedCamera.radius && this._attachedCamera.inertialRadiusOffset !== 0) {
  95756. zoomHasHitLimit = true;
  95757. }
  95758. // Update the record of previous radius - works as an approx. indicator of hitting radius limits
  95759. this._lastFrameRadius = this._attachedCamera.radius;
  95760. return this._zoomStopsAnimation ? zoomHasHitLimit : this._userIsZooming();
  95761. };
  95762. /**
  95763. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  95764. */
  95765. AutoRotationBehavior.prototype._applyUserInteraction = function () {
  95766. if (this._userIsMoving() && !this._shouldAnimationStopForInteraction()) {
  95767. this._lastInteractionTime = BABYLON.Tools.Now;
  95768. }
  95769. };
  95770. // Tools
  95771. AutoRotationBehavior.prototype._userIsMoving = function () {
  95772. if (!this._attachedCamera) {
  95773. return false;
  95774. }
  95775. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  95776. this._attachedCamera.inertialBetaOffset !== 0 ||
  95777. this._attachedCamera.inertialRadiusOffset !== 0 ||
  95778. this._attachedCamera.inertialPanningX !== 0 ||
  95779. this._attachedCamera.inertialPanningY !== 0 ||
  95780. this._isPointerDown;
  95781. };
  95782. return AutoRotationBehavior;
  95783. }());
  95784. BABYLON.AutoRotationBehavior = AutoRotationBehavior;
  95785. })(BABYLON || (BABYLON = {}));
  95786. //# sourceMappingURL=babylon.autoRotationBehavior.js.map
  95787. var BABYLON;
  95788. (function (BABYLON) {
  95789. /**
  95790. * A behavior that when attached to a mesh will allow the mesh to be dragged around the screen based on pointer events
  95791. */
  95792. var PointerDragBehavior = /** @class */ (function () {
  95793. /**
  95794. * Creates a pointer drag behavior that can be attached to a mesh
  95795. * @param options The drag axis or normal of the plane that will be dragged across. pointerObservableScene can be used to listen to drag events from another scene(eg. if the attached mesh is in an overlay scene).
  95796. */
  95797. function PointerDragBehavior(options) {
  95798. this.options = options;
  95799. this._draggingID = -1;
  95800. /**
  95801. * Fires each time the attached mesh is dragged with the pointer
  95802. */
  95803. this.onDragObservable = new BABYLON.Observable();
  95804. /**
  95805. * Fires each time a drag begins (eg. mouse down on mesh)
  95806. */
  95807. this.onDragStartObservable = new BABYLON.Observable();
  95808. /**
  95809. * Fires each time a drag ends (eg. mouse release after drag)
  95810. */
  95811. this.onDragEndObservable = new BABYLON.Observable();
  95812. /**
  95813. * If the attached mesh should be moved when dragged
  95814. */
  95815. this.moveAttached = true;
  95816. /**
  95817. * Mesh with the position where the drag plane should be placed
  95818. */
  95819. this._dragPlaneParent = null;
  95820. var optionCount = 0;
  95821. if (options.dragAxis) {
  95822. optionCount++;
  95823. }
  95824. if (options.dragPlaneNormal) {
  95825. optionCount++;
  95826. }
  95827. if (optionCount > 1) {
  95828. throw "Multiple drag modes specified in dragBehavior options. Only one expected";
  95829. }
  95830. if (optionCount < 1) {
  95831. throw "At least one drag mode option must be specified";
  95832. }
  95833. }
  95834. Object.defineProperty(PointerDragBehavior.prototype, "name", {
  95835. /**
  95836. * The name of the behavior
  95837. */
  95838. get: function () {
  95839. return "PointerDrag";
  95840. },
  95841. enumerable: true,
  95842. configurable: true
  95843. });
  95844. /**
  95845. * Initializes the behavior
  95846. */
  95847. PointerDragBehavior.prototype.init = function () { };
  95848. /**
  95849. * Attaches the drag behavior the passed in mesh
  95850. * @param ownerNode The mesh that will be dragged around once attached
  95851. */
  95852. PointerDragBehavior.prototype.attach = function (ownerNode) {
  95853. var _this = this;
  95854. this._scene = ownerNode.getScene();
  95855. if (!this.options.pointerObservableScene) {
  95856. this.options.pointerObservableScene = this._scene;
  95857. }
  95858. this._attachedNode = ownerNode;
  95859. // Initialize drag plane to not interfere with existing scene
  95860. if (!PointerDragBehavior._planeScene) {
  95861. PointerDragBehavior._planeScene = new BABYLON.Scene(this._scene.getEngine());
  95862. this._scene.getEngine().scenes.pop();
  95863. }
  95864. this._dragPlane = BABYLON.Mesh.CreatePlane("pointerDragPlane", 1000, PointerDragBehavior._planeScene, false, BABYLON.Mesh.DOUBLESIDE);
  95865. // State of the drag
  95866. var dragging = false;
  95867. var lastPosition = new BABYLON.Vector3(0, 0, 0);
  95868. var delta = new BABYLON.Vector3(0, 0, 0);
  95869. var pickPredicate = function (m) {
  95870. return _this._attachedNode == m || m.isDescendantOf(_this._attachedNode);
  95871. };
  95872. this._pointerObserver = this.options.pointerObservableScene.onPrePointerObservable.add(function (pointerInfoPre, eventState) {
  95873. // Check if attached mesh is picked
  95874. var pickInfo = pointerInfoPre.ray ? _this._scene.pickWithRay(pointerInfoPre.ray, pickPredicate) : _this._scene.pick(_this._scene.pointerX, _this._scene.pointerY, pickPredicate);
  95875. if (pickInfo) {
  95876. pickInfo.ray = pointerInfoPre.ray;
  95877. if (!pickInfo.ray) {
  95878. pickInfo.ray = _this.options.pointerObservableScene.createPickingRay(_this._scene.pointerX, _this._scene.pointerY, BABYLON.Matrix.Identity(), _this._scene.activeCamera);
  95879. }
  95880. if (pickInfo.hit) {
  95881. eventState.skipNextObservers = true;
  95882. }
  95883. }
  95884. if (pointerInfoPre.type == BABYLON.PointerEventTypes.POINTERDOWN) {
  95885. if (!dragging && pickInfo && pickInfo.hit && pickInfo.pickedMesh && pickInfo.ray) {
  95886. _this._updateDragPlanePosition(pickInfo.ray);
  95887. var pickedPoint = _this._pickWithRayOnDragPlane(pickInfo.ray);
  95888. if (pickedPoint) {
  95889. dragging = true;
  95890. _this._draggingID = pointerInfoPre.event.pointerId;
  95891. lastPosition.copyFrom(pickedPoint);
  95892. _this.onDragStartObservable.notifyObservers({ dragPlanePoint: pickedPoint });
  95893. }
  95894. }
  95895. }
  95896. else if (pointerInfoPre.type == BABYLON.PointerEventTypes.POINTERUP) {
  95897. if (_this._draggingID == pointerInfoPre.event.pointerId) {
  95898. dragging = false;
  95899. _this._draggingID = -1;
  95900. _this.onDragEndObservable.notifyObservers({ dragPlanePoint: lastPosition });
  95901. }
  95902. }
  95903. else if (pointerInfoPre.type == BABYLON.PointerEventTypes.POINTERMOVE) {
  95904. if (_this._draggingID == pointerInfoPre.event.pointerId && dragging && pickInfo && pickInfo.ray) {
  95905. var pickedPoint = _this._pickWithRayOnDragPlane(pickInfo.ray);
  95906. _this._updateDragPlanePosition(pickInfo.ray);
  95907. if (pickedPoint) {
  95908. // depending on the drag mode option drag accordingly
  95909. if (_this.options.dragAxis) {
  95910. //get the closest point on the dragaxis from the selected mesh to the picked point location
  95911. // https://www.opengl.org/discussion_boards/showthread.php/159717-Closest-point-on-a-Vector-to-a-point
  95912. _this.options.dragAxis.scaleToRef(BABYLON.Vector3.Dot(pickedPoint.subtract(lastPosition), _this.options.dragAxis), delta);
  95913. }
  95914. else {
  95915. pickedPoint.subtractToRef(lastPosition, delta);
  95916. }
  95917. if (_this.moveAttached) {
  95918. _this._attachedNode.position.addInPlace(delta);
  95919. }
  95920. _this.onDragObservable.notifyObservers({ delta: delta, dragPlanePoint: pickedPoint });
  95921. lastPosition.copyFrom(pickedPoint);
  95922. }
  95923. }
  95924. }
  95925. });
  95926. };
  95927. PointerDragBehavior.prototype._pickWithRayOnDragPlane = function (ray) {
  95928. var _this = this;
  95929. if (!ray) {
  95930. return null;
  95931. }
  95932. var pickResult = PointerDragBehavior._planeScene.pickWithRay(ray, function (m) { return m == _this._dragPlane; });
  95933. if (pickResult && pickResult.hit && pickResult.pickedMesh && pickResult.pickedPoint) {
  95934. return pickResult.pickedPoint;
  95935. }
  95936. else {
  95937. return null;
  95938. }
  95939. };
  95940. // Position the drag plane based on the attached mesh position, for single axis rotate the plane along the axis to face the camera
  95941. PointerDragBehavior.prototype._updateDragPlanePosition = function (ray) {
  95942. var pointA = this._dragPlaneParent ? this._dragPlaneParent.position : this._attachedNode.position; // center
  95943. if (this.options.dragAxis) {
  95944. var camPos = ray.origin;
  95945. // Calculate plane normal in direction of camera but perpendicular to drag axis
  95946. var pointB = pointA.add(this.options.dragAxis); // towards drag axis
  95947. var pointC = pointA.add(camPos.subtract(pointA).normalize()); // towards camera
  95948. // Get perpendicular line from direction to camera and drag axis
  95949. var lineA = pointB.subtract(pointA);
  95950. var lineB = pointC.subtract(pointA);
  95951. var perpLine = BABYLON.Vector3.Cross(lineA, lineB);
  95952. // Get perpendicular line from previous result and drag axis to adjust lineB to be perpendiculat to camera
  95953. var norm = BABYLON.Vector3.Cross(lineA, perpLine).normalize();
  95954. this._dragPlane.position.copyFrom(pointA);
  95955. this._dragPlane.lookAt(pointA.add(norm));
  95956. }
  95957. else if (this.options.dragPlaneNormal) {
  95958. this._dragPlane.position.copyFrom(pointA);
  95959. this._dragPlane.lookAt(pointA.add(this.options.dragPlaneNormal));
  95960. }
  95961. this._dragPlane.computeWorldMatrix(true);
  95962. };
  95963. /**
  95964. * Detaches the behavior from the mesh
  95965. */
  95966. PointerDragBehavior.prototype.detach = function () {
  95967. if (this._pointerObserver) {
  95968. this._scene.onPrePointerObservable.remove(this._pointerObserver);
  95969. }
  95970. };
  95971. return PointerDragBehavior;
  95972. }());
  95973. BABYLON.PointerDragBehavior = PointerDragBehavior;
  95974. })(BABYLON || (BABYLON = {}));
  95975. //# sourceMappingURL=babylon.pointerDragBehavior.js.map
  95976. var BABYLON;
  95977. (function (BABYLON) {
  95978. var NullEngineOptions = /** @class */ (function () {
  95979. function NullEngineOptions() {
  95980. this.renderWidth = 512;
  95981. this.renderHeight = 256;
  95982. this.textureSize = 512;
  95983. this.deterministicLockstep = false;
  95984. this.lockstepMaxSteps = 4;
  95985. }
  95986. return NullEngineOptions;
  95987. }());
  95988. BABYLON.NullEngineOptions = NullEngineOptions;
  95989. /**
  95990. * The null engine class provides support for headless version of babylon.js.
  95991. * This can be used in server side scenario or for testing purposes
  95992. */
  95993. var NullEngine = /** @class */ (function (_super) {
  95994. __extends(NullEngine, _super);
  95995. function NullEngine(options) {
  95996. if (options === void 0) { options = new NullEngineOptions(); }
  95997. var _this = _super.call(this, null) || this;
  95998. if (options.deterministicLockstep === undefined) {
  95999. options.deterministicLockstep = false;
  96000. }
  96001. if (options.lockstepMaxSteps === undefined) {
  96002. options.lockstepMaxSteps = 4;
  96003. }
  96004. _this._options = options;
  96005. // Init caps
  96006. // We consider we are on a webgl1 capable device
  96007. _this._caps = new BABYLON.EngineCapabilities();
  96008. _this._caps.maxTexturesImageUnits = 16;
  96009. _this._caps.maxVertexTextureImageUnits = 16;
  96010. _this._caps.maxTextureSize = 512;
  96011. _this._caps.maxCubemapTextureSize = 512;
  96012. _this._caps.maxRenderTextureSize = 512;
  96013. _this._caps.maxVertexAttribs = 16;
  96014. _this._caps.maxVaryingVectors = 16;
  96015. _this._caps.maxFragmentUniformVectors = 16;
  96016. _this._caps.maxVertexUniformVectors = 16;
  96017. // Extensions
  96018. _this._caps.standardDerivatives = false;
  96019. _this._caps.astc = null;
  96020. _this._caps.s3tc = null;
  96021. _this._caps.pvrtc = null;
  96022. _this._caps.etc1 = null;
  96023. _this._caps.etc2 = null;
  96024. _this._caps.textureAnisotropicFilterExtension = null;
  96025. _this._caps.maxAnisotropy = 0;
  96026. _this._caps.uintIndices = false;
  96027. _this._caps.fragmentDepthSupported = false;
  96028. _this._caps.highPrecisionShaderSupported = true;
  96029. _this._caps.colorBufferFloat = false;
  96030. _this._caps.textureFloat = false;
  96031. _this._caps.textureFloatLinearFiltering = false;
  96032. _this._caps.textureFloatRender = false;
  96033. _this._caps.textureHalfFloat = false;
  96034. _this._caps.textureHalfFloatLinearFiltering = false;
  96035. _this._caps.textureHalfFloatRender = false;
  96036. _this._caps.textureLOD = false;
  96037. _this._caps.drawBuffersExtension = false;
  96038. _this._caps.depthTextureExtension = false;
  96039. _this._caps.vertexArrayObject = false;
  96040. _this._caps.instancedArrays = false;
  96041. BABYLON.Tools.Log("Babylon.js null engine (v" + BABYLON.Engine.Version + ") launched");
  96042. // Wrappers
  96043. if (typeof URL === "undefined") {
  96044. URL = {
  96045. createObjectURL: function () { },
  96046. revokeObjectURL: function () { }
  96047. };
  96048. }
  96049. if (typeof Blob === "undefined") {
  96050. Blob = function () { };
  96051. }
  96052. return _this;
  96053. }
  96054. NullEngine.prototype.isDeterministicLockStep = function () {
  96055. return this._options.deterministicLockstep;
  96056. };
  96057. NullEngine.prototype.getLockstepMaxSteps = function () {
  96058. return this._options.lockstepMaxSteps;
  96059. };
  96060. NullEngine.prototype.getHardwareScalingLevel = function () {
  96061. return 1.0;
  96062. };
  96063. NullEngine.prototype.createVertexBuffer = function (vertices) {
  96064. return {
  96065. capacity: 0,
  96066. references: 1,
  96067. is32Bits: false
  96068. };
  96069. };
  96070. NullEngine.prototype.createIndexBuffer = function (indices) {
  96071. return {
  96072. capacity: 0,
  96073. references: 1,
  96074. is32Bits: false
  96075. };
  96076. };
  96077. NullEngine.prototype.clear = function (color, backBuffer, depth, stencil) {
  96078. if (stencil === void 0) { stencil = false; }
  96079. };
  96080. NullEngine.prototype.getRenderWidth = function (useScreen) {
  96081. if (useScreen === void 0) { useScreen = false; }
  96082. if (!useScreen && this._currentRenderTarget) {
  96083. return this._currentRenderTarget.width;
  96084. }
  96085. return this._options.renderWidth;
  96086. };
  96087. NullEngine.prototype.getRenderHeight = function (useScreen) {
  96088. if (useScreen === void 0) { useScreen = false; }
  96089. if (!useScreen && this._currentRenderTarget) {
  96090. return this._currentRenderTarget.height;
  96091. }
  96092. return this._options.renderHeight;
  96093. };
  96094. NullEngine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  96095. this._cachedViewport = viewport;
  96096. };
  96097. NullEngine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context) {
  96098. return {
  96099. transformFeedback: null,
  96100. __SPECTOR_rebuildProgram: null
  96101. };
  96102. };
  96103. NullEngine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  96104. return [];
  96105. };
  96106. NullEngine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  96107. return [];
  96108. };
  96109. NullEngine.prototype.bindSamplers = function (effect) {
  96110. this._currentEffect = null;
  96111. };
  96112. NullEngine.prototype.enableEffect = function (effect) {
  96113. this._currentEffect = effect;
  96114. if (effect.onBind) {
  96115. effect.onBind(effect);
  96116. }
  96117. effect.onBindObservable.notifyObservers(effect);
  96118. };
  96119. NullEngine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  96120. if (zOffset === void 0) { zOffset = 0; }
  96121. if (reverseSide === void 0) { reverseSide = false; }
  96122. };
  96123. NullEngine.prototype.setIntArray = function (uniform, array) {
  96124. };
  96125. NullEngine.prototype.setIntArray2 = function (uniform, array) {
  96126. };
  96127. NullEngine.prototype.setIntArray3 = function (uniform, array) {
  96128. };
  96129. NullEngine.prototype.setIntArray4 = function (uniform, array) {
  96130. };
  96131. NullEngine.prototype.setFloatArray = function (uniform, array) {
  96132. };
  96133. NullEngine.prototype.setFloatArray2 = function (uniform, array) {
  96134. };
  96135. NullEngine.prototype.setFloatArray3 = function (uniform, array) {
  96136. };
  96137. NullEngine.prototype.setFloatArray4 = function (uniform, array) {
  96138. };
  96139. NullEngine.prototype.setArray = function (uniform, array) {
  96140. };
  96141. NullEngine.prototype.setArray2 = function (uniform, array) {
  96142. };
  96143. NullEngine.prototype.setArray3 = function (uniform, array) {
  96144. };
  96145. NullEngine.prototype.setArray4 = function (uniform, array) {
  96146. };
  96147. NullEngine.prototype.setMatrices = function (uniform, matrices) {
  96148. };
  96149. NullEngine.prototype.setMatrix = function (uniform, matrix) {
  96150. };
  96151. NullEngine.prototype.setMatrix3x3 = function (uniform, matrix) {
  96152. };
  96153. NullEngine.prototype.setMatrix2x2 = function (uniform, matrix) {
  96154. };
  96155. NullEngine.prototype.setFloat = function (uniform, value) {
  96156. };
  96157. NullEngine.prototype.setFloat2 = function (uniform, x, y) {
  96158. };
  96159. NullEngine.prototype.setFloat3 = function (uniform, x, y, z) {
  96160. };
  96161. NullEngine.prototype.setBool = function (uniform, bool) {
  96162. };
  96163. NullEngine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  96164. };
  96165. NullEngine.prototype.setColor3 = function (uniform, color3) {
  96166. };
  96167. NullEngine.prototype.setColor4 = function (uniform, color3, alpha) {
  96168. };
  96169. NullEngine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  96170. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  96171. if (this._alphaMode === mode) {
  96172. return;
  96173. }
  96174. this._alphaState.alphaBlend = (mode !== BABYLON.Engine.ALPHA_DISABLE);
  96175. if (!noDepthWriteChange) {
  96176. this.setDepthWrite(mode === BABYLON.Engine.ALPHA_DISABLE);
  96177. }
  96178. this._alphaMode = mode;
  96179. };
  96180. NullEngine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  96181. };
  96182. NullEngine.prototype.wipeCaches = function (bruteForce) {
  96183. if (this.preventCacheWipeBetweenFrames) {
  96184. return;
  96185. }
  96186. this.resetTextureCache();
  96187. this._currentEffect = null;
  96188. if (bruteForce) {
  96189. this._currentProgram = null;
  96190. this._stencilState.reset();
  96191. this._depthCullingState.reset();
  96192. this._alphaState.reset();
  96193. }
  96194. this._cachedVertexBuffers = null;
  96195. this._cachedIndexBuffer = null;
  96196. this._cachedEffectForVertexBuffers = null;
  96197. };
  96198. NullEngine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  96199. };
  96200. NullEngine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  96201. };
  96202. NullEngine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  96203. };
  96204. NullEngine.prototype._createTexture = function () {
  96205. return {};
  96206. };
  96207. NullEngine.prototype._releaseTexture = function (texture) {
  96208. };
  96209. NullEngine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallBack, format) {
  96210. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  96211. if (onLoad === void 0) { onLoad = null; }
  96212. if (onError === void 0) { onError = null; }
  96213. if (buffer === void 0) { buffer = null; }
  96214. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  96215. var url = String(urlArg);
  96216. texture.url = url;
  96217. texture.generateMipMaps = !noMipmap;
  96218. texture.samplingMode = samplingMode;
  96219. texture.invertY = invertY;
  96220. texture.baseWidth = this._options.textureSize;
  96221. texture.baseHeight = this._options.textureSize;
  96222. texture.width = this._options.textureSize;
  96223. texture.height = this._options.textureSize;
  96224. if (format) {
  96225. texture.format = format;
  96226. }
  96227. texture.isReady = true;
  96228. if (onLoad) {
  96229. onLoad();
  96230. }
  96231. this._internalTexturesCache.push(texture);
  96232. return texture;
  96233. };
  96234. NullEngine.prototype.createRenderTargetTexture = function (size, options) {
  96235. var fullOptions = new BABYLON.RenderTargetCreationOptions();
  96236. if (options !== undefined && typeof options === "object") {
  96237. fullOptions.generateMipMaps = options.generateMipMaps;
  96238. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  96239. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  96240. fullOptions.type = options.type === undefined ? BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  96241. fullOptions.samplingMode = options.samplingMode === undefined ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : options.samplingMode;
  96242. }
  96243. else {
  96244. fullOptions.generateMipMaps = options;
  96245. fullOptions.generateDepthBuffer = true;
  96246. fullOptions.generateStencilBuffer = false;
  96247. fullOptions.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  96248. fullOptions.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  96249. }
  96250. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  96251. var width = size.width || size;
  96252. var height = size.height || size;
  96253. texture._depthStencilBuffer = {};
  96254. texture._framebuffer = {};
  96255. texture.baseWidth = width;
  96256. texture.baseHeight = height;
  96257. texture.width = width;
  96258. texture.height = height;
  96259. texture.isReady = true;
  96260. texture.samples = 1;
  96261. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  96262. texture.samplingMode = fullOptions.samplingMode;
  96263. texture.type = fullOptions.type;
  96264. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  96265. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  96266. this._internalTexturesCache.push(texture);
  96267. return texture;
  96268. };
  96269. NullEngine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  96270. texture.samplingMode = samplingMode;
  96271. };
  96272. NullEngine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport) {
  96273. if (this._currentRenderTarget) {
  96274. this.unBindFramebuffer(this._currentRenderTarget);
  96275. }
  96276. this._currentRenderTarget = texture;
  96277. this._currentFramebuffer = texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer;
  96278. if (this._cachedViewport && !forceFullscreenViewport) {
  96279. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  96280. }
  96281. };
  96282. NullEngine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  96283. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  96284. this._currentRenderTarget = null;
  96285. if (onBeforeUnbind) {
  96286. if (texture._MSAAFramebuffer) {
  96287. this._currentFramebuffer = texture._framebuffer;
  96288. }
  96289. onBeforeUnbind();
  96290. }
  96291. this._currentFramebuffer = null;
  96292. };
  96293. NullEngine.prototype.createDynamicVertexBuffer = function (vertices) {
  96294. var vbo = {
  96295. capacity: 1,
  96296. references: 1,
  96297. is32Bits: false
  96298. };
  96299. return vbo;
  96300. };
  96301. NullEngine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  96302. if (offset === void 0) { offset = 0; }
  96303. };
  96304. /**
  96305. * Updates a dynamic vertex buffer.
  96306. * @param vertexBuffer the vertex buffer to update
  96307. * @param data the data used to update the vertex buffer
  96308. * @param byteOffset the byte offset of the data (optional)
  96309. * @param byteLength the byte length of the data (optional)
  96310. */
  96311. NullEngine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, byteOffset, byteLength) {
  96312. };
  96313. NullEngine.prototype._bindTextureDirectly = function (target, texture) {
  96314. if (this._boundTexturesCache[this._activeChannel] !== texture) {
  96315. this._boundTexturesCache[this._activeChannel] = texture;
  96316. }
  96317. };
  96318. NullEngine.prototype._bindTexture = function (channel, texture) {
  96319. if (channel < 0) {
  96320. return;
  96321. }
  96322. this._bindTextureDirectly(0, texture);
  96323. };
  96324. NullEngine.prototype._releaseBuffer = function (buffer) {
  96325. buffer.references--;
  96326. if (buffer.references === 0) {
  96327. return true;
  96328. }
  96329. return false;
  96330. };
  96331. NullEngine.prototype.releaseEffects = function () {
  96332. };
  96333. return NullEngine;
  96334. }(BABYLON.Engine));
  96335. BABYLON.NullEngine = NullEngine;
  96336. })(BABYLON || (BABYLON = {}));
  96337. //# sourceMappingURL=babylon.nullEngine.js.map
  96338. var BABYLON;
  96339. (function (BABYLON) {
  96340. /**
  96341. * This class can be used to get instrumentation data from a Babylon engine
  96342. */
  96343. var EngineInstrumentation = /** @class */ (function () {
  96344. function EngineInstrumentation(engine) {
  96345. this.engine = engine;
  96346. this._captureGPUFrameTime = false;
  96347. this._gpuFrameTime = new BABYLON.PerfCounter();
  96348. this._captureShaderCompilationTime = false;
  96349. this._shaderCompilationTime = new BABYLON.PerfCounter();
  96350. // Observers
  96351. this._onBeginFrameObserver = null;
  96352. this._onEndFrameObserver = null;
  96353. this._onBeforeShaderCompilationObserver = null;
  96354. this._onAfterShaderCompilationObserver = null;
  96355. }
  96356. Object.defineProperty(EngineInstrumentation.prototype, "gpuFrameTimeCounter", {
  96357. // Properties
  96358. /**
  96359. * Gets the perf counter used for GPU frame time
  96360. */
  96361. get: function () {
  96362. return this._gpuFrameTime;
  96363. },
  96364. enumerable: true,
  96365. configurable: true
  96366. });
  96367. Object.defineProperty(EngineInstrumentation.prototype, "captureGPUFrameTime", {
  96368. /**
  96369. * Gets the GPU frame time capture status
  96370. */
  96371. get: function () {
  96372. return this._captureGPUFrameTime;
  96373. },
  96374. /**
  96375. * Enable or disable the GPU frame time capture
  96376. */
  96377. set: function (value) {
  96378. var _this = this;
  96379. if (value === this._captureGPUFrameTime) {
  96380. return;
  96381. }
  96382. this._captureGPUFrameTime = value;
  96383. if (value) {
  96384. this._onBeginFrameObserver = this.engine.onBeginFrameObservable.add(function () {
  96385. if (!_this._gpuFrameTimeToken) {
  96386. _this._gpuFrameTimeToken = _this.engine.startTimeQuery();
  96387. }
  96388. });
  96389. this._onEndFrameObserver = this.engine.onEndFrameObservable.add(function () {
  96390. if (!_this._gpuFrameTimeToken) {
  96391. return;
  96392. }
  96393. var time = _this.engine.endTimeQuery(_this._gpuFrameTimeToken);
  96394. if (time > -1) {
  96395. _this._gpuFrameTimeToken = null;
  96396. _this._gpuFrameTime.fetchNewFrame();
  96397. _this._gpuFrameTime.addCount(time, true);
  96398. }
  96399. });
  96400. }
  96401. else {
  96402. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  96403. this._onBeginFrameObserver = null;
  96404. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  96405. this._onEndFrameObserver = null;
  96406. }
  96407. },
  96408. enumerable: true,
  96409. configurable: true
  96410. });
  96411. Object.defineProperty(EngineInstrumentation.prototype, "shaderCompilationTimeCounter", {
  96412. /**
  96413. * Gets the perf counter used for shader compilation time
  96414. */
  96415. get: function () {
  96416. return this._shaderCompilationTime;
  96417. },
  96418. enumerable: true,
  96419. configurable: true
  96420. });
  96421. Object.defineProperty(EngineInstrumentation.prototype, "captureShaderCompilationTime", {
  96422. /**
  96423. * Gets the shader compilation time capture status
  96424. */
  96425. get: function () {
  96426. return this._captureShaderCompilationTime;
  96427. },
  96428. /**
  96429. * Enable or disable the shader compilation time capture
  96430. */
  96431. set: function (value) {
  96432. var _this = this;
  96433. if (value === this._captureShaderCompilationTime) {
  96434. return;
  96435. }
  96436. this._captureShaderCompilationTime = value;
  96437. if (value) {
  96438. this._onBeforeShaderCompilationObserver = this.engine.onBeforeShaderCompilationObservable.add(function () {
  96439. _this._shaderCompilationTime.fetchNewFrame();
  96440. _this._shaderCompilationTime.beginMonitoring();
  96441. });
  96442. this._onAfterShaderCompilationObserver = this.engine.onAfterShaderCompilationObservable.add(function () {
  96443. _this._shaderCompilationTime.endMonitoring();
  96444. });
  96445. }
  96446. else {
  96447. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  96448. this._onBeforeShaderCompilationObserver = null;
  96449. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  96450. this._onAfterShaderCompilationObserver = null;
  96451. }
  96452. },
  96453. enumerable: true,
  96454. configurable: true
  96455. });
  96456. EngineInstrumentation.prototype.dispose = function () {
  96457. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  96458. this._onBeginFrameObserver = null;
  96459. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  96460. this._onEndFrameObserver = null;
  96461. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  96462. this._onBeforeShaderCompilationObserver = null;
  96463. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  96464. this._onAfterShaderCompilationObserver = null;
  96465. this.engine = null;
  96466. };
  96467. return EngineInstrumentation;
  96468. }());
  96469. BABYLON.EngineInstrumentation = EngineInstrumentation;
  96470. })(BABYLON || (BABYLON = {}));
  96471. //# sourceMappingURL=babylon.engineInstrumentation.js.map
  96472. var BABYLON;
  96473. (function (BABYLON) {
  96474. /**
  96475. * This class can be used to get instrumentation data from a Babylon engine
  96476. */
  96477. var SceneInstrumentation = /** @class */ (function () {
  96478. function SceneInstrumentation(scene) {
  96479. var _this = this;
  96480. this.scene = scene;
  96481. this._captureActiveMeshesEvaluationTime = false;
  96482. this._activeMeshesEvaluationTime = new BABYLON.PerfCounter();
  96483. this._captureRenderTargetsRenderTime = false;
  96484. this._renderTargetsRenderTime = new BABYLON.PerfCounter();
  96485. this._captureFrameTime = false;
  96486. this._frameTime = new BABYLON.PerfCounter();
  96487. this._captureRenderTime = false;
  96488. this._renderTime = new BABYLON.PerfCounter();
  96489. this._captureInterFrameTime = false;
  96490. this._interFrameTime = new BABYLON.PerfCounter();
  96491. this._captureParticlesRenderTime = false;
  96492. this._particlesRenderTime = new BABYLON.PerfCounter();
  96493. this._captureSpritesRenderTime = false;
  96494. this._spritesRenderTime = new BABYLON.PerfCounter();
  96495. this._capturePhysicsTime = false;
  96496. this._physicsTime = new BABYLON.PerfCounter();
  96497. this._captureAnimationsTime = false;
  96498. this._animationsTime = new BABYLON.PerfCounter();
  96499. // Observers
  96500. this._onBeforeActiveMeshesEvaluationObserver = null;
  96501. this._onAfterActiveMeshesEvaluationObserver = null;
  96502. this._onBeforeRenderTargetsRenderObserver = null;
  96503. this._onAfterRenderTargetsRenderObserver = null;
  96504. this._onAfterRenderObserver = null;
  96505. this._onBeforeDrawPhaseObserver = null;
  96506. this._onAfterDrawPhaseObserver = null;
  96507. this._onBeforeAnimationsObserver = null;
  96508. this._onBeforeParticlesRenderingObserver = null;
  96509. this._onAfterParticlesRenderingObserver = null;
  96510. this._onBeforeSpritesRenderingObserver = null;
  96511. this._onAfterSpritesRenderingObserver = null;
  96512. this._onBeforePhysicsObserver = null;
  96513. this._onAfterPhysicsObserver = null;
  96514. this._onAfterAnimationsObserver = null;
  96515. // Before render
  96516. this._onBeforeAnimationsObserver = scene.onBeforeAnimationsObservable.add(function () {
  96517. if (_this._captureActiveMeshesEvaluationTime) {
  96518. _this._activeMeshesEvaluationTime.fetchNewFrame();
  96519. }
  96520. if (_this._captureRenderTargetsRenderTime) {
  96521. _this._renderTargetsRenderTime.fetchNewFrame();
  96522. }
  96523. if (_this._captureFrameTime) {
  96524. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  96525. _this._frameTime.beginMonitoring();
  96526. }
  96527. if (_this._captureInterFrameTime) {
  96528. _this._interFrameTime.endMonitoring();
  96529. }
  96530. if (_this._captureParticlesRenderTime) {
  96531. _this._particlesRenderTime.fetchNewFrame();
  96532. }
  96533. if (_this._captureSpritesRenderTime) {
  96534. _this._spritesRenderTime.fetchNewFrame();
  96535. }
  96536. if (_this._captureAnimationsTime) {
  96537. _this._animationsTime.beginMonitoring();
  96538. }
  96539. _this.scene.getEngine()._drawCalls.fetchNewFrame();
  96540. _this.scene.getEngine()._textureCollisions.fetchNewFrame();
  96541. });
  96542. // After render
  96543. this._onAfterRenderObserver = scene.onAfterRenderObservable.add(function () {
  96544. if (_this._captureFrameTime) {
  96545. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  96546. _this._frameTime.endMonitoring();
  96547. }
  96548. if (_this._captureRenderTime) {
  96549. _this._renderTime.endMonitoring(false);
  96550. }
  96551. if (_this._captureInterFrameTime) {
  96552. _this._interFrameTime.beginMonitoring();
  96553. }
  96554. });
  96555. }
  96556. Object.defineProperty(SceneInstrumentation.prototype, "activeMeshesEvaluationTimeCounter", {
  96557. // Properties
  96558. /**
  96559. * Gets the perf counter used for active meshes evaluation time
  96560. */
  96561. get: function () {
  96562. return this._activeMeshesEvaluationTime;
  96563. },
  96564. enumerable: true,
  96565. configurable: true
  96566. });
  96567. Object.defineProperty(SceneInstrumentation.prototype, "captureActiveMeshesEvaluationTime", {
  96568. /**
  96569. * Gets the active meshes evaluation time capture status
  96570. */
  96571. get: function () {
  96572. return this._captureActiveMeshesEvaluationTime;
  96573. },
  96574. /**
  96575. * Enable or disable the active meshes evaluation time capture
  96576. */
  96577. set: function (value) {
  96578. var _this = this;
  96579. if (value === this._captureActiveMeshesEvaluationTime) {
  96580. return;
  96581. }
  96582. this._captureActiveMeshesEvaluationTime = value;
  96583. if (value) {
  96584. this._onBeforeActiveMeshesEvaluationObserver = this.scene.onBeforeActiveMeshesEvaluationObservable.add(function () {
  96585. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  96586. _this._activeMeshesEvaluationTime.beginMonitoring();
  96587. });
  96588. this._onAfterActiveMeshesEvaluationObserver = this.scene.onAfterActiveMeshesEvaluationObservable.add(function () {
  96589. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  96590. _this._activeMeshesEvaluationTime.endMonitoring();
  96591. });
  96592. }
  96593. else {
  96594. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  96595. this._onBeforeActiveMeshesEvaluationObserver = null;
  96596. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  96597. this._onAfterActiveMeshesEvaluationObserver = null;
  96598. }
  96599. },
  96600. enumerable: true,
  96601. configurable: true
  96602. });
  96603. Object.defineProperty(SceneInstrumentation.prototype, "renderTargetsRenderTimeCounter", {
  96604. /**
  96605. * Gets the perf counter used for render targets render time
  96606. */
  96607. get: function () {
  96608. return this._renderTargetsRenderTime;
  96609. },
  96610. enumerable: true,
  96611. configurable: true
  96612. });
  96613. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTargetsRenderTime", {
  96614. /**
  96615. * Gets the render targets render time capture status
  96616. */
  96617. get: function () {
  96618. return this._captureRenderTargetsRenderTime;
  96619. },
  96620. /**
  96621. * Enable or disable the render targets render time capture
  96622. */
  96623. set: function (value) {
  96624. var _this = this;
  96625. if (value === this._captureRenderTargetsRenderTime) {
  96626. return;
  96627. }
  96628. this._captureRenderTargetsRenderTime = value;
  96629. if (value) {
  96630. this._onBeforeRenderTargetsRenderObserver = this.scene.onBeforeRenderTargetsRenderObservable.add(function () {
  96631. BABYLON.Tools.StartPerformanceCounter("Render targets rendering");
  96632. _this._renderTargetsRenderTime.beginMonitoring();
  96633. });
  96634. this._onAfterRenderTargetsRenderObserver = this.scene.onAfterRenderTargetsRenderObservable.add(function () {
  96635. BABYLON.Tools.EndPerformanceCounter("Render targets rendering");
  96636. _this._renderTargetsRenderTime.endMonitoring(false);
  96637. });
  96638. }
  96639. else {
  96640. this.scene.onBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  96641. this._onBeforeRenderTargetsRenderObserver = null;
  96642. this.scene.onAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  96643. this._onAfterRenderTargetsRenderObserver = null;
  96644. }
  96645. },
  96646. enumerable: true,
  96647. configurable: true
  96648. });
  96649. Object.defineProperty(SceneInstrumentation.prototype, "particlesRenderTimeCounter", {
  96650. /**
  96651. * Gets the perf counter used for particles render time
  96652. */
  96653. get: function () {
  96654. return this._particlesRenderTime;
  96655. },
  96656. enumerable: true,
  96657. configurable: true
  96658. });
  96659. Object.defineProperty(SceneInstrumentation.prototype, "captureParticlesRenderTime", {
  96660. /**
  96661. * Gets the particles render time capture status
  96662. */
  96663. get: function () {
  96664. return this._captureParticlesRenderTime;
  96665. },
  96666. /**
  96667. * Enable or disable the particles render time capture
  96668. */
  96669. set: function (value) {
  96670. var _this = this;
  96671. if (value === this._captureParticlesRenderTime) {
  96672. return;
  96673. }
  96674. this._captureParticlesRenderTime = value;
  96675. if (value) {
  96676. this._onBeforeParticlesRenderingObserver = this.scene.onBeforeParticlesRenderingObservable.add(function () {
  96677. BABYLON.Tools.StartPerformanceCounter("Particles");
  96678. _this._particlesRenderTime.beginMonitoring();
  96679. });
  96680. this._onAfterParticlesRenderingObserver = this.scene.onAfterParticlesRenderingObservable.add(function () {
  96681. BABYLON.Tools.EndPerformanceCounter("Particles");
  96682. _this._particlesRenderTime.endMonitoring(false);
  96683. });
  96684. }
  96685. else {
  96686. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  96687. this._onBeforeParticlesRenderingObserver = null;
  96688. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  96689. this._onAfterParticlesRenderingObserver = null;
  96690. }
  96691. },
  96692. enumerable: true,
  96693. configurable: true
  96694. });
  96695. Object.defineProperty(SceneInstrumentation.prototype, "spritesRenderTimeCounter", {
  96696. /**
  96697. * Gets the perf counter used for sprites render time
  96698. */
  96699. get: function () {
  96700. return this._spritesRenderTime;
  96701. },
  96702. enumerable: true,
  96703. configurable: true
  96704. });
  96705. Object.defineProperty(SceneInstrumentation.prototype, "captureSpritesRenderTime", {
  96706. /**
  96707. * Gets the sprites render time capture status
  96708. */
  96709. get: function () {
  96710. return this._captureSpritesRenderTime;
  96711. },
  96712. /**
  96713. * Enable or disable the sprites render time capture
  96714. */
  96715. set: function (value) {
  96716. var _this = this;
  96717. if (value === this._captureSpritesRenderTime) {
  96718. return;
  96719. }
  96720. this._captureSpritesRenderTime = value;
  96721. if (value) {
  96722. this._onBeforeSpritesRenderingObserver = this.scene.onBeforeSpritesRenderingObservable.add(function () {
  96723. BABYLON.Tools.StartPerformanceCounter("Sprites");
  96724. _this._spritesRenderTime.beginMonitoring();
  96725. });
  96726. this._onAfterSpritesRenderingObserver = this.scene.onAfterSpritesRenderingObservable.add(function () {
  96727. BABYLON.Tools.EndPerformanceCounter("Sprites");
  96728. _this._spritesRenderTime.endMonitoring(false);
  96729. });
  96730. }
  96731. else {
  96732. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  96733. this._onBeforeSpritesRenderingObserver = null;
  96734. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  96735. this._onAfterSpritesRenderingObserver = null;
  96736. }
  96737. },
  96738. enumerable: true,
  96739. configurable: true
  96740. });
  96741. Object.defineProperty(SceneInstrumentation.prototype, "physicsTimeCounter", {
  96742. /**
  96743. * Gets the perf counter used for physics time
  96744. */
  96745. get: function () {
  96746. return this._physicsTime;
  96747. },
  96748. enumerable: true,
  96749. configurable: true
  96750. });
  96751. Object.defineProperty(SceneInstrumentation.prototype, "capturePhysicsTime", {
  96752. /**
  96753. * Gets the physics time capture status
  96754. */
  96755. get: function () {
  96756. return this._capturePhysicsTime;
  96757. },
  96758. /**
  96759. * Enable or disable the physics time capture
  96760. */
  96761. set: function (value) {
  96762. var _this = this;
  96763. if (value === this._capturePhysicsTime) {
  96764. return;
  96765. }
  96766. this._capturePhysicsTime = value;
  96767. if (value) {
  96768. this._onBeforePhysicsObserver = this.scene.onBeforePhysicsObservable.add(function () {
  96769. BABYLON.Tools.StartPerformanceCounter("Physics");
  96770. _this._physicsTime.beginMonitoring();
  96771. });
  96772. this._onAfterPhysicsObserver = this.scene.onAfterPhysicsObservable.add(function () {
  96773. BABYLON.Tools.EndPerformanceCounter("Physics");
  96774. _this._physicsTime.endMonitoring();
  96775. });
  96776. }
  96777. else {
  96778. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  96779. this._onBeforePhysicsObserver = null;
  96780. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  96781. this._onAfterPhysicsObserver = null;
  96782. }
  96783. },
  96784. enumerable: true,
  96785. configurable: true
  96786. });
  96787. Object.defineProperty(SceneInstrumentation.prototype, "animationsTimeCounter", {
  96788. /**
  96789. * Gets the perf counter used for animations time
  96790. */
  96791. get: function () {
  96792. return this._animationsTime;
  96793. },
  96794. enumerable: true,
  96795. configurable: true
  96796. });
  96797. Object.defineProperty(SceneInstrumentation.prototype, "captureAnimationsTime", {
  96798. /**
  96799. * Gets the animations time capture status
  96800. */
  96801. get: function () {
  96802. return this._captureAnimationsTime;
  96803. },
  96804. /**
  96805. * Enable or disable the animations time capture
  96806. */
  96807. set: function (value) {
  96808. var _this = this;
  96809. if (value === this._captureAnimationsTime) {
  96810. return;
  96811. }
  96812. this._captureAnimationsTime = value;
  96813. if (value) {
  96814. this._onAfterAnimationsObserver = this.scene.onAfterAnimationsObservable.add(function () {
  96815. _this._animationsTime.endMonitoring();
  96816. });
  96817. }
  96818. else {
  96819. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  96820. this._onAfterAnimationsObserver = null;
  96821. }
  96822. },
  96823. enumerable: true,
  96824. configurable: true
  96825. });
  96826. Object.defineProperty(SceneInstrumentation.prototype, "frameTimeCounter", {
  96827. /**
  96828. * Gets the perf counter used for frame time capture
  96829. */
  96830. get: function () {
  96831. return this._frameTime;
  96832. },
  96833. enumerable: true,
  96834. configurable: true
  96835. });
  96836. Object.defineProperty(SceneInstrumentation.prototype, "captureFrameTime", {
  96837. /**
  96838. * Gets the frame time capture status
  96839. */
  96840. get: function () {
  96841. return this._captureFrameTime;
  96842. },
  96843. /**
  96844. * Enable or disable the frame time capture
  96845. */
  96846. set: function (value) {
  96847. this._captureFrameTime = value;
  96848. },
  96849. enumerable: true,
  96850. configurable: true
  96851. });
  96852. Object.defineProperty(SceneInstrumentation.prototype, "interFrameTimeCounter", {
  96853. /**
  96854. * Gets the perf counter used for inter-frames time capture
  96855. */
  96856. get: function () {
  96857. return this._interFrameTime;
  96858. },
  96859. enumerable: true,
  96860. configurable: true
  96861. });
  96862. Object.defineProperty(SceneInstrumentation.prototype, "captureInterFrameTime", {
  96863. /**
  96864. * Gets the inter-frames time capture status
  96865. */
  96866. get: function () {
  96867. return this._captureInterFrameTime;
  96868. },
  96869. /**
  96870. * Enable or disable the inter-frames time capture
  96871. */
  96872. set: function (value) {
  96873. this._captureInterFrameTime = value;
  96874. },
  96875. enumerable: true,
  96876. configurable: true
  96877. });
  96878. Object.defineProperty(SceneInstrumentation.prototype, "renderTimeCounter", {
  96879. /**
  96880. * Gets the perf counter used for render time capture
  96881. */
  96882. get: function () {
  96883. return this._renderTime;
  96884. },
  96885. enumerable: true,
  96886. configurable: true
  96887. });
  96888. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTime", {
  96889. /**
  96890. * Gets the render time capture status
  96891. */
  96892. get: function () {
  96893. return this._captureRenderTime;
  96894. },
  96895. /**
  96896. * Enable or disable the render time capture
  96897. */
  96898. set: function (value) {
  96899. var _this = this;
  96900. if (value === this._captureRenderTime) {
  96901. return;
  96902. }
  96903. this._captureRenderTime = value;
  96904. if (value) {
  96905. this._onBeforeDrawPhaseObserver = this.scene.onBeforeDrawPhaseObservable.add(function () {
  96906. _this._renderTime.beginMonitoring();
  96907. BABYLON.Tools.StartPerformanceCounter("Main render");
  96908. });
  96909. this._onAfterDrawPhaseObserver = this.scene.onAfterDrawPhaseObservable.add(function () {
  96910. _this._renderTime.endMonitoring(false);
  96911. BABYLON.Tools.EndPerformanceCounter("Main render");
  96912. });
  96913. }
  96914. else {
  96915. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  96916. this._onBeforeDrawPhaseObserver = null;
  96917. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  96918. this._onAfterDrawPhaseObserver = null;
  96919. }
  96920. },
  96921. enumerable: true,
  96922. configurable: true
  96923. });
  96924. Object.defineProperty(SceneInstrumentation.prototype, "drawCallsCounter", {
  96925. /**
  96926. * Gets the perf counter used for draw calls
  96927. */
  96928. get: function () {
  96929. return this.scene.getEngine()._drawCalls;
  96930. },
  96931. enumerable: true,
  96932. configurable: true
  96933. });
  96934. Object.defineProperty(SceneInstrumentation.prototype, "textureCollisionsCounter", {
  96935. /**
  96936. * Gets the perf counter used for texture collisions
  96937. */
  96938. get: function () {
  96939. return this.scene.getEngine()._textureCollisions;
  96940. },
  96941. enumerable: true,
  96942. configurable: true
  96943. });
  96944. SceneInstrumentation.prototype.dispose = function () {
  96945. this.scene.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  96946. this._onAfterRenderObserver = null;
  96947. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  96948. this._onBeforeActiveMeshesEvaluationObserver = null;
  96949. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  96950. this._onAfterActiveMeshesEvaluationObserver = null;
  96951. this.scene.onBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  96952. this._onBeforeRenderTargetsRenderObserver = null;
  96953. this.scene.onAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  96954. this._onAfterRenderTargetsRenderObserver = null;
  96955. this.scene.onBeforeAnimationsObservable.remove(this._onBeforeAnimationsObserver);
  96956. this._onBeforeAnimationsObserver = null;
  96957. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  96958. this._onBeforeParticlesRenderingObserver = null;
  96959. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  96960. this._onAfterParticlesRenderingObserver = null;
  96961. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  96962. this._onBeforeSpritesRenderingObserver = null;
  96963. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  96964. this._onAfterSpritesRenderingObserver = null;
  96965. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  96966. this._onBeforeDrawPhaseObserver = null;
  96967. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  96968. this._onAfterDrawPhaseObserver = null;
  96969. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  96970. this._onBeforePhysicsObserver = null;
  96971. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  96972. this._onAfterPhysicsObserver = null;
  96973. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  96974. this._onAfterAnimationsObserver = null;
  96975. this.scene = null;
  96976. };
  96977. return SceneInstrumentation;
  96978. }());
  96979. BABYLON.SceneInstrumentation = SceneInstrumentation;
  96980. })(BABYLON || (BABYLON = {}));
  96981. //# sourceMappingURL=babylon.sceneInstrumentation.js.map
  96982. var BABYLON;
  96983. (function (BABYLON) {
  96984. /**
  96985. * @hidden
  96986. **/
  96987. var _TimeToken = /** @class */ (function () {
  96988. function _TimeToken() {
  96989. this._timeElapsedQueryEnded = false;
  96990. }
  96991. return _TimeToken;
  96992. }());
  96993. BABYLON._TimeToken = _TimeToken;
  96994. })(BABYLON || (BABYLON = {}));
  96995. //# sourceMappingURL=babylon.timeToken.js.map
  96996. var BABYLON;
  96997. (function (BABYLON) {
  96998. /**
  96999. * Background material defines definition.
  97000. * @hidden Mainly internal Use
  97001. */
  97002. var BackgroundMaterialDefines = /** @class */ (function (_super) {
  97003. __extends(BackgroundMaterialDefines, _super);
  97004. /**
  97005. * Constructor of the defines.
  97006. */
  97007. function BackgroundMaterialDefines() {
  97008. var _this = _super.call(this) || this;
  97009. /**
  97010. * True if the diffuse texture is in use.
  97011. */
  97012. _this.DIFFUSE = false;
  97013. /**
  97014. * The direct UV channel to use.
  97015. */
  97016. _this.DIFFUSEDIRECTUV = 0;
  97017. /**
  97018. * True if the diffuse texture is in gamma space.
  97019. */
  97020. _this.GAMMADIFFUSE = false;
  97021. /**
  97022. * True if the diffuse texture has opacity in the alpha channel.
  97023. */
  97024. _this.DIFFUSEHASALPHA = false;
  97025. /**
  97026. * True if you want the material to fade to transparent at grazing angle.
  97027. */
  97028. _this.OPACITYFRESNEL = false;
  97029. /**
  97030. * True if an extra blur needs to be added in the reflection.
  97031. */
  97032. _this.REFLECTIONBLUR = false;
  97033. /**
  97034. * True if you want the material to fade to reflection at grazing angle.
  97035. */
  97036. _this.REFLECTIONFRESNEL = false;
  97037. /**
  97038. * True if you want the material to falloff as far as you move away from the scene center.
  97039. */
  97040. _this.REFLECTIONFALLOFF = false;
  97041. /**
  97042. * False if the current Webgl implementation does not support the texture lod extension.
  97043. */
  97044. _this.TEXTURELODSUPPORT = false;
  97045. /**
  97046. * True to ensure the data are premultiplied.
  97047. */
  97048. _this.PREMULTIPLYALPHA = false;
  97049. /**
  97050. * True if the texture contains cooked RGB values and not gray scaled multipliers.
  97051. */
  97052. _this.USERGBCOLOR = false;
  97053. /**
  97054. * True if highlight and shadow levels have been specified. It can help ensuring the main perceived color
  97055. * stays aligned with the desired configuration.
  97056. */
  97057. _this.USEHIGHLIGHTANDSHADOWCOLORS = false;
  97058. /**
  97059. * True to add noise in order to reduce the banding effect.
  97060. */
  97061. _this.NOISE = false;
  97062. /**
  97063. * is the reflection texture in BGR color scheme?
  97064. * Mainly used to solve a bug in ios10 video tag
  97065. */
  97066. _this.REFLECTIONBGR = false;
  97067. _this.IMAGEPROCESSING = false;
  97068. _this.VIGNETTE = false;
  97069. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  97070. _this.VIGNETTEBLENDMODEOPAQUE = false;
  97071. _this.TONEMAPPING = false;
  97072. _this.CONTRAST = false;
  97073. _this.COLORCURVES = false;
  97074. _this.COLORGRADING = false;
  97075. _this.COLORGRADING3D = false;
  97076. _this.SAMPLER3DGREENDEPTH = false;
  97077. _this.SAMPLER3DBGRMAP = false;
  97078. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  97079. _this.EXPOSURE = false;
  97080. // Reflection.
  97081. _this.REFLECTION = false;
  97082. _this.REFLECTIONMAP_3D = false;
  97083. _this.REFLECTIONMAP_SPHERICAL = false;
  97084. _this.REFLECTIONMAP_PLANAR = false;
  97085. _this.REFLECTIONMAP_CUBIC = false;
  97086. _this.REFLECTIONMAP_PROJECTION = false;
  97087. _this.REFLECTIONMAP_SKYBOX = false;
  97088. _this.REFLECTIONMAP_EXPLICIT = false;
  97089. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  97090. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  97091. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  97092. _this.INVERTCUBICMAP = false;
  97093. _this.REFLECTIONMAP_OPPOSITEZ = false;
  97094. _this.LODINREFLECTIONALPHA = false;
  97095. _this.GAMMAREFLECTION = false;
  97096. _this.EQUIRECTANGULAR_RELFECTION_FOV = false;
  97097. // Default BJS.
  97098. _this.MAINUV1 = false;
  97099. _this.MAINUV2 = false;
  97100. _this.UV1 = false;
  97101. _this.UV2 = false;
  97102. _this.CLIPPLANE = false;
  97103. _this.POINTSIZE = false;
  97104. _this.FOG = false;
  97105. _this.NORMAL = false;
  97106. _this.NUM_BONE_INFLUENCERS = 0;
  97107. _this.BonesPerMesh = 0;
  97108. _this.INSTANCES = false;
  97109. _this.SHADOWFLOAT = false;
  97110. _this.rebuild();
  97111. return _this;
  97112. }
  97113. return BackgroundMaterialDefines;
  97114. }(BABYLON.MaterialDefines));
  97115. /**
  97116. * Background material used to create an efficient environement around your scene.
  97117. */
  97118. var BackgroundMaterial = /** @class */ (function (_super) {
  97119. __extends(BackgroundMaterial, _super);
  97120. /**
  97121. * Instantiates a Background Material in the given scene
  97122. * @param name The friendly name of the material
  97123. * @param scene The scene to add the material to
  97124. */
  97125. function BackgroundMaterial(name, scene) {
  97126. var _this = _super.call(this, name, scene) || this;
  97127. /**
  97128. * Key light Color (multiply against the environement texture)
  97129. */
  97130. _this.primaryColor = BABYLON.Color3.White();
  97131. _this._primaryColorShadowLevel = 0;
  97132. _this._primaryColorHighlightLevel = 0;
  97133. /**
  97134. * Reflection Texture used in the material.
  97135. * Should be author in a specific way for the best result (refer to the documentation).
  97136. */
  97137. _this.reflectionTexture = null;
  97138. /**
  97139. * Reflection Texture level of blur.
  97140. *
  97141. * Can be use to reuse an existing HDR Texture and target a specific LOD to prevent authoring the
  97142. * texture twice.
  97143. */
  97144. _this.reflectionBlur = 0;
  97145. /**
  97146. * Diffuse Texture used in the material.
  97147. * Should be author in a specific way for the best result (refer to the documentation).
  97148. */
  97149. _this.diffuseTexture = null;
  97150. _this._shadowLights = null;
  97151. /**
  97152. * Specify the list of lights casting shadow on the material.
  97153. * All scene shadow lights will be included if null.
  97154. */
  97155. _this.shadowLights = null;
  97156. /**
  97157. * Helps adjusting the shadow to a softer level if required.
  97158. * 0 means black shadows and 1 means no shadows.
  97159. */
  97160. _this.shadowLevel = 0;
  97161. /**
  97162. * In case of opacity Fresnel or reflection falloff, this is use as a scene center.
  97163. * It is usually zero but might be interesting to modify according to your setup.
  97164. */
  97165. _this.sceneCenter = BABYLON.Vector3.Zero();
  97166. /**
  97167. * This helps specifying that the material is falling off to the sky box at grazing angle.
  97168. * This helps ensuring a nice transition when the camera goes under the ground.
  97169. */
  97170. _this.opacityFresnel = true;
  97171. /**
  97172. * This helps specifying that the material is falling off from diffuse to the reflection texture at grazing angle.
  97173. * This helps adding a mirror texture on the ground.
  97174. */
  97175. _this.reflectionFresnel = false;
  97176. /**
  97177. * This helps specifying the falloff radius off the reflection texture from the sceneCenter.
  97178. * This helps adding a nice falloff effect to the reflection if used as a mirror for instance.
  97179. */
  97180. _this.reflectionFalloffDistance = 0.0;
  97181. /**
  97182. * This specifies the weight of the reflection against the background in case of reflection Fresnel.
  97183. */
  97184. _this.reflectionAmount = 1.0;
  97185. /**
  97186. * This specifies the weight of the reflection at grazing angle.
  97187. */
  97188. _this.reflectionReflectance0 = 0.05;
  97189. /**
  97190. * This specifies the weight of the reflection at a perpendicular point of view.
  97191. */
  97192. _this.reflectionReflectance90 = 0.5;
  97193. /**
  97194. * Helps to directly use the maps channels instead of their level.
  97195. */
  97196. _this.useRGBColor = true;
  97197. /**
  97198. * This helps reducing the banding effect that could occur on the background.
  97199. */
  97200. _this.enableNoise = false;
  97201. _this._fovMultiplier = 1.0;
  97202. /**
  97203. * Enable the FOV adjustment feature controlled by fovMultiplier.
  97204. */
  97205. _this.useEquirectangularFOV = false;
  97206. _this._maxSimultaneousLights = 4;
  97207. /**
  97208. * Number of Simultaneous lights allowed on the material.
  97209. */
  97210. _this.maxSimultaneousLights = 4;
  97211. /**
  97212. * Keep track of the image processing observer to allow dispose and replace.
  97213. */
  97214. _this._imageProcessingObserver = null;
  97215. /**
  97216. * Due to a bug in iOS10, video tags (which are using the background material) are in BGR and not RGB.
  97217. * Setting this flag to true (not done automatically!) will convert it back to RGB.
  97218. */
  97219. _this.switchToBGR = false;
  97220. // Temp values kept as cache in the material.
  97221. _this._renderTargets = new BABYLON.SmartArray(16);
  97222. _this._reflectionControls = BABYLON.Vector4.Zero();
  97223. _this._white = BABYLON.Color3.White();
  97224. _this._primaryShadowColor = BABYLON.Color3.Black();
  97225. _this._primaryHighlightColor = BABYLON.Color3.Black();
  97226. // Setup the default processing configuration to the scene.
  97227. _this._attachImageProcessingConfiguration(null);
  97228. _this.getRenderTargetTextures = function () {
  97229. _this._renderTargets.reset();
  97230. if (_this._diffuseTexture && _this._diffuseTexture.isRenderTarget) {
  97231. _this._renderTargets.push(_this._diffuseTexture);
  97232. }
  97233. if (_this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  97234. _this._renderTargets.push(_this._reflectionTexture);
  97235. }
  97236. return _this._renderTargets;
  97237. };
  97238. return _this;
  97239. }
  97240. Object.defineProperty(BackgroundMaterial.prototype, "_perceptualColor", {
  97241. /**
  97242. * Experimental Internal Use Only.
  97243. *
  97244. * Key light Color in "perceptual value" meaning the color you would like to see on screen.
  97245. * This acts as a helper to set the primary color to a more "human friendly" value.
  97246. * Conversion to linear space as well as exposure and tone mapping correction will be applied to keep the
  97247. * output color as close as possible from the chosen value.
  97248. * (This does not account for contrast color grading and color curves as they are considered post effect and not directly
  97249. * part of lighting setup.)
  97250. */
  97251. get: function () {
  97252. return this.__perceptualColor;
  97253. },
  97254. set: function (value) {
  97255. this.__perceptualColor = value;
  97256. this._computePrimaryColorFromPerceptualColor();
  97257. this._markAllSubMeshesAsLightsDirty();
  97258. },
  97259. enumerable: true,
  97260. configurable: true
  97261. });
  97262. Object.defineProperty(BackgroundMaterial.prototype, "primaryColorShadowLevel", {
  97263. /**
  97264. * Defines the level of the shadows (dark area of the reflection map) in order to help scaling the colors.
  97265. * The color opposite to the primary color is used at the level chosen to define what the black area would look.
  97266. */
  97267. get: function () {
  97268. return this._primaryColorShadowLevel;
  97269. },
  97270. set: function (value) {
  97271. this._primaryColorShadowLevel = value;
  97272. this._computePrimaryColors();
  97273. this._markAllSubMeshesAsLightsDirty();
  97274. },
  97275. enumerable: true,
  97276. configurable: true
  97277. });
  97278. Object.defineProperty(BackgroundMaterial.prototype, "primaryColorHighlightLevel", {
  97279. /**
  97280. * Defines the level of the highliights (highlight area of the reflection map) in order to help scaling the colors.
  97281. * The primary color is used at the level chosen to define what the white area would look.
  97282. */
  97283. get: function () {
  97284. return this._primaryColorHighlightLevel;
  97285. },
  97286. set: function (value) {
  97287. this._primaryColorHighlightLevel = value;
  97288. this._computePrimaryColors();
  97289. this._markAllSubMeshesAsLightsDirty();
  97290. },
  97291. enumerable: true,
  97292. configurable: true
  97293. });
  97294. Object.defineProperty(BackgroundMaterial.prototype, "reflectionStandardFresnelWeight", {
  97295. /**
  97296. * Sets the reflection reflectance fresnel values according to the default standard
  97297. * empirically know to work well :-)
  97298. */
  97299. set: function (value) {
  97300. var reflectionWeight = value;
  97301. if (reflectionWeight < 0.5) {
  97302. reflectionWeight = reflectionWeight * 2.0;
  97303. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 * reflectionWeight;
  97304. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 * reflectionWeight;
  97305. }
  97306. else {
  97307. reflectionWeight = reflectionWeight * 2.0 - 1.0;
  97308. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 + (1.0 - BackgroundMaterial.StandardReflectance0) * reflectionWeight;
  97309. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 + (1.0 - BackgroundMaterial.StandardReflectance90) * reflectionWeight;
  97310. }
  97311. },
  97312. enumerable: true,
  97313. configurable: true
  97314. });
  97315. Object.defineProperty(BackgroundMaterial.prototype, "fovMultiplier", {
  97316. /**
  97317. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  97318. * Best used when trying to implement visual zoom effects like fish-eye or binoculars while not adjusting camera fov.
  97319. * Recommended to be keep at 1.0 except for special cases.
  97320. */
  97321. get: function () {
  97322. return this._fovMultiplier;
  97323. },
  97324. set: function (value) {
  97325. if (isNaN(value)) {
  97326. value = 1.0;
  97327. }
  97328. this._fovMultiplier = Math.max(0.0, Math.min(2.0, value));
  97329. },
  97330. enumerable: true,
  97331. configurable: true
  97332. });
  97333. /**
  97334. * Attaches a new image processing configuration to the PBR Material.
  97335. * @param configuration (if null the scene configuration will be use)
  97336. */
  97337. BackgroundMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  97338. var _this = this;
  97339. if (configuration === this._imageProcessingConfiguration) {
  97340. return;
  97341. }
  97342. // Detaches observer.
  97343. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  97344. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  97345. }
  97346. // Pick the scene configuration if needed.
  97347. if (!configuration) {
  97348. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  97349. }
  97350. else {
  97351. this._imageProcessingConfiguration = configuration;
  97352. }
  97353. // Attaches observer.
  97354. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  97355. _this._computePrimaryColorFromPerceptualColor();
  97356. _this._markAllSubMeshesAsImageProcessingDirty();
  97357. });
  97358. };
  97359. Object.defineProperty(BackgroundMaterial.prototype, "imageProcessingConfiguration", {
  97360. /**
  97361. * Gets the image processing configuration used either in this material.
  97362. */
  97363. get: function () {
  97364. return this._imageProcessingConfiguration;
  97365. },
  97366. /**
  97367. * Sets the Default image processing configuration used either in the this material.
  97368. *
  97369. * If sets to null, the scene one is in use.
  97370. */
  97371. set: function (value) {
  97372. this._attachImageProcessingConfiguration(value);
  97373. // Ensure the effect will be rebuilt.
  97374. this._markAllSubMeshesAsTexturesDirty();
  97375. },
  97376. enumerable: true,
  97377. configurable: true
  97378. });
  97379. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurvesEnabled", {
  97380. /**
  97381. * Gets wether the color curves effect is enabled.
  97382. */
  97383. get: function () {
  97384. return this.imageProcessingConfiguration.colorCurvesEnabled;
  97385. },
  97386. /**
  97387. * Sets wether the color curves effect is enabled.
  97388. */
  97389. set: function (value) {
  97390. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  97391. },
  97392. enumerable: true,
  97393. configurable: true
  97394. });
  97395. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingEnabled", {
  97396. /**
  97397. * Gets wether the color grading effect is enabled.
  97398. */
  97399. get: function () {
  97400. return this.imageProcessingConfiguration.colorGradingEnabled;
  97401. },
  97402. /**
  97403. * Gets wether the color grading effect is enabled.
  97404. */
  97405. set: function (value) {
  97406. this.imageProcessingConfiguration.colorGradingEnabled = value;
  97407. },
  97408. enumerable: true,
  97409. configurable: true
  97410. });
  97411. Object.defineProperty(BackgroundMaterial.prototype, "cameraToneMappingEnabled", {
  97412. /**
  97413. * Gets wether tonemapping is enabled or not.
  97414. */
  97415. get: function () {
  97416. return this._imageProcessingConfiguration.toneMappingEnabled;
  97417. },
  97418. /**
  97419. * Sets wether tonemapping is enabled or not
  97420. */
  97421. set: function (value) {
  97422. this._imageProcessingConfiguration.toneMappingEnabled = value;
  97423. },
  97424. enumerable: true,
  97425. configurable: true
  97426. });
  97427. ;
  97428. ;
  97429. Object.defineProperty(BackgroundMaterial.prototype, "cameraExposure", {
  97430. /**
  97431. * The camera exposure used on this material.
  97432. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  97433. * This corresponds to a photographic exposure.
  97434. */
  97435. get: function () {
  97436. return this._imageProcessingConfiguration.exposure;
  97437. },
  97438. /**
  97439. * The camera exposure used on this material.
  97440. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  97441. * This corresponds to a photographic exposure.
  97442. */
  97443. set: function (value) {
  97444. this._imageProcessingConfiguration.exposure = value;
  97445. },
  97446. enumerable: true,
  97447. configurable: true
  97448. });
  97449. ;
  97450. ;
  97451. Object.defineProperty(BackgroundMaterial.prototype, "cameraContrast", {
  97452. /**
  97453. * Gets The camera contrast used on this material.
  97454. */
  97455. get: function () {
  97456. return this._imageProcessingConfiguration.contrast;
  97457. },
  97458. /**
  97459. * Sets The camera contrast used on this material.
  97460. */
  97461. set: function (value) {
  97462. this._imageProcessingConfiguration.contrast = value;
  97463. },
  97464. enumerable: true,
  97465. configurable: true
  97466. });
  97467. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingTexture", {
  97468. /**
  97469. * Gets the Color Grading 2D Lookup Texture.
  97470. */
  97471. get: function () {
  97472. return this._imageProcessingConfiguration.colorGradingTexture;
  97473. },
  97474. /**
  97475. * Sets the Color Grading 2D Lookup Texture.
  97476. */
  97477. set: function (value) {
  97478. this.imageProcessingConfiguration.colorGradingTexture = value;
  97479. },
  97480. enumerable: true,
  97481. configurable: true
  97482. });
  97483. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurves", {
  97484. /**
  97485. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  97486. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  97487. * 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;
  97488. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  97489. */
  97490. get: function () {
  97491. return this.imageProcessingConfiguration.colorCurves;
  97492. },
  97493. /**
  97494. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  97495. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  97496. * 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;
  97497. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  97498. */
  97499. set: function (value) {
  97500. this.imageProcessingConfiguration.colorCurves = value;
  97501. },
  97502. enumerable: true,
  97503. configurable: true
  97504. });
  97505. /**
  97506. * The entire material has been created in order to prevent overdraw.
  97507. * @returns false
  97508. */
  97509. BackgroundMaterial.prototype.needAlphaTesting = function () {
  97510. return true;
  97511. };
  97512. /**
  97513. * The entire material has been created in order to prevent overdraw.
  97514. * @returns true if blending is enable
  97515. */
  97516. BackgroundMaterial.prototype.needAlphaBlending = function () {
  97517. return ((this.alpha < 0) || (this._diffuseTexture != null && this._diffuseTexture.hasAlpha));
  97518. };
  97519. /**
  97520. * Checks wether the material is ready to be rendered for a given mesh.
  97521. * @param mesh The mesh to render
  97522. * @param subMesh The submesh to check against
  97523. * @param useInstances Specify wether or not the material is used with instances
  97524. * @returns true if all the dependencies are ready (Textures, Effects...)
  97525. */
  97526. BackgroundMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  97527. var _this = this;
  97528. if (useInstances === void 0) { useInstances = false; }
  97529. if (subMesh.effect && this.isFrozen) {
  97530. if (this._wasPreviouslyReady) {
  97531. return true;
  97532. }
  97533. }
  97534. if (!subMesh._materialDefines) {
  97535. subMesh._materialDefines = new BackgroundMaterialDefines();
  97536. }
  97537. var scene = this.getScene();
  97538. var defines = subMesh._materialDefines;
  97539. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  97540. if (defines._renderId === scene.getRenderId()) {
  97541. return true;
  97542. }
  97543. }
  97544. var engine = scene.getEngine();
  97545. // Lights
  97546. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, false, this._maxSimultaneousLights);
  97547. defines._needNormals = true;
  97548. // Textures
  97549. if (defines._areTexturesDirty) {
  97550. defines._needUVs = false;
  97551. if (scene.texturesEnabled) {
  97552. if (scene.getEngine().getCaps().textureLOD) {
  97553. defines.TEXTURELODSUPPORT = true;
  97554. }
  97555. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  97556. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  97557. return false;
  97558. }
  97559. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  97560. defines.DIFFUSEHASALPHA = this._diffuseTexture.hasAlpha;
  97561. defines.GAMMADIFFUSE = this._diffuseTexture.gammaSpace;
  97562. defines.OPACITYFRESNEL = this._opacityFresnel;
  97563. }
  97564. else {
  97565. defines.DIFFUSE = false;
  97566. defines.DIFFUSEHASALPHA = false;
  97567. defines.GAMMADIFFUSE = false;
  97568. defines.OPACITYFRESNEL = false;
  97569. }
  97570. var reflectionTexture = this._reflectionTexture;
  97571. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  97572. if (!reflectionTexture.isReadyOrNotBlocking()) {
  97573. return false;
  97574. }
  97575. defines.REFLECTION = true;
  97576. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  97577. defines.REFLECTIONBLUR = this._reflectionBlur > 0;
  97578. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  97579. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  97580. defines.EQUIRECTANGULAR_RELFECTION_FOV = this.useEquirectangularFOV;
  97581. defines.REFLECTIONBGR = this.switchToBGR;
  97582. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  97583. defines.INVERTCUBICMAP = true;
  97584. }
  97585. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  97586. switch (reflectionTexture.coordinatesMode) {
  97587. case BABYLON.Texture.EXPLICIT_MODE:
  97588. defines.REFLECTIONMAP_EXPLICIT = true;
  97589. break;
  97590. case BABYLON.Texture.PLANAR_MODE:
  97591. defines.REFLECTIONMAP_PLANAR = true;
  97592. break;
  97593. case BABYLON.Texture.PROJECTION_MODE:
  97594. defines.REFLECTIONMAP_PROJECTION = true;
  97595. break;
  97596. case BABYLON.Texture.SKYBOX_MODE:
  97597. defines.REFLECTIONMAP_SKYBOX = true;
  97598. break;
  97599. case BABYLON.Texture.SPHERICAL_MODE:
  97600. defines.REFLECTIONMAP_SPHERICAL = true;
  97601. break;
  97602. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  97603. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  97604. break;
  97605. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  97606. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  97607. break;
  97608. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  97609. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  97610. break;
  97611. case BABYLON.Texture.CUBIC_MODE:
  97612. case BABYLON.Texture.INVCUBIC_MODE:
  97613. default:
  97614. defines.REFLECTIONMAP_CUBIC = true;
  97615. break;
  97616. }
  97617. if (this.reflectionFresnel) {
  97618. defines.REFLECTIONFRESNEL = true;
  97619. defines.REFLECTIONFALLOFF = this.reflectionFalloffDistance > 0;
  97620. this._reflectionControls.x = this.reflectionAmount;
  97621. this._reflectionControls.y = this.reflectionReflectance0;
  97622. this._reflectionControls.z = this.reflectionReflectance90;
  97623. this._reflectionControls.w = 1 / this.reflectionFalloffDistance;
  97624. }
  97625. else {
  97626. defines.REFLECTIONFRESNEL = false;
  97627. defines.REFLECTIONFALLOFF = false;
  97628. }
  97629. }
  97630. else {
  97631. defines.REFLECTION = false;
  97632. defines.REFLECTIONFRESNEL = false;
  97633. defines.REFLECTIONFALLOFF = false;
  97634. defines.REFLECTIONBLUR = false;
  97635. defines.REFLECTIONMAP_3D = false;
  97636. defines.REFLECTIONMAP_SPHERICAL = false;
  97637. defines.REFLECTIONMAP_PLANAR = false;
  97638. defines.REFLECTIONMAP_CUBIC = false;
  97639. defines.REFLECTIONMAP_PROJECTION = false;
  97640. defines.REFLECTIONMAP_SKYBOX = false;
  97641. defines.REFLECTIONMAP_EXPLICIT = false;
  97642. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  97643. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  97644. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  97645. defines.INVERTCUBICMAP = false;
  97646. defines.REFLECTIONMAP_OPPOSITEZ = false;
  97647. defines.LODINREFLECTIONALPHA = false;
  97648. defines.GAMMAREFLECTION = false;
  97649. }
  97650. }
  97651. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  97652. defines.USERGBCOLOR = this._useRGBColor;
  97653. defines.NOISE = this._enableNoise;
  97654. }
  97655. if (defines._areLightsDirty) {
  97656. defines.USEHIGHLIGHTANDSHADOWCOLORS = !this._useRGBColor && (this._primaryColorShadowLevel !== 0 || this._primaryColorHighlightLevel !== 0);
  97657. }
  97658. if (defines._areImageProcessingDirty) {
  97659. if (!this._imageProcessingConfiguration.isReady()) {
  97660. return false;
  97661. }
  97662. this._imageProcessingConfiguration.prepareDefines(defines);
  97663. }
  97664. // Misc.
  97665. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, false, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  97666. // Values that need to be evaluated on every frame
  97667. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  97668. // Attribs
  97669. if (BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, false, true, false)) {
  97670. if (mesh) {
  97671. if (!scene.getEngine().getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  97672. mesh.createNormals(true);
  97673. BABYLON.Tools.Warn("BackgroundMaterial: Normals have been created for the mesh: " + mesh.name);
  97674. }
  97675. }
  97676. }
  97677. // Get correct effect
  97678. if (defines.isDirty) {
  97679. defines.markAsProcessed();
  97680. scene.resetCachedMaterial();
  97681. // Fallbacks
  97682. var fallbacks = new BABYLON.EffectFallbacks();
  97683. if (defines.FOG) {
  97684. fallbacks.addFallback(0, "FOG");
  97685. }
  97686. if (defines.POINTSIZE) {
  97687. fallbacks.addFallback(1, "POINTSIZE");
  97688. }
  97689. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  97690. if (defines.NUM_BONE_INFLUENCERS > 0) {
  97691. fallbacks.addCPUSkinningFallback(0, mesh);
  97692. }
  97693. //Attributes
  97694. var attribs = [BABYLON.VertexBuffer.PositionKind];
  97695. if (defines.NORMAL) {
  97696. attribs.push(BABYLON.VertexBuffer.NormalKind);
  97697. }
  97698. if (defines.UV1) {
  97699. attribs.push(BABYLON.VertexBuffer.UVKind);
  97700. }
  97701. if (defines.UV2) {
  97702. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  97703. }
  97704. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  97705. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  97706. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType",
  97707. "vFogInfos", "vFogColor", "pointSize",
  97708. "vClipPlane", "mBones",
  97709. "vPrimaryColor", "vPrimaryColorShadow",
  97710. "vReflectionInfos", "reflectionMatrix", "vReflectionMicrosurfaceInfos", "fFovMultiplier",
  97711. "shadowLevel", "alpha",
  97712. "vBackgroundCenter", "vReflectionControl",
  97713. "vDiffuseInfos", "diffuseMatrix",
  97714. ];
  97715. var samplers = ["diffuseSampler", "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh"];
  97716. var uniformBuffers = ["Material", "Scene"];
  97717. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  97718. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  97719. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  97720. uniformsNames: uniforms,
  97721. uniformBuffersNames: uniformBuffers,
  97722. samplers: samplers,
  97723. defines: defines,
  97724. maxSimultaneousLights: this._maxSimultaneousLights
  97725. });
  97726. var onCompiled = function (effect) {
  97727. if (_this.onCompiled) {
  97728. _this.onCompiled(effect);
  97729. }
  97730. _this.bindSceneUniformBuffer(effect, scene.getSceneUniformBuffer());
  97731. };
  97732. var join = defines.toString();
  97733. subMesh.setEffect(scene.getEngine().createEffect("background", {
  97734. attributes: attribs,
  97735. uniformsNames: uniforms,
  97736. uniformBuffersNames: uniformBuffers,
  97737. samplers: samplers,
  97738. defines: join,
  97739. fallbacks: fallbacks,
  97740. onCompiled: onCompiled,
  97741. onError: this.onError,
  97742. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights }
  97743. }, engine), defines);
  97744. this.buildUniformLayout();
  97745. }
  97746. if (!subMesh.effect || !subMesh.effect.isReady()) {
  97747. return false;
  97748. }
  97749. defines._renderId = scene.getRenderId();
  97750. this._wasPreviouslyReady = true;
  97751. return true;
  97752. };
  97753. /**
  97754. * Compute the primary color according to the chosen perceptual color.
  97755. */
  97756. BackgroundMaterial.prototype._computePrimaryColorFromPerceptualColor = function () {
  97757. if (!this.__perceptualColor) {
  97758. return;
  97759. }
  97760. this._primaryColor.copyFrom(this.__perceptualColor);
  97761. // Revert gamma space.
  97762. this._primaryColor.toLinearSpaceToRef(this._primaryColor);
  97763. // Revert image processing configuration.
  97764. if (this._imageProcessingConfiguration) {
  97765. // Revert Exposure.
  97766. this._primaryColor.scaleToRef(1 / this._imageProcessingConfiguration.exposure, this._primaryColor);
  97767. }
  97768. this._computePrimaryColors();
  97769. };
  97770. /**
  97771. * Compute the highlights and shadow colors according to their chosen levels.
  97772. */
  97773. BackgroundMaterial.prototype._computePrimaryColors = function () {
  97774. if (this._primaryColorShadowLevel === 0 && this._primaryColorHighlightLevel === 0) {
  97775. return;
  97776. }
  97777. // Find the highlight color based on the configuration.
  97778. this._primaryColor.scaleToRef(this._primaryColorShadowLevel, this._primaryShadowColor);
  97779. this._primaryColor.subtractToRef(this._primaryShadowColor, this._primaryShadowColor);
  97780. // Find the shadow color based on the configuration.
  97781. this._white.subtractToRef(this._primaryColor, this._primaryHighlightColor);
  97782. this._primaryHighlightColor.scaleToRef(this._primaryColorHighlightLevel, this._primaryHighlightColor);
  97783. this._primaryColor.addToRef(this._primaryHighlightColor, this._primaryHighlightColor);
  97784. };
  97785. /**
  97786. * Build the uniform buffer used in the material.
  97787. */
  97788. BackgroundMaterial.prototype.buildUniformLayout = function () {
  97789. // Order is important !
  97790. this._uniformBuffer.addUniform("vPrimaryColor", 4);
  97791. this._uniformBuffer.addUniform("vPrimaryColorShadow", 4);
  97792. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  97793. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  97794. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  97795. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  97796. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  97797. this._uniformBuffer.addUniform("fFovMultiplier", 1);
  97798. this._uniformBuffer.addUniform("pointSize", 1);
  97799. this._uniformBuffer.addUniform("shadowLevel", 1);
  97800. this._uniformBuffer.addUniform("alpha", 1);
  97801. this._uniformBuffer.addUniform("vBackgroundCenter", 3);
  97802. this._uniformBuffer.addUniform("vReflectionControl", 4);
  97803. this._uniformBuffer.create();
  97804. };
  97805. /**
  97806. * Unbind the material.
  97807. */
  97808. BackgroundMaterial.prototype.unbind = function () {
  97809. if (this._diffuseTexture && this._diffuseTexture.isRenderTarget) {
  97810. this._uniformBuffer.setTexture("diffuseSampler", null);
  97811. }
  97812. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  97813. this._uniformBuffer.setTexture("reflectionSampler", null);
  97814. }
  97815. _super.prototype.unbind.call(this);
  97816. };
  97817. /**
  97818. * Bind only the world matrix to the material.
  97819. * @param world The world matrix to bind.
  97820. */
  97821. BackgroundMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  97822. this._activeEffect.setMatrix("world", world);
  97823. };
  97824. /**
  97825. * Bind the material for a dedicated submeh (every used meshes will be considered opaque).
  97826. * @param world The world matrix to bind.
  97827. * @param subMesh The submesh to bind for.
  97828. */
  97829. BackgroundMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  97830. var scene = this.getScene();
  97831. var defines = subMesh._materialDefines;
  97832. if (!defines) {
  97833. return;
  97834. }
  97835. var effect = subMesh.effect;
  97836. if (!effect) {
  97837. return;
  97838. }
  97839. this._activeEffect = effect;
  97840. // Matrices
  97841. this.bindOnlyWorldMatrix(world);
  97842. // Bones
  97843. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  97844. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  97845. if (mustRebind) {
  97846. this._uniformBuffer.bindToEffect(effect, "Material");
  97847. this.bindViewProjection(effect);
  97848. var reflectionTexture = this._reflectionTexture;
  97849. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  97850. // Texture uniforms
  97851. if (scene.texturesEnabled) {
  97852. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  97853. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  97854. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  97855. }
  97856. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  97857. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  97858. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, this._reflectionBlur);
  97859. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  97860. }
  97861. }
  97862. if (this.shadowLevel > 0) {
  97863. this._uniformBuffer.updateFloat("shadowLevel", this.shadowLevel);
  97864. }
  97865. this._uniformBuffer.updateFloat("alpha", this.alpha);
  97866. // Point size
  97867. if (this.pointsCloud) {
  97868. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  97869. }
  97870. if (defines.USEHIGHLIGHTANDSHADOWCOLORS) {
  97871. this._uniformBuffer.updateColor4("vPrimaryColor", this._primaryHighlightColor, 1.0);
  97872. this._uniformBuffer.updateColor4("vPrimaryColorShadow", this._primaryShadowColor, 1.0);
  97873. }
  97874. else {
  97875. this._uniformBuffer.updateColor4("vPrimaryColor", this._primaryColor, 1.0);
  97876. }
  97877. }
  97878. this._uniformBuffer.updateFloat("fFovMultiplier", this._fovMultiplier);
  97879. // Textures
  97880. if (scene.texturesEnabled) {
  97881. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  97882. this._uniformBuffer.setTexture("diffuseSampler", this._diffuseTexture);
  97883. }
  97884. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  97885. if (defines.REFLECTIONBLUR && defines.TEXTURELODSUPPORT) {
  97886. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  97887. }
  97888. else if (!defines.REFLECTIONBLUR) {
  97889. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  97890. }
  97891. else {
  97892. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  97893. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  97894. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  97895. }
  97896. if (defines.REFLECTIONFRESNEL) {
  97897. this._uniformBuffer.updateFloat3("vBackgroundCenter", this.sceneCenter.x, this.sceneCenter.y, this.sceneCenter.z);
  97898. this._uniformBuffer.updateFloat4("vReflectionControl", this._reflectionControls.x, this._reflectionControls.y, this._reflectionControls.z, this._reflectionControls.w);
  97899. }
  97900. }
  97901. }
  97902. // Clip plane
  97903. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  97904. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  97905. }
  97906. if (mustRebind || !this.isFrozen) {
  97907. if (scene.lightsEnabled) {
  97908. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, false);
  97909. }
  97910. // View
  97911. this.bindView(effect);
  97912. // Fog
  97913. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  97914. // image processing
  97915. this._imageProcessingConfiguration.bind(this._activeEffect);
  97916. }
  97917. this._uniformBuffer.update();
  97918. this._afterBind(mesh);
  97919. };
  97920. /**
  97921. * Dispose the material.
  97922. * @param forceDisposeEffect Force disposal of the associated effect.
  97923. * @param forceDisposeTextures Force disposal of the associated textures.
  97924. */
  97925. BackgroundMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  97926. if (forceDisposeEffect === void 0) { forceDisposeEffect = false; }
  97927. if (forceDisposeTextures === void 0) { forceDisposeTextures = false; }
  97928. if (forceDisposeTextures) {
  97929. if (this.diffuseTexture) {
  97930. this.diffuseTexture.dispose();
  97931. }
  97932. if (this.reflectionTexture) {
  97933. this.reflectionTexture.dispose();
  97934. }
  97935. }
  97936. this._renderTargets.dispose();
  97937. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  97938. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  97939. }
  97940. _super.prototype.dispose.call(this, forceDisposeEffect);
  97941. };
  97942. /**
  97943. * Clones the material.
  97944. * @param name The cloned name.
  97945. * @returns The cloned material.
  97946. */
  97947. BackgroundMaterial.prototype.clone = function (name) {
  97948. var _this = this;
  97949. return BABYLON.SerializationHelper.Clone(function () { return new BackgroundMaterial(name, _this.getScene()); }, this);
  97950. };
  97951. /**
  97952. * Serializes the current material to its JSON representation.
  97953. * @returns The JSON representation.
  97954. */
  97955. BackgroundMaterial.prototype.serialize = function () {
  97956. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  97957. serializationObject.customType = "BABYLON.BackgroundMaterial";
  97958. return serializationObject;
  97959. };
  97960. /**
  97961. * Gets the class name of the material
  97962. * @returns "BackgroundMaterial"
  97963. */
  97964. BackgroundMaterial.prototype.getClassName = function () {
  97965. return "BackgroundMaterial";
  97966. };
  97967. /**
  97968. * Parse a JSON input to create back a background material.
  97969. * @param source The JSON data to parse
  97970. * @param scene The scene to create the parsed material in
  97971. * @param rootUrl The root url of the assets the material depends upon
  97972. * @returns the instantiated BackgroundMaterial.
  97973. */
  97974. BackgroundMaterial.Parse = function (source, scene, rootUrl) {
  97975. return BABYLON.SerializationHelper.Parse(function () { return new BackgroundMaterial(source.name, scene); }, source, scene, rootUrl);
  97976. };
  97977. /**
  97978. * Standard reflectance value at parallel view angle.
  97979. */
  97980. BackgroundMaterial.StandardReflectance0 = 0.05;
  97981. /**
  97982. * Standard reflectance value at grazing angle.
  97983. */
  97984. BackgroundMaterial.StandardReflectance90 = 0.5;
  97985. __decorate([
  97986. BABYLON.serializeAsColor3()
  97987. ], BackgroundMaterial.prototype, "_primaryColor", void 0);
  97988. __decorate([
  97989. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  97990. ], BackgroundMaterial.prototype, "primaryColor", void 0);
  97991. __decorate([
  97992. BABYLON.serializeAsColor3()
  97993. ], BackgroundMaterial.prototype, "__perceptualColor", void 0);
  97994. __decorate([
  97995. BABYLON.serialize()
  97996. ], BackgroundMaterial.prototype, "_primaryColorShadowLevel", void 0);
  97997. __decorate([
  97998. BABYLON.serialize()
  97999. ], BackgroundMaterial.prototype, "_primaryColorHighlightLevel", void 0);
  98000. __decorate([
  98001. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  98002. ], BackgroundMaterial.prototype, "primaryColorHighlightLevel", null);
  98003. __decorate([
  98004. BABYLON.serializeAsTexture()
  98005. ], BackgroundMaterial.prototype, "_reflectionTexture", void 0);
  98006. __decorate([
  98007. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  98008. ], BackgroundMaterial.prototype, "reflectionTexture", void 0);
  98009. __decorate([
  98010. BABYLON.serialize()
  98011. ], BackgroundMaterial.prototype, "_reflectionBlur", void 0);
  98012. __decorate([
  98013. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  98014. ], BackgroundMaterial.prototype, "reflectionBlur", void 0);
  98015. __decorate([
  98016. BABYLON.serializeAsTexture()
  98017. ], BackgroundMaterial.prototype, "_diffuseTexture", void 0);
  98018. __decorate([
  98019. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  98020. ], BackgroundMaterial.prototype, "diffuseTexture", void 0);
  98021. __decorate([
  98022. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  98023. ], BackgroundMaterial.prototype, "shadowLights", void 0);
  98024. __decorate([
  98025. BABYLON.serialize()
  98026. ], BackgroundMaterial.prototype, "_shadowLevel", void 0);
  98027. __decorate([
  98028. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  98029. ], BackgroundMaterial.prototype, "shadowLevel", void 0);
  98030. __decorate([
  98031. BABYLON.serializeAsVector3()
  98032. ], BackgroundMaterial.prototype, "_sceneCenter", void 0);
  98033. __decorate([
  98034. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  98035. ], BackgroundMaterial.prototype, "sceneCenter", void 0);
  98036. __decorate([
  98037. BABYLON.serialize()
  98038. ], BackgroundMaterial.prototype, "_opacityFresnel", void 0);
  98039. __decorate([
  98040. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  98041. ], BackgroundMaterial.prototype, "opacityFresnel", void 0);
  98042. __decorate([
  98043. BABYLON.serialize()
  98044. ], BackgroundMaterial.prototype, "_reflectionFresnel", void 0);
  98045. __decorate([
  98046. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  98047. ], BackgroundMaterial.prototype, "reflectionFresnel", void 0);
  98048. __decorate([
  98049. BABYLON.serialize()
  98050. ], BackgroundMaterial.prototype, "_reflectionFalloffDistance", void 0);
  98051. __decorate([
  98052. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  98053. ], BackgroundMaterial.prototype, "reflectionFalloffDistance", void 0);
  98054. __decorate([
  98055. BABYLON.serialize()
  98056. ], BackgroundMaterial.prototype, "_reflectionAmount", void 0);
  98057. __decorate([
  98058. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  98059. ], BackgroundMaterial.prototype, "reflectionAmount", void 0);
  98060. __decorate([
  98061. BABYLON.serialize()
  98062. ], BackgroundMaterial.prototype, "_reflectionReflectance0", void 0);
  98063. __decorate([
  98064. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  98065. ], BackgroundMaterial.prototype, "reflectionReflectance0", void 0);
  98066. __decorate([
  98067. BABYLON.serialize()
  98068. ], BackgroundMaterial.prototype, "_reflectionReflectance90", void 0);
  98069. __decorate([
  98070. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  98071. ], BackgroundMaterial.prototype, "reflectionReflectance90", void 0);
  98072. __decorate([
  98073. BABYLON.serialize()
  98074. ], BackgroundMaterial.prototype, "_useRGBColor", void 0);
  98075. __decorate([
  98076. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  98077. ], BackgroundMaterial.prototype, "useRGBColor", void 0);
  98078. __decorate([
  98079. BABYLON.serialize()
  98080. ], BackgroundMaterial.prototype, "_enableNoise", void 0);
  98081. __decorate([
  98082. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  98083. ], BackgroundMaterial.prototype, "enableNoise", void 0);
  98084. __decorate([
  98085. BABYLON.serialize()
  98086. ], BackgroundMaterial.prototype, "_maxSimultaneousLights", void 0);
  98087. __decorate([
  98088. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  98089. ], BackgroundMaterial.prototype, "maxSimultaneousLights", void 0);
  98090. __decorate([
  98091. BABYLON.serializeAsImageProcessingConfiguration()
  98092. ], BackgroundMaterial.prototype, "_imageProcessingConfiguration", void 0);
  98093. return BackgroundMaterial;
  98094. }(BABYLON.PushMaterial));
  98095. BABYLON.BackgroundMaterial = BackgroundMaterial;
  98096. })(BABYLON || (BABYLON = {}));
  98097. //# sourceMappingURL=babylon.backgroundMaterial.js.map
  98098. var __assign = (this && this.__assign) || Object.assign || function(t) {
  98099. for (var s, i = 1, n = arguments.length; i < n; i++) {
  98100. s = arguments[i];
  98101. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  98102. t[p] = s[p];
  98103. }
  98104. return t;
  98105. };
  98106. var BABYLON;
  98107. (function (BABYLON) {
  98108. /**
  98109. * The Environment helper class can be used to add a fully featuread none expensive background to your scene.
  98110. * It includes by default a skybox and a ground relying on the BackgroundMaterial.
  98111. * It also helps with the default setup of your imageProcessing configuration.
  98112. */
  98113. var EnvironmentHelper = /** @class */ (function () {
  98114. /**
  98115. * constructor
  98116. * @param options
  98117. * @param scene The scene to add the material to
  98118. */
  98119. function EnvironmentHelper(options, scene) {
  98120. var _this = this;
  98121. this._errorHandler = function (message, exception) {
  98122. _this.onErrorObservable.notifyObservers({ message: message, exception: exception });
  98123. };
  98124. this._options = __assign({}, EnvironmentHelper._getDefaultOptions(), options);
  98125. this._scene = scene;
  98126. this.onErrorObservable = new BABYLON.Observable();
  98127. this._setupBackground();
  98128. this._setupImageProcessing();
  98129. }
  98130. /**
  98131. * Creates the default options for the helper.
  98132. */
  98133. EnvironmentHelper._getDefaultOptions = function () {
  98134. return {
  98135. createGround: true,
  98136. groundSize: 15,
  98137. groundTexture: this._groundTextureCDNUrl,
  98138. groundColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  98139. groundOpacity: 0.9,
  98140. enableGroundShadow: true,
  98141. groundShadowLevel: 0.5,
  98142. enableGroundMirror: false,
  98143. groundMirrorSizeRatio: 0.3,
  98144. groundMirrorBlurKernel: 64,
  98145. groundMirrorAmount: 1,
  98146. groundMirrorFresnelWeight: 1,
  98147. groundMirrorFallOffDistance: 0,
  98148. groundMirrorTextureType: BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT,
  98149. groundYBias: 0.00001,
  98150. createSkybox: true,
  98151. skyboxSize: 20,
  98152. skyboxTexture: this._skyboxTextureCDNUrl,
  98153. skyboxColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  98154. backgroundYRotation: 0,
  98155. sizeAuto: true,
  98156. rootPosition: BABYLON.Vector3.Zero(),
  98157. setupImageProcessing: true,
  98158. environmentTexture: this._environmentTextureCDNUrl,
  98159. cameraExposure: 0.8,
  98160. cameraContrast: 1.2,
  98161. toneMappingEnabled: true,
  98162. };
  98163. };
  98164. Object.defineProperty(EnvironmentHelper.prototype, "rootMesh", {
  98165. /**
  98166. * Gets the root mesh created by the helper.
  98167. */
  98168. get: function () {
  98169. return this._rootMesh;
  98170. },
  98171. enumerable: true,
  98172. configurable: true
  98173. });
  98174. Object.defineProperty(EnvironmentHelper.prototype, "skybox", {
  98175. /**
  98176. * Gets the skybox created by the helper.
  98177. */
  98178. get: function () {
  98179. return this._skybox;
  98180. },
  98181. enumerable: true,
  98182. configurable: true
  98183. });
  98184. Object.defineProperty(EnvironmentHelper.prototype, "skyboxTexture", {
  98185. /**
  98186. * Gets the skybox texture created by the helper.
  98187. */
  98188. get: function () {
  98189. return this._skyboxTexture;
  98190. },
  98191. enumerable: true,
  98192. configurable: true
  98193. });
  98194. Object.defineProperty(EnvironmentHelper.prototype, "skyboxMaterial", {
  98195. /**
  98196. * Gets the skybox material created by the helper.
  98197. */
  98198. get: function () {
  98199. return this._skyboxMaterial;
  98200. },
  98201. enumerable: true,
  98202. configurable: true
  98203. });
  98204. Object.defineProperty(EnvironmentHelper.prototype, "ground", {
  98205. /**
  98206. * Gets the ground mesh created by the helper.
  98207. */
  98208. get: function () {
  98209. return this._ground;
  98210. },
  98211. enumerable: true,
  98212. configurable: true
  98213. });
  98214. Object.defineProperty(EnvironmentHelper.prototype, "groundTexture", {
  98215. /**
  98216. * Gets the ground texture created by the helper.
  98217. */
  98218. get: function () {
  98219. return this._groundTexture;
  98220. },
  98221. enumerable: true,
  98222. configurable: true
  98223. });
  98224. Object.defineProperty(EnvironmentHelper.prototype, "groundMirror", {
  98225. /**
  98226. * Gets the ground mirror created by the helper.
  98227. */
  98228. get: function () {
  98229. return this._groundMirror;
  98230. },
  98231. enumerable: true,
  98232. configurable: true
  98233. });
  98234. Object.defineProperty(EnvironmentHelper.prototype, "groundMirrorRenderList", {
  98235. /**
  98236. * Gets the ground mirror render list to helps pushing the meshes
  98237. * you wish in the ground reflection.
  98238. */
  98239. get: function () {
  98240. if (this._groundMirror) {
  98241. return this._groundMirror.renderList;
  98242. }
  98243. return null;
  98244. },
  98245. enumerable: true,
  98246. configurable: true
  98247. });
  98248. Object.defineProperty(EnvironmentHelper.prototype, "groundMaterial", {
  98249. /**
  98250. * Gets the ground material created by the helper.
  98251. */
  98252. get: function () {
  98253. return this._groundMaterial;
  98254. },
  98255. enumerable: true,
  98256. configurable: true
  98257. });
  98258. /**
  98259. * Updates the background according to the new options
  98260. * @param options
  98261. */
  98262. EnvironmentHelper.prototype.updateOptions = function (options) {
  98263. var newOptions = __assign({}, this._options, options);
  98264. if (this._ground && !newOptions.createGround) {
  98265. this._ground.dispose();
  98266. this._ground = null;
  98267. }
  98268. if (this._groundMaterial && !newOptions.createGround) {
  98269. this._groundMaterial.dispose();
  98270. this._groundMaterial = null;
  98271. }
  98272. if (this._groundTexture) {
  98273. if (this._options.groundTexture != newOptions.groundTexture) {
  98274. this._groundTexture.dispose();
  98275. this._groundTexture = null;
  98276. }
  98277. }
  98278. if (this._skybox && !newOptions.createSkybox) {
  98279. this._skybox.dispose();
  98280. this._skybox = null;
  98281. }
  98282. if (this._skyboxMaterial && !newOptions.createSkybox) {
  98283. this._skyboxMaterial.dispose();
  98284. this._skyboxMaterial = null;
  98285. }
  98286. if (this._skyboxTexture) {
  98287. if (this._options.skyboxTexture != newOptions.skyboxTexture) {
  98288. this._skyboxTexture.dispose();
  98289. this._skyboxTexture = null;
  98290. }
  98291. }
  98292. if (this._groundMirror && !newOptions.enableGroundMirror) {
  98293. this._groundMirror.dispose();
  98294. this._groundMirror = null;
  98295. }
  98296. if (this._scene.environmentTexture) {
  98297. if (this._options.environmentTexture != newOptions.environmentTexture) {
  98298. this._scene.environmentTexture.dispose();
  98299. }
  98300. }
  98301. this._options = newOptions;
  98302. this._setupBackground();
  98303. this._setupImageProcessing();
  98304. };
  98305. /**
  98306. * Sets the primary color of all the available elements.
  98307. * @param color the main color to affect to the ground and the background
  98308. */
  98309. EnvironmentHelper.prototype.setMainColor = function (color) {
  98310. if (this.groundMaterial) {
  98311. this.groundMaterial.primaryColor = color;
  98312. }
  98313. if (this.skyboxMaterial) {
  98314. this.skyboxMaterial.primaryColor = color;
  98315. }
  98316. if (this.groundMirror) {
  98317. this.groundMirror.clearColor = new BABYLON.Color4(color.r, color.g, color.b, 1.0);
  98318. }
  98319. };
  98320. /**
  98321. * Setup the image processing according to the specified options.
  98322. */
  98323. EnvironmentHelper.prototype._setupImageProcessing = function () {
  98324. if (this._options.setupImageProcessing) {
  98325. this._scene.imageProcessingConfiguration.contrast = this._options.cameraContrast;
  98326. this._scene.imageProcessingConfiguration.exposure = this._options.cameraExposure;
  98327. this._scene.imageProcessingConfiguration.toneMappingEnabled = this._options.toneMappingEnabled;
  98328. this._setupEnvironmentTexture();
  98329. }
  98330. };
  98331. /**
  98332. * Setup the environment texture according to the specified options.
  98333. */
  98334. EnvironmentHelper.prototype._setupEnvironmentTexture = function () {
  98335. if (this._scene.environmentTexture) {
  98336. return;
  98337. }
  98338. if (this._options.environmentTexture instanceof BABYLON.BaseTexture) {
  98339. this._scene.environmentTexture = this._options.environmentTexture;
  98340. return;
  98341. }
  98342. var environmentTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(this._options.environmentTexture, this._scene);
  98343. this._scene.environmentTexture = environmentTexture;
  98344. };
  98345. /**
  98346. * Setup the background according to the specified options.
  98347. */
  98348. EnvironmentHelper.prototype._setupBackground = function () {
  98349. if (!this._rootMesh) {
  98350. this._rootMesh = new BABYLON.Mesh("BackgroundHelper", this._scene);
  98351. }
  98352. this._rootMesh.rotation.y = this._options.backgroundYRotation;
  98353. var sceneSize = this._getSceneSize();
  98354. if (this._options.createGround) {
  98355. this._setupGround(sceneSize);
  98356. this._setupGroundMaterial();
  98357. this._setupGroundDiffuseTexture();
  98358. if (this._options.enableGroundMirror) {
  98359. this._setupGroundMirrorTexture(sceneSize);
  98360. }
  98361. this._setupMirrorInGroundMaterial();
  98362. }
  98363. if (this._options.createSkybox) {
  98364. this._setupSkybox(sceneSize);
  98365. this._setupSkyboxMaterial();
  98366. this._setupSkyboxReflectionTexture();
  98367. }
  98368. this._rootMesh.position.x = sceneSize.rootPosition.x;
  98369. this._rootMesh.position.z = sceneSize.rootPosition.z;
  98370. this._rootMesh.position.y = sceneSize.rootPosition.y;
  98371. };
  98372. /**
  98373. * Get the scene sizes according to the setup.
  98374. */
  98375. EnvironmentHelper.prototype._getSceneSize = function () {
  98376. var _this = this;
  98377. var groundSize = this._options.groundSize;
  98378. var skyboxSize = this._options.skyboxSize;
  98379. var rootPosition = this._options.rootPosition;
  98380. if (!this._scene.meshes || this._scene.meshes.length === 1) { // 1 only means the root of the helper.
  98381. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  98382. }
  98383. var sceneExtends = this._scene.getWorldExtends(function (mesh) {
  98384. return (mesh !== _this._ground && mesh !== _this._rootMesh && mesh !== _this._skybox);
  98385. });
  98386. var sceneDiagonal = sceneExtends.max.subtract(sceneExtends.min);
  98387. if (this._options.sizeAuto) {
  98388. if (this._scene.activeCamera instanceof BABYLON.ArcRotateCamera &&
  98389. this._scene.activeCamera.upperRadiusLimit) {
  98390. groundSize = this._scene.activeCamera.upperRadiusLimit * 2;
  98391. skyboxSize = groundSize;
  98392. }
  98393. var sceneDiagonalLenght = sceneDiagonal.length();
  98394. if (sceneDiagonalLenght > groundSize) {
  98395. groundSize = sceneDiagonalLenght * 2;
  98396. skyboxSize = groundSize;
  98397. }
  98398. // 10 % bigger.
  98399. groundSize *= 1.1;
  98400. skyboxSize *= 1.5;
  98401. rootPosition = sceneExtends.min.add(sceneDiagonal.scale(0.5));
  98402. rootPosition.y = sceneExtends.min.y - this._options.groundYBias;
  98403. }
  98404. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  98405. };
  98406. /**
  98407. * Setup the ground according to the specified options.
  98408. */
  98409. EnvironmentHelper.prototype._setupGround = function (sceneSize) {
  98410. var _this = this;
  98411. if (!this._ground) {
  98412. this._ground = BABYLON.Mesh.CreatePlane("BackgroundPlane", sceneSize.groundSize, this._scene);
  98413. this._ground.rotation.x = Math.PI / 2; // Face up by default.
  98414. this._ground.parent = this._rootMesh;
  98415. this._ground.onDisposeObservable.add(function () { _this._ground = null; });
  98416. }
  98417. this._ground.receiveShadows = this._options.enableGroundShadow;
  98418. };
  98419. /**
  98420. * Setup the ground material according to the specified options.
  98421. */
  98422. EnvironmentHelper.prototype._setupGroundMaterial = function () {
  98423. if (!this._groundMaterial) {
  98424. this._groundMaterial = new BABYLON.BackgroundMaterial("BackgroundPlaneMaterial", this._scene);
  98425. }
  98426. this._groundMaterial.alpha = this._options.groundOpacity;
  98427. this._groundMaterial.alphaMode = BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF;
  98428. this._groundMaterial.shadowLevel = this._options.groundShadowLevel;
  98429. this._groundMaterial.primaryColor = this._options.groundColor;
  98430. this._groundMaterial.useRGBColor = false;
  98431. this._groundMaterial.enableNoise = true;
  98432. if (this._ground) {
  98433. this._ground.material = this._groundMaterial;
  98434. }
  98435. };
  98436. /**
  98437. * Setup the ground diffuse texture according to the specified options.
  98438. */
  98439. EnvironmentHelper.prototype._setupGroundDiffuseTexture = function () {
  98440. if (!this._groundMaterial) {
  98441. return;
  98442. }
  98443. if (this._groundTexture) {
  98444. return;
  98445. }
  98446. if (this._options.groundTexture instanceof BABYLON.BaseTexture) {
  98447. this._groundMaterial.diffuseTexture = this._options.groundTexture;
  98448. return;
  98449. }
  98450. var diffuseTexture = new BABYLON.Texture(this._options.groundTexture, this._scene, undefined, undefined, undefined, undefined, this._errorHandler);
  98451. diffuseTexture.gammaSpace = false;
  98452. diffuseTexture.hasAlpha = true;
  98453. this._groundMaterial.diffuseTexture = diffuseTexture;
  98454. };
  98455. /**
  98456. * Setup the ground mirror texture according to the specified options.
  98457. */
  98458. EnvironmentHelper.prototype._setupGroundMirrorTexture = function (sceneSize) {
  98459. var wrapping = BABYLON.Texture.CLAMP_ADDRESSMODE;
  98460. if (!this._groundMirror) {
  98461. this._groundMirror = new BABYLON.MirrorTexture("BackgroundPlaneMirrorTexture", { ratio: this._options.groundMirrorSizeRatio }, this._scene, false, this._options.groundMirrorTextureType, BABYLON.Texture.BILINEAR_SAMPLINGMODE, true);
  98462. this._groundMirror.mirrorPlane = new BABYLON.Plane(0, -1, 0, sceneSize.rootPosition.y);
  98463. this._groundMirror.anisotropicFilteringLevel = 1;
  98464. this._groundMirror.wrapU = wrapping;
  98465. this._groundMirror.wrapV = wrapping;
  98466. this._groundMirror.gammaSpace = false;
  98467. if (this._groundMirror.renderList) {
  98468. for (var i = 0; i < this._scene.meshes.length; i++) {
  98469. var mesh = this._scene.meshes[i];
  98470. if (mesh !== this._ground &&
  98471. mesh !== this._skybox &&
  98472. mesh !== this._rootMesh) {
  98473. this._groundMirror.renderList.push(mesh);
  98474. }
  98475. }
  98476. }
  98477. }
  98478. this._groundMirror.clearColor = new BABYLON.Color4(this._options.groundColor.r, this._options.groundColor.g, this._options.groundColor.b, 1);
  98479. this._groundMirror.adaptiveBlurKernel = this._options.groundMirrorBlurKernel;
  98480. };
  98481. /**
  98482. * Setup the ground to receive the mirror texture.
  98483. */
  98484. EnvironmentHelper.prototype._setupMirrorInGroundMaterial = function () {
  98485. if (this._groundMaterial) {
  98486. this._groundMaterial.reflectionTexture = this._groundMirror;
  98487. this._groundMaterial.reflectionFresnel = true;
  98488. this._groundMaterial.reflectionAmount = this._options.groundMirrorAmount;
  98489. this._groundMaterial.reflectionStandardFresnelWeight = this._options.groundMirrorFresnelWeight;
  98490. this._groundMaterial.reflectionFalloffDistance = this._options.groundMirrorFallOffDistance;
  98491. }
  98492. };
  98493. /**
  98494. * Setup the skybox according to the specified options.
  98495. */
  98496. EnvironmentHelper.prototype._setupSkybox = function (sceneSize) {
  98497. var _this = this;
  98498. if (!this._skybox) {
  98499. this._skybox = BABYLON.Mesh.CreateBox("BackgroundSkybox", sceneSize.skyboxSize, this._scene, undefined, BABYLON.Mesh.BACKSIDE);
  98500. this._skybox.onDisposeObservable.add(function () { _this._skybox = null; });
  98501. }
  98502. this._skybox.parent = this._rootMesh;
  98503. };
  98504. /**
  98505. * Setup the skybox material according to the specified options.
  98506. */
  98507. EnvironmentHelper.prototype._setupSkyboxMaterial = function () {
  98508. if (!this._skybox) {
  98509. return;
  98510. }
  98511. if (!this._skyboxMaterial) {
  98512. this._skyboxMaterial = new BABYLON.BackgroundMaterial("BackgroundSkyboxMaterial", this._scene);
  98513. }
  98514. this._skyboxMaterial.useRGBColor = false;
  98515. this._skyboxMaterial.primaryColor = this._options.skyboxColor;
  98516. this._skyboxMaterial.enableNoise = true;
  98517. this._skybox.material = this._skyboxMaterial;
  98518. };
  98519. /**
  98520. * Setup the skybox reflection texture according to the specified options.
  98521. */
  98522. EnvironmentHelper.prototype._setupSkyboxReflectionTexture = function () {
  98523. if (!this._skyboxMaterial) {
  98524. return;
  98525. }
  98526. if (this._skyboxTexture) {
  98527. return;
  98528. }
  98529. if (this._options.skyboxTexture instanceof BABYLON.BaseTexture) {
  98530. this._skyboxMaterial.reflectionTexture = this._options.skyboxTexture;
  98531. return;
  98532. }
  98533. this._skyboxTexture = new BABYLON.CubeTexture(this._options.skyboxTexture, this._scene, undefined, undefined, undefined, undefined, this._errorHandler);
  98534. this._skyboxTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  98535. this._skyboxTexture.gammaSpace = false;
  98536. this._skyboxMaterial.reflectionTexture = this._skyboxTexture;
  98537. };
  98538. /**
  98539. * Dispose all the elements created by the Helper.
  98540. */
  98541. EnvironmentHelper.prototype.dispose = function () {
  98542. if (this._groundMaterial) {
  98543. this._groundMaterial.dispose(true, true);
  98544. }
  98545. if (this._skyboxMaterial) {
  98546. this._skyboxMaterial.dispose(true, true);
  98547. }
  98548. this._rootMesh.dispose(false);
  98549. };
  98550. /**
  98551. * Default ground texture URL.
  98552. */
  98553. EnvironmentHelper._groundTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundGround.png";
  98554. /**
  98555. * Default skybox texture URL.
  98556. */
  98557. EnvironmentHelper._skyboxTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundSkybox.dds";
  98558. /**
  98559. * Default environment texture URL.
  98560. */
  98561. EnvironmentHelper._environmentTextureCDNUrl = "https://assets.babylonjs.com/environments/environmentSpecular.dds";
  98562. return EnvironmentHelper;
  98563. }());
  98564. BABYLON.EnvironmentHelper = EnvironmentHelper;
  98565. })(BABYLON || (BABYLON = {}));
  98566. //# sourceMappingURL=babylon.environmentHelper.js.map
  98567. var BABYLON;
  98568. (function (BABYLON) {
  98569. /**
  98570. * This class is made for on one-liner static method to help creating particle systems.
  98571. */
  98572. var ParticleHelper = /** @class */ (function () {
  98573. function ParticleHelper() {
  98574. }
  98575. /**
  98576. * This is the main static method (one-liner) of this helper to create different particle systems.
  98577. * @param type This string represents the type to the particle system to create
  98578. * @param emitter The object where the particle system will start to emit from.
  98579. * @param scene The scene where the particle system should live.
  98580. * @param gpu If the system will use gpu.
  98581. * @returns the ParticleSystem created.
  98582. */
  98583. ParticleHelper.CreateAsync = function (type, emitter, scene, gpu) {
  98584. var _this = this;
  98585. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  98586. if (gpu === void 0) { gpu = false; }
  98587. return new Promise(function (resolve, reject) {
  98588. if (scene) {
  98589. _this._scene = scene;
  98590. }
  98591. else {
  98592. return reject("A particle system need a scene.");
  98593. }
  98594. if (gpu && !BABYLON.GPUParticleSystem.IsSupported) {
  98595. return reject("Particle system with GPU is not supported.");
  98596. }
  98597. _this._emitter = emitter;
  98598. BABYLON.Tools.LoadFile(_this._baseAssetsUrl + "/systems/" + type + ".json", function (data, response) {
  98599. var newData = JSON.parse(data.toString());
  98600. return resolve(_this._createSystem(newData));
  98601. }, undefined, undefined, undefined, function (req, exception) {
  98602. return reject("An error occured while the creation of your particle system. Check if your type '" + type + "' exists.");
  98603. });
  98604. });
  98605. };
  98606. ParticleHelper._createSystem = function (data) {
  98607. // Create a particle system
  98608. var system = new BABYLON.ParticleSystem(data.type, data.capacity, this._scene);
  98609. // Texture of each particle
  98610. system.particleTexture = new BABYLON.Texture(this._baseAssetsUrl + "/textures/" + data.textureFile, this._scene);
  98611. // Where the particles come from
  98612. system.emitter = this._emitter; // the starting object, the emitter
  98613. // Colors of all particles
  98614. system.color1 = new BABYLON.Color4(data.color1.r, data.color1.g, data.color1.b, data.color1.a);
  98615. system.color2 = new BABYLON.Color4(data.color2.r, data.color2.g, data.color2.b, data.color2.a);
  98616. system.colorDead = new BABYLON.Color4(data.colorDead.r, data.colorDead.g, data.colorDead.b, data.colorDead.a);
  98617. // Size of each particle (random between...
  98618. system.minSize = data.minSize;
  98619. system.maxSize = data.maxSize;
  98620. // Life time of each particle (random between...
  98621. system.minLifeTime = data.minLifeTime;
  98622. system.maxLifeTime = data.maxLifeTime;
  98623. // Emission rate
  98624. system.emitRate = data.emitRate;
  98625. // Blend mode : BLENDMODE_ONEONE, or BLENDMODE_STANDARD
  98626. system.blendMode = data.blendMode;
  98627. // Set the gravity of all particles
  98628. system.gravity = new BABYLON.Vector3(data.gravity.x, data.gravity.y, data.gravity.z);
  98629. // Angular speed, in radians
  98630. system.minAngularSpeed = data.minAngularSpeed;
  98631. system.maxAngularSpeed = data.maxAngularSpeed;
  98632. // Speed
  98633. system.minEmitPower = data.minEmitPower;
  98634. system.maxEmitPower = data.maxEmitPower;
  98635. system.updateSpeed = data.updateSpeed;
  98636. switch (data.emitterType) {
  98637. case "box":
  98638. if (!data.direction1 || !data.direction2) {
  98639. throw new Error("Directions are missing in this particle system.");
  98640. }
  98641. if (!data.minEmitBox || !data.maxEmitBox) {
  98642. throw new Error("EmitBox is missing in this particle system.");
  98643. }
  98644. system.createBoxEmitter(new BABYLON.Vector3(data.direction1.x, data.direction1.y, data.direction1.z), new BABYLON.Vector3(data.direction2.x, data.direction2.y, data.direction2.z), new BABYLON.Vector3(data.minEmitBox.x, data.minEmitBox.y, data.minEmitBox.z), new BABYLON.Vector3(data.maxEmitBox.x, data.maxEmitBox.y, data.maxEmitBox.z));
  98645. break;
  98646. case "sphere":
  98647. system.createSphereEmitter(data.radius);
  98648. break;
  98649. case "directed_sphere":
  98650. if (!data.direction1 || !data.direction2) {
  98651. throw new Error("Directions are missing in this particle system.");
  98652. }
  98653. system.createDirectedSphereEmitter(data.radius, new BABYLON.Vector3(data.direction1.x, data.direction1.y, data.direction1.z), new BABYLON.Vector3(data.direction2.x, data.direction2.y, data.direction2.z));
  98654. break;
  98655. case "cone":
  98656. system.createConeEmitter(data.radius, data.angle);
  98657. break;
  98658. default:
  98659. break;
  98660. }
  98661. return system;
  98662. };
  98663. /**
  98664. * Base Assets URL.
  98665. */
  98666. ParticleHelper._baseAssetsUrl = "https://assets.babylonjs.com/particles";
  98667. return ParticleHelper;
  98668. }());
  98669. BABYLON.ParticleHelper = ParticleHelper;
  98670. })(BABYLON || (BABYLON = {}));
  98671. //# sourceMappingURL=babylon.particleHelper.js.map
  98672. var BABYLON;
  98673. (function (BABYLON) {
  98674. /**
  98675. * Display a 360 degree video on an approximately spherical surface, useful for VR applications or skyboxes.
  98676. * As a subclass of Node, this allow parenting to the camera or multiple videos with different locations in the scene.
  98677. * This class achieves its effect with a VideoTexture and a correctly configured BackgroundMaterial on an inverted sphere.
  98678. * Potential additions to this helper include zoom and and non-infinite distance rendering effects.
  98679. */
  98680. var VideoDome = /** @class */ (function (_super) {
  98681. __extends(VideoDome, _super);
  98682. /**
  98683. * Create an instance of this class and pass through the parameters to the relevant classes, VideoTexture, StandardMaterial, and Mesh.
  98684. * @param name Element's name, child elements will append suffixes for their own names.
  98685. * @param urlsOrVideo
  98686. * @param options An object containing optional or exposed sub element properties:
  98687. * @param options **resolution=12** Integer, lower resolutions have more artifacts at extreme fovs
  98688. * @param options **clickToPlay=false** Add a click to play listener to the video, does not prevent autoplay.
  98689. * @param options **autoPlay=true** Automatically attempt to being playing the video.
  98690. * @param options **loop=true** Automatically loop video on end.
  98691. * @param options **size=1000** Physical radius to create the dome at, defaults to approximately half the far clip plane.
  98692. */
  98693. function VideoDome(name, urlsOrVideo, options, scene) {
  98694. var _this = _super.call(this, name, scene) || this;
  98695. // set defaults and manage values
  98696. name = name || "videoDome";
  98697. options.resolution = (Math.abs(options.resolution) | 0) || 12;
  98698. options.clickToPlay = Boolean(options.clickToPlay);
  98699. options.autoPlay = options.autoPlay === undefined ? true : Boolean(options.autoPlay);
  98700. options.loop = options.loop === undefined ? true : Boolean(options.loop);
  98701. options.size = Math.abs(options.size) || (scene.activeCamera ? scene.activeCamera.maxZ * 0.48 : 1000);
  98702. // create
  98703. var tempOptions = { loop: options.loop, autoPlay: options.autoPlay, autoUpdateTexture: true };
  98704. var material = _this._material = new BABYLON.BackgroundMaterial(name + "_material", scene);
  98705. var texture = _this._videoTexture = new BABYLON.VideoTexture(name + "_texture", urlsOrVideo, scene, false, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, tempOptions);
  98706. _this._mesh = BABYLON.MeshBuilder.CreateIcoSphere(name + "_mesh", {
  98707. flat: false,
  98708. radius: options.size,
  98709. subdivisions: options.resolution,
  98710. sideOrientation: BABYLON.Mesh.BACKSIDE // needs to be inside out
  98711. }, scene);
  98712. // configure material
  98713. texture.coordinatesMode = BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE; // matches orientation
  98714. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE; // always clamp the up/down
  98715. material.reflectionTexture = _this._videoTexture;
  98716. material.useEquirectangularFOV = true;
  98717. material.fovMultiplier = 1.0;
  98718. // configure mesh
  98719. _this._mesh.material = material;
  98720. _this._mesh.parent = _this;
  98721. // optional configuration
  98722. if (options.clickToPlay) {
  98723. scene.onPointerUp = function () {
  98724. _this._videoTexture.video.play();
  98725. };
  98726. }
  98727. return _this;
  98728. }
  98729. Object.defineProperty(VideoDome.prototype, "fovMultiplier", {
  98730. /**
  98731. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  98732. * Also see the options.resolution property.
  98733. */
  98734. get: function () {
  98735. return this._material.fovMultiplier;
  98736. },
  98737. set: function (value) {
  98738. this._material.fovMultiplier = value;
  98739. },
  98740. enumerable: true,
  98741. configurable: true
  98742. });
  98743. /**
  98744. * Releases resources associated with this node.
  98745. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  98746. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  98747. */
  98748. VideoDome.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  98749. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  98750. this._videoTexture.dispose();
  98751. this._mesh.dispose();
  98752. this._material.dispose();
  98753. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  98754. };
  98755. return VideoDome;
  98756. }(BABYLON.Node));
  98757. BABYLON.VideoDome = VideoDome;
  98758. })(BABYLON || (BABYLON = {}));
  98759. //# sourceMappingURL=babylon.videoDome.js.map
  98760. BABYLON.Effect.ShadersStore={"defaultVertexShader":"#include<__decl__defaultVertex>\n\n#define CUSTOM_VERTEX_BEGIN\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef TANGENT\nattribute vec4 tangent;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<helperFunctions>\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0\nvarying vec2 vDiffuseUV;\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\nvarying vec2 vAmbientUV;\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0\nvarying vec2 vOpacityUV;\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\nvarying vec2 vEmissiveUV;\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\nvarying vec2 vLightmapUV;\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM) && SPECULARDIRECTUV == 0\nvarying vec2 vSpecularUV;\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0\nvarying vec2 vBumpUV;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<bumpVertexDeclaration>\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#include<logDepthDeclaration>\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_VERTEX_MAIN_BEGIN\nvec3 positionUpdated=position;\n#ifdef NORMAL \nvec3 normalUpdated=normal;\n#endif\n#ifdef TANGENT\nvec4 tangentUpdated=tangent;\n#endif\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=positionUpdated;\n#endif \n#define CUSTOM_VERTEX_UPDATE_POSITION\n#define CUSTOM_VERTEX_UPDATE_NORMAL\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(positionUpdated,1.0);\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvNormalW=normalize(normalWorld*normalUpdated);\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(positionUpdated,0.0)));\n#endif\n\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef MAINUV1\nvMainUV1=uv;\n#endif\n#ifdef MAINUV2\nvMainUV2=uv2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0\nif (vDiffuseInfos.x == 0.)\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\nif (vAmbientInfos.x == 0.)\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0\nif (vOpacityInfos.x == 0.)\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\nif (vEmissiveInfos.x == 0.)\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\nif (vLightmapInfos.x == 0.)\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM) && SPECULARDIRECTUV == 0\nif (vSpecularInfos.x == 0.)\n{\nvSpecularUV=vec2(specularMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvSpecularUV=vec2(specularMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0\nif (vBumpInfos.x == 0.)\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#include<bumpVertex>\n#include<clipPlaneVertex>\n#include<fogVertex>\n#include<shadowsVertex>[0..maxSimultaneousLights]\n#ifdef VERTEXCOLOR\n\nvColor=color;\n#endif\n#include<pointCloudVertex>\n#include<logDepthVertex>\n#define CUSTOM_VERTEX_MAIN_END\n}\n","defaultPixelShader":"#include<__decl__defaultFragment>\n#if defined(BUMP) || !defined(NORMAL)\n#extension GL_OES_standard_derivatives : enable\n#endif\n#define CUSTOM_FRAGMENT_BEGIN\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\n\n#define RECIPROCAL_PI2 0.15915494\nuniform vec3 vEyePosition;\nuniform vec3 vAmbientColor;\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2;\n#endif\n\n#include<helperFunctions>\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<lightsFragmentFunctions>\n#include<shadowsFragmentFunctions>\n\n#ifdef DIFFUSE\n#if DIFFUSEDIRECTUV == 1\n#define vDiffuseUV vMainUV1\n#elif DIFFUSEDIRECTUV == 2\n#define vDiffuseUV vMainUV2\n#else\nvarying vec2 vDiffuseUV;\n#endif\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef AMBIENT\n#if AMBIENTDIRECTUV == 1\n#define vAmbientUV vMainUV1\n#elif AMBIENTDIRECTUV == 2\n#define vAmbientUV vMainUV2\n#else\nvarying vec2 vAmbientUV;\n#endif\nuniform sampler2D ambientSampler;\n#endif\n#ifdef OPACITY \n#if OPACITYDIRECTUV == 1\n#define vOpacityUV vMainUV1\n#elif OPACITYDIRECTUV == 2\n#define vOpacityUV vMainUV2\n#else\nvarying vec2 vOpacityUV;\n#endif\nuniform sampler2D opacitySampler;\n#endif\n#ifdef EMISSIVE\n#if EMISSIVEDIRECTUV == 1\n#define vEmissiveUV vMainUV1\n#elif EMISSIVEDIRECTUV == 2\n#define vEmissiveUV vMainUV2\n#else\nvarying vec2 vEmissiveUV;\n#endif\nuniform sampler2D emissiveSampler;\n#endif\n#ifdef LIGHTMAP\n#if LIGHTMAPDIRECTUV == 1\n#define vLightmapUV vMainUV1\n#elif LIGHTMAPDIRECTUV == 2\n#define vLightmapUV vMainUV2\n#else\nvarying vec2 vLightmapUV;\n#endif\nuniform sampler2D lightmapSampler;\n#endif\n#ifdef REFRACTION\n#ifdef REFRACTIONMAP_3D\nuniform samplerCube refractionCubeSampler;\n#else\nuniform sampler2D refraction2DSampler;\n#endif\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\n#if SPECULARDIRECTUV == 1\n#define vSpecularUV vMainUV1\n#elif SPECULARDIRECTUV == 2\n#define vSpecularUV vMainUV2\n#else\nvarying vec2 vSpecularUV;\n#endif\nuniform sampler2D specularSampler;\n#endif\n#ifdef ALPHATEST\nuniform float alphaCutOff;\n#endif\n\n#include<fresnelFunction>\n\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\nuniform samplerCube reflectionCubeSampler;\n#else\nuniform sampler2D reflection2DSampler;\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n#include<imageProcessingDeclaration>\n#include<imageProcessingFunctions>\n#include<bumpFragmentFunctions>\n#include<clipPlaneFragmentDeclaration>\n#include<logDepthDeclaration>\n#include<fogFragmentDeclaration>\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_FRAGMENT_MAIN_BEGIN\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\nvec4 baseColor=vec4(1.,1.,1.,1.);\nvec3 diffuseColor=vDiffuseColor.rgb;\n\nfloat alpha=vDiffuseColor.a;\n\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=normalize(-cross(dFdx(vPositionW),dFdy(vPositionW)));\n#endif\n#include<bumpFragment>\n#ifdef TWOSIDEDLIGHTING\nnormalW=gl_FrontFacing ? normalW : -normalW;\n#endif\n#ifdef DIFFUSE\nbaseColor=texture2D(diffuseSampler,vDiffuseUV+uvOffset);\n#ifdef ALPHATEST\nif (baseColor.a<alphaCutOff)\ndiscard;\n#endif\n#ifdef ALPHAFROMDIFFUSE\nalpha*=baseColor.a;\n#endif\n#define CUSTOM_FRAGMENT_UPDATE_ALPHA\nbaseColor.rgb*=vDiffuseInfos.y;\n#endif\n#include<depthPrePass>\n#ifdef VERTEXCOLOR\nbaseColor.rgb*=vColor.rgb;\n#endif\n#define CUSTOM_FRAGMENT_UPDATE_DIFFUSE\n\nvec3 baseAmbientColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nbaseAmbientColor=texture2D(ambientSampler,vAmbientUV+uvOffset).rgb*vAmbientInfos.y;\n#endif\n#define CUSTOM_FRAGMENT_BEFORE_LIGHTS\n\n#ifdef SPECULARTERM\nfloat glossiness=vSpecularColor.a;\nvec3 specularColor=vSpecularColor.rgb;\n#ifdef SPECULAR\nvec4 specularMapColor=texture2D(specularSampler,vSpecularUV+uvOffset);\nspecularColor=specularMapColor.rgb;\n#ifdef GLOSSINESS\nglossiness=glossiness*specularMapColor.a;\n#endif\n#endif\n#else\nfloat glossiness=0.;\n#endif\n\nvec3 diffuseBase=vec3(0.,0.,0.);\nlightingInfo info;\n#ifdef SPECULARTERM\nvec3 specularBase=vec3(0.,0.,0.);\n#endif\nfloat shadow=1.;\n#ifdef LIGHTMAP\nvec3 lightmapColor=texture2D(lightmapSampler,vLightmapUV+uvOffset).rgb*vLightmapInfos.y;\n#endif\n#include<lightFragment>[0..maxSimultaneousLights]\n\nvec3 refractionColor=vec3(0.,0.,0.);\n#ifdef REFRACTION\nvec3 refractionVector=normalize(refract(-viewDirectionW,normalW,vRefractionInfos.y));\n#ifdef REFRACTIONMAP_3D\nrefractionVector.y=refractionVector.y*vRefractionInfos.w;\nif (dot(refractionVector,viewDirectionW)<1.0) {\nrefractionColor=textureCube(refractionCubeSampler,refractionVector).rgb;\n}\n#else\nvec3 vRefractionUVW=vec3(refractionMatrix*(view*vec4(vPositionW+refractionVector*vRefractionInfos.z,1.0)));\nvec2 refractionCoords=vRefractionUVW.xy/vRefractionUVW.z;\nrefractionCoords.y=1.0-refractionCoords.y;\nrefractionColor=texture2D(refraction2DSampler,refractionCoords).rgb;\n#endif\n#ifdef IS_REFRACTION_LINEAR\nrefractionColor=toGammaSpace(refractionColor);\n#endif\nrefractionColor*=vRefractionInfos.x;\n#endif\n\nvec3 reflectionColor=vec3(0.,0.,0.);\n#ifdef REFLECTION\nvec3 vReflectionUVW=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_3D\n#ifdef ROUGHNESS\nfloat bias=vReflectionInfos.y;\n#ifdef SPECULARTERM\n#ifdef SPECULAR\n#ifdef GLOSSINESS\nbias*=(1.0-specularMapColor.a);\n#endif\n#endif\n#endif\nreflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW,bias).rgb;\n#else\nreflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW).rgb;\n#endif\n#else\nvec2 coords=vReflectionUVW.xy;\n#ifdef REFLECTIONMAP_PROJECTION\ncoords/=vReflectionUVW.z;\n#endif\ncoords.y=1.0-coords.y;\nreflectionColor=texture2D(reflection2DSampler,coords).rgb;\n#endif\n#ifdef IS_REFLECTION_LINEAR\nreflectionColor=toGammaSpace(reflectionColor);\n#endif\nreflectionColor*=vReflectionInfos.x;\n#ifdef REFLECTIONFRESNEL\nfloat reflectionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,reflectionRightColor.a,reflectionLeftColor.a);\n#ifdef REFLECTIONFRESNELFROMSPECULAR\n#ifdef SPECULARTERM\nreflectionColor*=specularColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#else\nreflectionColor*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#endif\n#else\nreflectionColor*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#endif\n#endif\n#endif\n#ifdef REFRACTIONFRESNEL\nfloat refractionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,refractionRightColor.a,refractionLeftColor.a);\nrefractionColor*=refractionLeftColor.rgb*(1.0-refractionFresnelTerm)+refractionFresnelTerm*refractionRightColor.rgb;\n#endif\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV+uvOffset);\n#ifdef OPACITYRGB\nopacityMap.rgb=opacityMap.rgb*vec3(0.3,0.59,0.11);\nalpha*=(opacityMap.x+opacityMap.y+opacityMap.z)* vOpacityInfos.y;\n#else\nalpha*=opacityMap.a*vOpacityInfos.y;\n#endif\n#endif\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\n#ifdef OPACITYFRESNEL\nfloat opacityFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,opacityParts.z,opacityParts.w);\nalpha+=opacityParts.x*(1.0-opacityFresnelTerm)+opacityFresnelTerm*opacityParts.y;\n#endif\n\nvec3 emissiveColor=vEmissiveColor;\n#ifdef EMISSIVE\nemissiveColor+=texture2D(emissiveSampler,vEmissiveUV+uvOffset).rgb*vEmissiveInfos.y;\n#endif\n#ifdef EMISSIVEFRESNEL\nfloat emissiveFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,emissiveRightColor.a,emissiveLeftColor.a);\nemissiveColor*=emissiveLeftColor.rgb*(1.0-emissiveFresnelTerm)+emissiveFresnelTerm*emissiveRightColor.rgb;\n#endif\n\n#ifdef DIFFUSEFRESNEL\nfloat diffuseFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,diffuseRightColor.a,diffuseLeftColor.a);\ndiffuseBase*=diffuseLeftColor.rgb*(1.0-diffuseFresnelTerm)+diffuseFresnelTerm*diffuseRightColor.rgb;\n#endif\n\n#ifdef EMISSIVEASILLUMINATION\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#else\n#ifdef LINKEMISSIVEWITHDIFFUSE\nvec3 finalDiffuse=clamp((diffuseBase+emissiveColor)*diffuseColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#else\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor+emissiveColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#endif\n#endif\n#ifdef SPECULARTERM\nvec3 finalSpecular=specularBase*specularColor;\n#ifdef SPECULAROVERALPHA\nalpha=clamp(alpha+dot(finalSpecular,vec3(0.3,0.59,0.11)),0.,1.);\n#endif\n#else\nvec3 finalSpecular=vec3(0.0);\n#endif\n#ifdef REFLECTIONOVERALPHA\nalpha=clamp(alpha+dot(reflectionColor,vec3(0.3,0.59,0.11)),0.,1.);\n#endif\n\n#ifdef EMISSIVEASILLUMINATION\nvec4 color=vec4(clamp(finalDiffuse*baseAmbientColor+finalSpecular+reflectionColor+emissiveColor+refractionColor,0.0,1.0),alpha);\n#else\nvec4 color=vec4(finalDiffuse*baseAmbientColor+finalSpecular+reflectionColor+refractionColor,alpha);\n#endif\n\n#ifdef LIGHTMAP\n#ifndef LIGHTMAPEXCLUDED\n#ifdef USELIGHTMAPASSHADOWMAP\ncolor.rgb*=lightmapColor;\n#else\ncolor.rgb+=lightmapColor;\n#endif\n#endif\n#endif\n#define CUSTOM_FRAGMENT_BEFORE_FOG\ncolor.rgb=max(color.rgb,0.);\n#include<logDepthFragment>\n#include<fogFragment>\n\n\n#ifdef IMAGEPROCESSINGPOSTPROCESS\ncolor.rgb=toLinearSpace(color.rgb);\n#else\n#ifdef IMAGEPROCESSING\ncolor.rgb=toLinearSpace(color.rgb);\ncolor=applyImageProcessing(color);\n#endif\n#endif\n#ifdef PREMULTIPLYALPHA\n\ncolor.rgb*=color.a;\n#endif\n#define CUSTOM_FRAGMENT_BEFORE_FRAGCOLOR\ngl_FragColor=color;\n}\n","pbrVertexShader":"precision highp float;\n#include<__decl__pbrVertex>\n\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef TANGENT\nattribute vec4 tangent;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2; \n#endif \n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<helperFunctions>\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\n#if defined(ALBEDO) && ALBEDODIRECTUV == 0\nvarying vec2 vAlbedoUV;\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\nvarying vec2 vAmbientUV;\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0\nvarying vec2 vOpacityUV;\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\nvarying vec2 vEmissiveUV;\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\nvarying vec2 vLightmapUV;\n#endif\n#if defined(REFLECTIVITY) && REFLECTIVITYDIRECTUV == 0\nvarying vec2 vReflectivityUV;\n#endif\n#if defined(MICROSURFACEMAP) && MICROSURFACEMAPDIRECTUV == 0\nvarying vec2 vMicroSurfaceSamplerUV;\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0\nvarying vec2 vBumpUV;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\nvarying vec3 vEnvironmentIrradiance;\n#include<harmonicsFunctions>\n#endif\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<bumpVertexDeclaration>\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#include<logDepthDeclaration>\nvoid main(void) {\nvec3 positionUpdated=position;\n#ifdef NORMAL\nvec3 normalUpdated=normal;\n#endif\n#ifdef TANGENT\nvec4 tangentUpdated=tangent;\n#endif\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=positionUpdated;\n#endif \n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(positionUpdated,1.0);\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvNormalW=normalize(normalWorld*normalUpdated);\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\nvec3 reflectionVector=vec3(reflectionMatrix*vec4(vNormalW,0)).xyz;\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflectionVector.z*=-1.0;\n#endif\nvEnvironmentIrradiance=environmentIrradianceJones(reflectionVector);\n#endif\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(positionUpdated,0.0)));\n#endif\n\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef MAINUV1\nvMainUV1=uv;\n#endif \n#ifdef MAINUV2\nvMainUV2=uv2;\n#endif \n#if defined(ALBEDO) && ALBEDODIRECTUV == 0 \nif (vAlbedoInfos.x == 0.)\n{\nvAlbedoUV=vec2(albedoMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAlbedoUV=vec2(albedoMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0 \nif (vAmbientInfos.x == 0.)\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0 \nif (vOpacityInfos.x == 0.)\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0 \nif (vEmissiveInfos.x == 0.)\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0 \nif (vLightmapInfos.x == 0.)\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(REFLECTIVITY) && REFLECTIVITYDIRECTUV == 0 \nif (vReflectivityInfos.x == 0.)\n{\nvReflectivityUV=vec2(reflectivityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvReflectivityUV=vec2(reflectivityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(MICROSURFACEMAP) && MICROSURFACEMAPDIRECTUV == 0 \nif (vMicroSurfaceSamplerInfos.x == 0.)\n{\nvMicroSurfaceSamplerUV=vec2(microSurfaceSamplerMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvMicroSurfaceSamplerUV=vec2(microSurfaceSamplerMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0 \nif (vBumpInfos.x == 0.)\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n\n#include<bumpVertex>\n\n#include<clipPlaneVertex>\n\n#include<fogVertex>\n\n#include<shadowsVertex>[0..maxSimultaneousLights]\n\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n\n#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif\n\n#include<logDepthVertex>\n}","pbrPixelShader":"#if defined(BUMP) || !defined(NORMAL) || defined(FORCENORMALFORWARD) || defined(SPECULARAA)\n#extension GL_OES_standard_derivatives : enable\n#endif\n#ifdef LODBASEDMICROSFURACE\n#extension GL_EXT_shader_texture_lod : enable\n#endif\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\nprecision highp float;\n#include<__decl__pbrFragment>\nuniform vec4 vEyePosition;\nuniform vec3 vAmbientColor;\nuniform vec4 vCameraInfos;\n\nvarying vec3 vPositionW;\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif \n#ifdef MAINUV2 \nvarying vec2 vMainUV2;\n#endif \n#ifdef NORMAL\nvarying vec3 vNormalW;\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\nvarying vec3 vEnvironmentIrradiance;\n#endif\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n\n#ifdef ALBEDO\n#if ALBEDODIRECTUV == 1\n#define vAlbedoUV vMainUV1\n#elif ALBEDODIRECTUV == 2\n#define vAlbedoUV vMainUV2\n#else\nvarying vec2 vAlbedoUV;\n#endif\nuniform sampler2D albedoSampler;\n#endif\n#ifdef AMBIENT\n#if AMBIENTDIRECTUV == 1\n#define vAmbientUV vMainUV1\n#elif AMBIENTDIRECTUV == 2\n#define vAmbientUV vMainUV2\n#else\nvarying vec2 vAmbientUV;\n#endif\nuniform sampler2D ambientSampler;\n#endif\n#ifdef OPACITY\n#if OPACITYDIRECTUV == 1\n#define vOpacityUV vMainUV1\n#elif OPACITYDIRECTUV == 2\n#define vOpacityUV vMainUV2\n#else\nvarying vec2 vOpacityUV;\n#endif\nuniform sampler2D opacitySampler;\n#endif\n#ifdef EMISSIVE\n#if EMISSIVEDIRECTUV == 1\n#define vEmissiveUV vMainUV1\n#elif EMISSIVEDIRECTUV == 2\n#define vEmissiveUV vMainUV2\n#else\nvarying vec2 vEmissiveUV;\n#endif\nuniform sampler2D emissiveSampler;\n#endif\n#ifdef LIGHTMAP\n#if LIGHTMAPDIRECTUV == 1\n#define vLightmapUV vMainUV1\n#elif LIGHTMAPDIRECTUV == 2\n#define vLightmapUV vMainUV2\n#else\nvarying vec2 vLightmapUV;\n#endif\nuniform sampler2D lightmapSampler;\n#endif\n#ifdef REFLECTIVITY\n#if REFLECTIVITYDIRECTUV == 1\n#define vReflectivityUV vMainUV1\n#elif REFLECTIVITYDIRECTUV == 2\n#define vReflectivityUV vMainUV2\n#else\nvarying vec2 vReflectivityUV;\n#endif\nuniform sampler2D reflectivitySampler;\n#endif\n#ifdef MICROSURFACEMAP\n#if MICROSURFACEMAPDIRECTUV == 1\n#define vMicroSurfaceSamplerUV vMainUV1\n#elif MICROSURFACEMAPDIRECTUV == 2\n#define vMicroSurfaceSamplerUV vMainUV2\n#else\nvarying vec2 vMicroSurfaceSamplerUV;\n#endif\nuniform sampler2D microSurfaceSampler;\n#endif\n\n#ifdef REFRACTION\n#ifdef REFRACTIONMAP_3D\n#define sampleRefraction(s,c) textureCube(s,c)\nuniform samplerCube refractionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleRefractionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube refractionSamplerLow;\nuniform samplerCube refractionSamplerHigh;\n#endif\n#else\n#define sampleRefraction(s,c) texture2D(s,c)\nuniform sampler2D refractionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleRefractionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform samplerCube refractionSamplerLow;\nuniform samplerCube refractionSamplerHigh;\n#endif\n#endif\n#endif\n\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\n#define sampleReflection(s,c) textureCube(s,c)\nuniform samplerCube reflectionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleReflectionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#else\n#define sampleReflection(s,c) texture2D(s,c)\nuniform sampler2D reflectionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleReflectionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n#ifdef ENVIRONMENTBRDF\nuniform sampler2D environmentBrdfSampler;\n#endif\n\n#ifndef FROMLINEARSPACE\n#define FROMLINEARSPACE;\n#endif\n#include<imageProcessingDeclaration>\n#include<helperFunctions>\n#include<imageProcessingFunctions>\n\n#include<shadowsFragmentFunctions>\n#include<pbrFunctions>\n#include<harmonicsFunctions>\n#include<pbrLightFunctions>\n#include<bumpFragmentFunctions>\n#include<clipPlaneFragmentDeclaration>\n#include<logDepthDeclaration>\n\n#include<fogFragmentDeclaration>\nvoid main(void) {\n#include<clipPlaneFragment>\n\n\nvec3 viewDirectionW=normalize(vEyePosition.xyz-vPositionW);\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=normalize(cross(dFdx(vPositionW),dFdy(vPositionW)))*vEyePosition.w;\n#endif\n#include<bumpFragment>\n#ifdef SPECULARAA\nvec3 nDfdx=dFdx(normalW.xyz);\nvec3 nDfdy=dFdy(normalW.xyz);\nfloat slopeSquare=max(dot(nDfdx,nDfdx),dot(nDfdy,nDfdy));\n\nfloat geometricRoughnessFactor=pow(clamp(slopeSquare ,0.,1.),0.333);\n\nfloat geometricAlphaGFactor=sqrt(slopeSquare);\n#else\nfloat geometricRoughnessFactor=0.;\n#endif\n#if defined(FORCENORMALFORWARD) && defined(NORMAL)\nvec3 faceNormal=normalize(cross(dFdx(vPositionW),dFdy(vPositionW)))*vEyePosition.w;\n#if defined(TWOSIDEDLIGHTING)\nfaceNormal=gl_FrontFacing ? faceNormal : -faceNormal;\n#endif\nnormalW*=sign(dot(normalW,faceNormal));\n#endif\n#if defined(TWOSIDEDLIGHTING) && defined(NORMAL)\nnormalW=gl_FrontFacing ? normalW : -normalW;\n#endif\n\n\nvec3 surfaceAlbedo=vAlbedoColor.rgb;\n\nfloat alpha=vAlbedoColor.a;\n#ifdef ALBEDO\nvec4 albedoTexture=texture2D(albedoSampler,vAlbedoUV+uvOffset);\n#if defined(ALPHAFROMALBEDO) || defined(ALPHATEST)\nalpha*=albedoTexture.a;\n#endif\nsurfaceAlbedo*=toLinearSpace(albedoTexture.rgb);\nsurfaceAlbedo*=vAlbedoInfos.y;\n#endif\n\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV+uvOffset);\n#ifdef OPACITYRGB\nalpha=getLuminance(opacityMap.rgb);\n#else\nalpha*=opacityMap.a;\n#endif\nalpha*=vOpacityInfos.y;\n#endif\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\n#if !defined(LINKREFRACTIONTOTRANSPARENCY) && !defined(ALPHAFRESNEL)\n#ifdef ALPHATEST\nif (alpha<ALPHATESTVALUE)\ndiscard;\n#ifndef ALPHABLEND\n\nalpha=1.0;\n#endif\n#endif\n#endif\n#include<depthPrePass>\n#ifdef VERTEXCOLOR\nsurfaceAlbedo*=vColor.rgb;\n#endif\n\nvec3 ambientOcclusionColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nvec3 ambientOcclusionColorMap=texture2D(ambientSampler,vAmbientUV+uvOffset).rgb*vAmbientInfos.y;\n#ifdef AMBIENTINGRAYSCALE\nambientOcclusionColorMap=vec3(ambientOcclusionColorMap.r,ambientOcclusionColorMap.r,ambientOcclusionColorMap.r);\n#endif\nambientOcclusionColor=mix(ambientOcclusionColor,ambientOcclusionColorMap,vAmbientInfos.z);\n#endif\n#ifdef UNLIT\nvec3 diffuseBase=vec3(1.,1.,1.);\n#else\n\nfloat microSurface=vReflectivityColor.a;\nvec3 surfaceReflectivityColor=vReflectivityColor.rgb;\n#ifdef METALLICWORKFLOW\nvec2 metallicRoughness=surfaceReflectivityColor.rg;\n#ifdef REFLECTIVITY\nvec4 surfaceMetallicColorMap=texture2D(reflectivitySampler,vReflectivityUV+uvOffset);\n#ifdef AOSTOREINMETALMAPRED\nvec3 aoStoreInMetalMap=vec3(surfaceMetallicColorMap.r,surfaceMetallicColorMap.r,surfaceMetallicColorMap.r);\nambientOcclusionColor=mix(ambientOcclusionColor,aoStoreInMetalMap,vReflectivityInfos.z);\n#endif\n#ifdef METALLNESSSTOREINMETALMAPBLUE\nmetallicRoughness.r*=surfaceMetallicColorMap.b;\n#else\nmetallicRoughness.r*=surfaceMetallicColorMap.r;\n#endif\n#ifdef ROUGHNESSSTOREINMETALMAPALPHA\nmetallicRoughness.g*=surfaceMetallicColorMap.a;\n#else\n#ifdef ROUGHNESSSTOREINMETALMAPGREEN\nmetallicRoughness.g*=surfaceMetallicColorMap.g;\n#endif\n#endif\n#endif\n#ifdef MICROSURFACEMAP\nvec4 microSurfaceTexel=texture2D(microSurfaceSampler,vMicroSurfaceSamplerUV+uvOffset)*vMicroSurfaceSamplerInfos.y;\nmetallicRoughness.g*=microSurfaceTexel.r;\n#endif\n\nmicroSurface=1.0-metallicRoughness.g;\n\nvec3 baseColor=surfaceAlbedo;\n\n\nconst vec3 DefaultSpecularReflectanceDielectric=vec3(0.04,0.04,0.04);\n\nsurfaceAlbedo=mix(baseColor.rgb*(1.0-DefaultSpecularReflectanceDielectric.r),vec3(0.,0.,0.),metallicRoughness.r);\n\nsurfaceReflectivityColor=mix(DefaultSpecularReflectanceDielectric,baseColor,metallicRoughness.r);\n#else\n#ifdef REFLECTIVITY\nvec4 surfaceReflectivityColorMap=texture2D(reflectivitySampler,vReflectivityUV+uvOffset);\nsurfaceReflectivityColor*=toLinearSpace(surfaceReflectivityColorMap.rgb);\nsurfaceReflectivityColor*=vReflectivityInfos.y;\n#ifdef MICROSURFACEFROMREFLECTIVITYMAP\nmicroSurface*=surfaceReflectivityColorMap.a;\nmicroSurface*=vReflectivityInfos.z;\n#else\n#ifdef MICROSURFACEAUTOMATIC\nmicroSurface*=computeDefaultMicroSurface(microSurface,surfaceReflectivityColor);\n#endif\n#ifdef MICROSURFACEMAP\nvec4 microSurfaceTexel=texture2D(microSurfaceSampler,vMicroSurfaceSamplerUV+uvOffset)*vMicroSurfaceSamplerInfos.y;\nmicroSurface*=microSurfaceTexel.r;\n#endif\n#endif\n#endif\n#endif\n\nmicroSurface=clamp(microSurface,0.,1.);\n\nfloat roughness=1.-microSurface;\n\n#ifdef ALPHAFRESNEL\n#if defined(ALPHATEST) || defined(ALPHABLEND)\n\n\n\nfloat opacityPerceptual=alpha;\n#ifdef LINEARALPHAFRESNEL\nfloat opacity0=opacityPerceptual;\n#else\nfloat opacity0=opacityPerceptual*opacityPerceptual;\n#endif\nfloat opacity90=fresnelGrazingReflectance(opacity0);\nvec3 normalForward=faceforward(normalW,-viewDirectionW,normalW);\n\nalpha=fresnelSchlickEnvironmentGGX(clamp(dot(viewDirectionW,normalForward),0.0,1.0),vec3(opacity0),vec3(opacity90),sqrt(microSurface)).x;\n#ifdef ALPHATEST\nif (alpha<ALPHATESTVALUE)\ndiscard;\n#ifndef ALPHABLEND\n\nalpha=1.0;\n#endif\n#endif\n#endif\n#endif\n\n\nfloat NdotVUnclamped=dot(normalW,viewDirectionW);\nfloat NdotV=clamp(NdotVUnclamped,0.,1.)+0.00001;\nfloat alphaG=convertRoughnessToAverageSlope(roughness);\n#ifdef SPECULARAA\n\n\nalphaG+=(0.75*geometricAlphaGFactor);\n#endif\n\n#ifdef REFRACTION\nvec3 environmentRefraction=vec3(0.,0.,0.);\nvec3 refractionVector=refract(-viewDirectionW,normalW,vRefractionInfos.y);\n#ifdef REFRACTIONMAP_OPPOSITEZ\nrefractionVector.z*=-1.0;\n#endif\n\n#ifdef REFRACTIONMAP_3D\nrefractionVector.y=refractionVector.y*vRefractionInfos.w;\nvec3 refractionCoords=refractionVector;\nrefractionCoords=vec3(refractionMatrix*vec4(refractionCoords,0));\n#else\nvec3 vRefractionUVW=vec3(refractionMatrix*(view*vec4(vPositionW+refractionVector*vRefractionInfos.z,1.0)));\nvec2 refractionCoords=vRefractionUVW.xy/vRefractionUVW.z;\nrefractionCoords.y=1.0-refractionCoords.y;\n#endif\n#ifdef LODINREFRACTIONALPHA\nfloat refractionLOD=getLodFromAlphaG(vRefractionMicrosurfaceInfos.x,alphaG,NdotVUnclamped);\n#else\nfloat refractionLOD=getLodFromAlphaG(vRefractionMicrosurfaceInfos.x,alphaG,1.0);\n#endif\n#ifdef LODBASEDMICROSFURACE\n\nrefractionLOD=refractionLOD*vRefractionMicrosurfaceInfos.y+vRefractionMicrosurfaceInfos.z;\n#ifdef LODINREFRACTIONALPHA\n\n\n\n\n\n\n\n\n\nfloat automaticRefractionLOD=UNPACK_LOD(sampleRefraction(refractionSampler,refractionCoords).a);\nfloat requestedRefractionLOD=max(automaticRefractionLOD,refractionLOD);\n#else\nfloat requestedRefractionLOD=refractionLOD;\n#endif\nenvironmentRefraction=sampleRefractionLod(refractionSampler,refractionCoords,requestedRefractionLOD).rgb;\n#else\nfloat lodRefractionNormalized=clamp(refractionLOD/log2(vRefractionMicrosurfaceInfos.x),0.,1.);\nfloat lodRefractionNormalizedDoubled=lodRefractionNormalized*2.0;\nvec3 environmentRefractionMid=sampleRefraction(refractionSampler,refractionCoords).rgb;\nif(lodRefractionNormalizedDoubled<1.0){\nenvironmentRefraction=mix(\nsampleRefraction(refractionSamplerHigh,refractionCoords).rgb,\nenvironmentRefractionMid,\nlodRefractionNormalizedDoubled\n);\n}else{\nenvironmentRefraction=mix(\nenvironmentRefractionMid,\nsampleRefraction(refractionSamplerLow,refractionCoords).rgb,\nlodRefractionNormalizedDoubled-1.0\n);\n}\n#endif\n#ifdef GAMMAREFRACTION\nenvironmentRefraction=toLinearSpace(environmentRefraction.rgb);\n#endif\n\nenvironmentRefraction*=vRefractionInfos.x;\n#endif\n\n#ifdef REFLECTION\nvec3 environmentRadiance=vec3(0.,0.,0.);\nvec3 environmentIrradiance=vec3(0.,0.,0.);\nvec3 reflectionVector=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflectionVector.z*=-1.0;\n#endif\n\n#ifdef REFLECTIONMAP_3D\nvec3 reflectionCoords=reflectionVector;\n#else\nvec2 reflectionCoords=reflectionVector.xy;\n#ifdef REFLECTIONMAP_PROJECTION\nreflectionCoords/=reflectionVector.z;\n#endif\nreflectionCoords.y=1.0-reflectionCoords.y;\n#endif\n#if defined(LODINREFLECTIONALPHA) && !defined(REFLECTIONMAP_SKYBOX)\nfloat reflectionLOD=getLodFromAlphaG(vReflectionMicrosurfaceInfos.x,alphaG,NdotVUnclamped);\n#else\nfloat reflectionLOD=getLodFromAlphaG(vReflectionMicrosurfaceInfos.x,alphaG,1.);\n#endif\n#ifdef LODBASEDMICROSFURACE\n\nreflectionLOD=reflectionLOD*vReflectionMicrosurfaceInfos.y+vReflectionMicrosurfaceInfos.z;\n#ifdef LODINREFLECTIONALPHA\n\n\n\n\n\n\n\n\n\nfloat automaticReflectionLOD=UNPACK_LOD(sampleReflection(reflectionSampler,reflectionCoords).a);\nfloat requestedReflectionLOD=max(automaticReflectionLOD,reflectionLOD);\n#else\nfloat requestedReflectionLOD=reflectionLOD;\n#endif\nenvironmentRadiance=sampleReflectionLod(reflectionSampler,reflectionCoords,requestedReflectionLOD).rgb;\n#else\nfloat lodReflectionNormalized=clamp(reflectionLOD/log2(vReflectionMicrosurfaceInfos.x),0.,1.);\nfloat lodReflectionNormalizedDoubled=lodReflectionNormalized*2.0;\nvec3 environmentSpecularMid=sampleReflection(reflectionSampler,reflectionCoords).rgb;\nif(lodReflectionNormalizedDoubled<1.0){\nenvironmentRadiance=mix(\nsampleReflection(reflectionSamplerHigh,reflectionCoords).rgb,\nenvironmentSpecularMid,\nlodReflectionNormalizedDoubled\n);\n}else{\nenvironmentRadiance=mix(\nenvironmentSpecularMid,\nsampleReflection(reflectionSamplerLow,reflectionCoords).rgb,\nlodReflectionNormalizedDoubled-1.0\n);\n}\n#endif\n#ifdef GAMMAREFLECTION\nenvironmentRadiance=toLinearSpace(environmentRadiance.rgb);\n#endif\n\n#ifdef USESPHERICALFROMREFLECTIONMAP\n#if defined(NORMAL) && defined(USESPHERICALINVERTEX)\nenvironmentIrradiance=vEnvironmentIrradiance;\n#else\nvec3 irradianceVector=vec3(reflectionMatrix*vec4(normalW,0)).xyz;\n#ifdef REFLECTIONMAP_OPPOSITEZ\nirradianceVector.z*=-1.0;\n#endif\nenvironmentIrradiance=environmentIrradianceJones(irradianceVector);\n#endif\n#endif\n\nenvironmentRadiance*=vReflectionInfos.x;\nenvironmentRadiance*=vReflectionColor.rgb;\nenvironmentIrradiance*=vReflectionColor.rgb;\n#endif\n\n\n\nfloat reflectance=max(max(surfaceReflectivityColor.r,surfaceReflectivityColor.g),surfaceReflectivityColor.b);\nfloat reflectance90=fresnelGrazingReflectance(reflectance);\nvec3 specularEnvironmentR0=surfaceReflectivityColor.rgb;\nvec3 specularEnvironmentR90=vec3(1.0,1.0,1.0)*reflectance90;\n\nvec3 diffuseBase=vec3(0.,0.,0.);\n#ifdef SPECULARTERM\nvec3 specularBase=vec3(0.,0.,0.);\n#endif\n#ifdef LIGHTMAP\nvec3 lightmapColor=texture2D(lightmapSampler,vLightmapUV+uvOffset).rgb;\n#ifdef GAMMALIGHTMAP\nlightmapColor=toLinearSpace(lightmapColor);\n#endif\nlightmapColor*=vLightmapInfos.y;\n#endif\nlightingInfo info;\nfloat shadow=1.; \nfloat NdotL=-1.;\n#include<lightFragment>[0..maxSimultaneousLights]\n\n#if defined(ENVIRONMENTBRDF) && !defined(REFLECTIONMAP_SKYBOX)\n\nvec2 brdfSamplerUV=vec2(NdotV,roughness);\n\nvec4 environmentBrdf=texture2D(environmentBrdfSampler,brdfSamplerUV);\nvec3 specularEnvironmentReflectance=specularEnvironmentR0*environmentBrdf.x+environmentBrdf.y;\n#ifdef RADIANCEOCCLUSION\n#ifdef AMBIENTINGRAYSCALE\nfloat ambientMonochrome=ambientOcclusionColor.r;\n#else\nfloat ambientMonochrome=getLuminance(ambientOcclusionColor);\n#endif\nfloat seo=environmentRadianceOcclusion(ambientMonochrome,NdotVUnclamped);\nspecularEnvironmentReflectance*=seo;\n#endif\n#ifdef HORIZONOCCLUSION\n#ifdef BUMP\n#ifdef REFLECTIONMAP_3D\nfloat eho=environmentHorizonOcclusion(-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*=tint;\n\nalpha=1.0;\n#endif\n\nvec3 bounceSpecularEnvironmentReflectance=(2.0*specularEnvironmentReflectance)/(1.0+specularEnvironmentReflectance);\nspecularEnvironmentReflectance=mix(bounceSpecularEnvironmentReflectance,specularEnvironmentReflectance,alpha);\n\ntransmission*=1.0-specularEnvironmentReflectance;\n\nrefractance=transmission;\n#endif\n\n\n\n\nsurfaceAlbedo.rgb=(1.-reflectance)*surfaceAlbedo.rgb;\n\n#ifdef REFLECTION\nvec3 finalIrradiance=environmentIrradiance;\nfinalIrradiance*=surfaceAlbedo.rgb;\n#endif\n\n#ifdef SPECULARTERM\nvec3 finalSpecular=specularBase;\nfinalSpecular=max(finalSpecular,0.0);\n\nvec3 finalSpecularScaled=finalSpecular*vLightingIntensity.x*vLightingIntensity.w;\n#endif\n\n#ifdef REFLECTION\nvec3 finalRadiance=environmentRadiance;\nfinalRadiance*=specularEnvironmentReflectance;\n\nvec3 finalRadianceScaled=finalRadiance*vLightingIntensity.z;\n#endif\n\n#ifdef REFRACTION\nvec3 finalRefraction=environmentRefraction;\nfinalRefraction*=refractance;\n#endif\n\n#ifdef ALPHABLEND\nfloat luminanceOverAlpha=0.0;\n#if defined(REFLECTION) && defined(RADIANCEOVERALPHA)\nluminanceOverAlpha+=getLuminance(finalRadianceScaled);\n#endif\n#if defined(SPECULARTERM) && defined(SPECULAROVERALPHA)\nluminanceOverAlpha+=getLuminance(finalSpecularScaled);\n#endif\n#if defined(RADIANCEOVERALPHA) || defined(SPECULAROVERALPHA)\nalpha=clamp(alpha+luminanceOverAlpha*luminanceOverAlpha,0.,1.);\n#endif\n#endif\n#endif\n\nvec3 finalDiffuse=diffuseBase;\nfinalDiffuse.rgb+=vAmbientColor;\nfinalDiffuse*=surfaceAlbedo.rgb;\nfinalDiffuse=max(finalDiffuse,0.0);\n\nvec3 finalEmissive=vEmissiveColor;\n#ifdef EMISSIVE\nvec3 emissiveColorTex=texture2D(emissiveSampler,vEmissiveUV+uvOffset).rgb;\nfinalEmissive*=toLinearSpace(emissiveColorTex.rgb);\nfinalEmissive*=vEmissiveInfos.y;\n#endif\n\n\n\nvec4 finalColor=vec4(\nfinalDiffuse*ambientOcclusionColor*vLightingIntensity.x +\n#ifndef UNLIT\n#ifdef REFLECTION\nfinalIrradiance*ambientOcclusionColor*vLightingIntensity.z +\n#endif\n#ifdef SPECULARTERM\n\n\nfinalSpecularScaled +\n#endif\n#ifdef REFLECTION\n\n\nfinalRadianceScaled +\n#endif\n#ifdef REFRACTION\nfinalRefraction*vLightingIntensity.z +\n#endif\n#endif\nfinalEmissive*vLightingIntensity.y,\nalpha);\n\n#ifdef LIGHTMAP\n#ifndef LIGHTMAPEXCLUDED\n#ifdef USELIGHTMAPASSHADOWMAP\nfinalColor.rgb*=lightmapColor;\n#else\nfinalColor.rgb+=lightmapColor;\n#endif\n#endif\n#endif\n\nfinalColor=max(finalColor,0.0);\n#include<logDepthFragment>\n#include<fogFragment>(color,finalColor)\n#ifdef IMAGEPROCESSINGPOSTPROCESS\n\n\nfinalColor.rgb=clamp(finalColor.rgb,0.,30.0);\n#else\n\nfinalColor=applyImageProcessing(finalColor);\n#endif\n#ifdef PREMULTIPLYALPHA\n\nfinalColor.rgb*=finalColor.a;\n#endif\ngl_FragColor=finalColor;\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n}","spritesVertexShader":"\nattribute vec4 position;\nattribute vec4 options;\nattribute vec4 cellInfo;\nattribute vec4 color;\n\nuniform vec2 textureInfos;\nuniform mat4 view;\nuniform mat4 projection;\n\nvarying vec2 vUV;\nvarying vec4 vColor;\n#include<fogVertexDeclaration>\nvoid main(void) { \nvec3 viewPos=(view*vec4(position.xyz,1.0)).xyz; \nvec2 cornerPos;\nfloat angle=position.w;\nvec2 size=vec2(options.x,options.y);\nvec2 offset=options.zw;\nvec2 uvScale=textureInfos.xy;\ncornerPos=vec2(offset.x-0.5,offset.y-0.5)*size;\n\nvec3 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\n\nviewPos+=rotatedCorner;\ngl_Position=projection*vec4(viewPos,1.0); \n\nvColor=color;\n\nvec2 uvOffset=vec2(abs(offset.x-cellInfo.x),1.0-abs(offset.y-cellInfo.y));\nvUV=(uvOffset+cellInfo.zw)*uvScale;\n\n#ifdef FOG\nvFogDistance=viewPos;\n#endif\n}","spritesPixelShader":"uniform bool alphaTest;\nvarying vec4 vColor;\n\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n\n#include<fogFragmentDeclaration>\nvoid main(void) {\nvec4 color=texture2D(diffuseSampler,vUV);\nif (alphaTest) \n{\nif (color.a<0.95)\ndiscard;\n}\ncolor*=vColor;\n#include<fogFragment>\ngl_FragColor=color;\n}","particlesVertexShader":"\nattribute vec3 position;\nattribute vec4 color;\nattribute vec4 options;\nattribute float cellIndex;\n\nuniform mat4 view;\nuniform mat4 projection;\nuniform vec3 particlesInfos; \n\nvarying vec2 vUV;\nvarying vec4 vColor;\n#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nuniform mat4 invView;\nvarying float fClipDistance;\n#endif\nvoid main(void) { \nvec3 viewPos=(view*vec4(position,1.0)).xyz; \nvec2 cornerPos;\nfloat size=options.y;\nfloat angle=options.x;\nvec2 offset=options.zw;\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); \nvColor=color;\n#ifdef ANIMATESHEET\nfloat rowOffset=floor(cellIndex/particlesInfos.z);\nfloat columnOffset=cellIndex-rowOffset*particlesInfos.z;\nvec2 uvScale=particlesInfos.xy;\nvec2 uvOffset=vec2(offset.x ,1.0-offset.y);\nvUV=(uvOffset+vec2(columnOffset,rowOffset))*uvScale;\n#else\nvUV=offset;\n#endif\n\n#ifdef CLIPPLANE\nvec4 worldPos=invView*vec4(viewPos,1.0);\nfClipDistance=dot(worldPos,vClipPlane);\n#endif\n}","particlesPixelShader":"\nvarying vec2 vUV;\nvarying vec4 vColor;\nuniform vec4 textureMask;\nuniform sampler2D diffuseSampler;\n#ifdef CLIPPLANE\nvarying float fClipDistance;\n#endif\nvoid main(void) {\n#ifdef CLIPPLANE\nif (fClipDistance>0.0)\ndiscard;\n#endif\nvec4 baseColor=texture2D(diffuseSampler,vUV);\ngl_FragColor=(baseColor*textureMask+(vec4(1.,1.,1.,1.)-textureMask))*vColor;\n}","gpuRenderParticlesVertexShader":"#version 300 es\nuniform vec4 colorDead;\nuniform mat4 view;\nuniform mat4 projection;\n\nin vec3 position;\nin float age;\nin float life;\nin float size;\nin vec4 color;\nin vec2 offset;\nin vec2 uv;\nin vec2 angle;\nout vec2 vUV;\nout vec4 vColor;\n#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nuniform mat4 invView;\nout float fClipDistance;\n#endif\nvoid main() {\nvUV=uv;\nfloat ratio=age/life;\nvColor=color*vec4(1.0-ratio)+colorDead*vec4(ratio);\nvec2 cornerPos=offset*size;\n\nvec4 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle.x)-cornerPos.y*sin(angle.x);\nrotatedCorner.y=cornerPos.x*sin(angle.x)+cornerPos.y*cos(angle.x);\nrotatedCorner.z=0.;\nrotatedCorner.w=0.;\n\nvec4 viewPosition=view*vec4(position,1.0);\ngl_Position=projection*(viewPosition+rotatedCorner);\n\n#ifdef CLIPPLANE\nvec4 worldPos=invView*viewPosition;\nfClipDistance=dot(worldPos,vClipPlane);\n#endif \n}","gpuRenderParticlesPixelShader":"#version 300 es\nuniform sampler2D textureSampler;\nin vec2 vUV;\nin vec4 vColor;\nout vec4 outFragColor;\n#ifdef CLIPPLANE\nin float fClipDistance;\n#endif\nvoid main() {\n#ifdef CLIPPLANE\nif (fClipDistance>0.0)\ndiscard;\n#endif \noutFragColor=texture(textureSampler,vUV)*vColor;\n}\n","gpuUpdateParticlesVertexShader":"#version 300 es\n#define PI 3.14159\nuniform float currentCount;\nuniform float timeDelta;\nuniform float stopFactor;\nuniform vec3 generalRandoms;\nuniform mat4 emitterWM;\nuniform vec2 lifeTime;\nuniform vec2 emitPower;\nuniform vec2 sizeRange;\nuniform vec4 color1;\nuniform vec4 color2;\nuniform vec3 gravity;\nuniform sampler2D randomSampler;\nuniform vec2 angleRange;\n#ifdef BOXEMITTER\nuniform vec3 direction1;\nuniform vec3 direction2;\nuniform vec3 minEmitBox;\nuniform vec3 maxEmitBox;\n#endif\n#ifdef SPHEREEMITTER\nuniform float radius;\n#ifdef DIRECTEDSPHEREEMITTER\nuniform vec3 direction1;\nuniform vec3 direction2;\n#else\nuniform float directionRandomizer;\n#endif\n#endif\n#ifdef CONEEMITTER\nuniform float radius;\nuniform float coneAngle;\nuniform float height;\nuniform float directionRandomizer;\n#endif\n\nin vec3 position;\nin float age;\nin float life;\nin float seed;\nin float size;\nin vec4 color;\nin vec3 direction;\nin vec2 angle;\n\nout vec3 outPosition;\nout float outAge;\nout float outLife;\nout float outSeed;\nout float outSize;\nout vec4 outColor;\nout vec3 outDirection;\nout vec2 outAngle;\nvec3 getRandomVec3(float offset) {\nreturn texture(randomSampler,vec2(float(gl_VertexID)*offset/currentCount,0)).rgb;\n}\nvec4 getRandomVec4(float offset) {\nreturn texture(randomSampler,vec2(float(gl_VertexID)*offset/currentCount,0));\n}\nvoid main() {\nif (age>=life) {\nif (stopFactor == 0.) {\noutPosition=position;\noutAge=life;\noutLife=life;\noutSeed=seed;\noutColor=vec4(0.,0.,0.,0.);\noutSize=0.;\noutDirection=direction;\noutAngle=angle;\nreturn;\n}\nvec3 position;\nvec3 direction;\n\nvec4 randoms=getRandomVec4(generalRandoms.x);\n\noutAge=0.0;\noutLife=lifeTime.x+(lifeTime.y-lifeTime.x)*randoms.r;\n\noutSeed=seed;\n\noutSize=sizeRange.x+(sizeRange.y-sizeRange.x)*randoms.g;\n\noutColor=color1+(color2-color1)*randoms.b;\n\noutAngle.y=angleRange.x+(angleRange.y-angleRange.x)*randoms.a;\noutAngle.x=0.;\n\n#ifdef BOXEMITTER\nvec3 randoms2=getRandomVec3(generalRandoms.y);\nvec3 randoms3=getRandomVec3(generalRandoms.z);\nposition=minEmitBox+(maxEmitBox-minEmitBox)*randoms2;\ndirection=direction1+(direction2-direction1)*randoms3;\n#elif defined(SPHEREEMITTER)\nvec3 randoms2=getRandomVec3(generalRandoms.y);\nvec3 randoms3=getRandomVec3(generalRandoms.z);\n\nfloat phi=2.0*PI*randoms2.x;\nfloat theta=PI*randoms2.y;\nfloat randX=cos(phi)*sin(theta);\nfloat randY=cos(theta);\nfloat randZ=sin(phi)*sin(theta);\nposition=(radius*randoms2.z)*vec3(randX,randY,randZ);\n#ifdef DIRECTEDSPHEREEMITTER\ndirection=direction1+(direction2-direction1)*randoms3;\n#else\n\ndirection=position+directionRandomizer*randoms3;\n#endif\n#elif defined(CONEEMITTER)\nvec3 randoms2=getRandomVec3(generalRandoms.y);\nfloat s=2.0*PI*randoms2.x;\nfloat h=randoms2.y;\n\nh=1.-h*h;\nfloat lRadius=radius*randoms2.z;\nlRadius=lRadius*h;\nfloat randX=lRadius*sin(s);\nfloat randZ=lRadius*cos(s);\nfloat randY=h*height;\nposition=vec3(randX,randY,randZ); \n\nif (coneAngle == 0.) {\ndirection=vec3(0.,1.0,0.);\n} else {\nvec3 randoms3=getRandomVec3(generalRandoms.z);\ndirection=position+directionRandomizer*randoms3;\n}\n#else \n\nposition=vec3(0.,0.,0.);\n\ndirection=2.0*(getRandomVec3(seed)-vec3(0.5,0.5,0.5));\n#endif\nfloat power=emitPower.x+(emitPower.y-emitPower.x)*randoms.a;\noutPosition=(emitterWM*vec4(position,1.)).xyz;\noutDirection=(emitterWM*vec4(direction*power,0.)).xyz;\n} else { \noutPosition=position+direction*timeDelta;\noutAge=age+timeDelta;\noutLife=life;\noutSeed=seed;\noutColor=color;\noutSize=size;\noutDirection=direction+gravity*timeDelta;\noutAngle=vec2(angle.x+angle.y*timeDelta,angle.y);\n}\n}","gpuUpdateParticlesPixelShader":"#version 300 es\nvoid main() {\ndiscard;\n}\n","colorVertexShader":"\nattribute vec3 position;\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<bonesDeclaration>\n\nuniform mat4 viewProjection;\nuniform mat4 world;\n\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\nvoid main(void) {\nmat4 finalWorld=world;\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#ifdef VERTEXCOLOR\n\nvColor=color;\n#endif\n}","colorPixelShader":"#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#else\nuniform vec4 color;\n#endif\nvoid main(void) {\n#ifdef VERTEXCOLOR\ngl_FragColor=vColor;\n#else\ngl_FragColor=color;\n#endif\n}","postprocessVertexShader":"\nattribute vec2 position;\nuniform vec2 scale;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=(position*madd+madd)*scale;\ngl_Position=vec4(position,0.0,1.0);\n}","passPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nvoid main(void) \n{\ngl_FragColor=texture2D(textureSampler,vUV);\n}","shadowMapVertexShader":"\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\nuniform vec3 lightData;\n#endif\n#include<bonesDeclaration>\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n\n#include<instancesDeclaration>\n#include<helperFunctions>\nuniform mat4 viewProjection;\nuniform vec3 biasAndScale;\nuniform vec2 depthValues;\nvarying float vDepthMetric;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\nvoid main(void)\n{\nvec3 positionUpdated=position;\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#include<instancesVertex>\n#include<bonesVertex>\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\n\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvec3 worldNor=normalize(normalWorld*normal);\n#ifdef DIRECTIONINLIGHTDATA\nvec3 worldLightDir=normalize(-lightData.xyz);\n#else\nvec3 directionToLight=lightData.xyz-worldPos.xyz;\nvec3 worldLightDir=normalize(directionToLight);\n#endif\nfloat ndl=dot(worldNor,worldLightDir);\nfloat sinNL=sqrt(1.0-ndl*ndl);\nfloat normalBias=biasAndScale.y*sinNL;\nworldPos.xyz-=worldNor*normalBias;\n#endif\n\ngl_Position=viewProjection*worldPos;\n#ifdef DEPTHTEXTURE\n\ngl_Position.z+=biasAndScale.x*gl_Position.w;\n#endif\n\nvDepthMetric=((gl_Position.z+depthValues.x)/(depthValues.y))+biasAndScale.x;\n#ifdef ALPHATEST\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","shadowMapPixelShader":"#ifndef FLOAT\nvec4 pack(float depth)\n{\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(depth*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\n#endif\nvarying float vDepthMetric;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\nuniform vec3 biasAndScale;\nuniform vec2 depthValues;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\nfloat depth=vDepthMetric;\n#ifdef ESM\ndepth=clamp(exp(-min(87.,biasAndScale.z*depth)),0.,1.);\n#endif\n#ifdef FLOAT\ngl_FragColor=vec4(depth,1.0,1.0,1.0);\n#else\ngl_FragColor=pack(depth);\n#endif\n}","depthBoxBlurPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec2 screenSize;\nvoid main(void)\n{\nvec4 colorDepth=vec4(0.0);\nfor (int x=-OFFSET; x<=OFFSET; x++)\nfor (int y=-OFFSET; y<=OFFSET; y++)\ncolorDepth+=texture2D(textureSampler,vUV+vec2(x,y)/screenSize);\ngl_FragColor=(colorDepth/float((OFFSET*2+1)*(OFFSET*2+1)));\n}","proceduralVertexShader":"\nattribute vec2 position;\n\nvarying vec2 vPosition;\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvPosition=position;\nvUV=position*madd+madd;\ngl_Position=vec4(position,0.0,1.0);\n}","depthVertexShader":"\nattribute vec3 position;\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\nuniform vec2 depthValues;\n#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\nvarying float vDepthMetric;\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\nvDepthMetric=((gl_Position.z+depthValues.x)/(depthValues.y));\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","depthPixelShader":"#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\nvarying float vDepthMetric;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\ngl_FragColor=vec4(vDepthMetric,vDepthMetric*vDepthMetric,0.0,1.0);\n}","ssaoPixelShader":"\nuniform sampler2D textureSampler;\nvarying vec2 vUV;\n#ifdef SSAO\nuniform sampler2D randomSampler;\nuniform float randTextureTiles;\nuniform float samplesFactor;\nuniform vec3 sampleSphere[SAMPLES];\nuniform float totalStrength;\nuniform float radius;\nuniform float area;\nuniform float fallOff;\nuniform float base;\nvec3 normalFromDepth(float depth,vec2 coords)\n{\nvec2 offset1=vec2(0.0,radius);\nvec2 offset2=vec2(radius,0.0);\nfloat depth1=texture2D(textureSampler,coords+offset1).r;\nfloat depth2=texture2D(textureSampler,coords+offset2).r;\nvec3 p1=vec3(offset1,depth1-depth);\nvec3 p2=vec3(offset2,depth2-depth);\nvec3 normal=cross(p1,p2);\nnormal.z=-normal.z;\nreturn normalize(normal);\n}\nvoid main()\n{\nvec3 random=normalize(texture2D(randomSampler,vUV*randTextureTiles).rgb);\nfloat depth=texture2D(textureSampler,vUV).r;\nvec3 position=vec3(vUV,depth);\nvec3 normal=normalFromDepth(depth,vUV);\nfloat radiusDepth=radius/depth;\nfloat occlusion=0.0;\nvec3 ray;\nvec3 hemiRay;\nfloat occlusionDepth;\nfloat difference;\nfor (int i=0; i<SAMPLES; i++)\n{\nray=radiusDepth*reflect(sampleSphere[i],random);\nhemiRay=position+sign(dot(ray,normal))*ray;\nocclusionDepth=texture2D(textureSampler,clamp(hemiRay.xy,vec2(0.001,0.001),vec2(0.999,0.999))).r;\ndifference=depth-occlusionDepth;\nocclusion+=step(fallOff,difference)*(1.0-smoothstep(fallOff,area,difference));\n}\nfloat ao=1.0-totalStrength*occlusion*samplesFactor;\nfloat result=clamp(ao+base,0.0,1.0);\ngl_FragColor.r=result;\ngl_FragColor.g=result;\ngl_FragColor.b=result;\ngl_FragColor.a=1.0;\n}\n#endif\n","ssao2PixelShader":"\nprecision highp float;\nuniform sampler2D textureSampler;\nuniform float near;\nuniform float far;\nuniform float radius;\nvarying vec2 vUV;\nfloat perspectiveDepthToViewZ( const in float invClipZ,const in float near,const in float far ) {\nreturn ( near*far )/( ( far-near )*invClipZ-far );\n}\nfloat viewZToPerspectiveDepth( const in float viewZ,const in float near,const in float far ) {\nreturn ( near*far/viewZ+far)/( far-near );\n}\nfloat viewZToOrthographicDepth( const in float viewZ,const in float near,const in float far ) {\nreturn ( viewZ+near )/( near-far );\n}\n#ifdef SSAO\nuniform sampler2D randomSampler;\nuniform sampler2D normalSampler;\nuniform float randTextureTiles;\nuniform float samplesFactor;\nuniform vec3 sampleSphere[SAMPLES];\nuniform float totalStrength;\nuniform float base;\nuniform float xViewport;\nuniform float yViewport;\nuniform float maxZ;\nuniform float minZAspect;\nuniform vec2 texelSize;\nuniform mat4 projection;\nvoid main()\n{\nvec3 random=texture2D(randomSampler,vUV*randTextureTiles).rgb;\nfloat depth=texture2D(textureSampler,vUV).r;\nfloat depthSign=depth/abs(depth);\ndepth=depth*depthSign;\nvec3 normal=texture2D(normalSampler,vUV).rgb; \nfloat occlusion=0.0;\nfloat correctedRadius=min(radius,minZAspect*depth/near);\nvec3 vViewRay=vec3((vUV.x*2.0-1.0)*xViewport,(vUV.y*2.0-1.0)*yViewport,depthSign);\nvec3 origin=vViewRay*depth;\nvec3 rvec=random*2.0-1.0;\nrvec.z=0.0;\nvec3 tangent=normalize(rvec-normal*dot(rvec,normal));\nvec3 bitangent=cross(normal,tangent);\nmat3 tbn=mat3(tangent,bitangent,normal);\nfloat difference;\nif (depth>maxZ) {\ngl_FragColor=vec4(1.0,1.0,1.0,1.0);\nreturn;\n}\nfor (int i=0; i<SAMPLES; ++i) {\n\nvec3 samplePosition=tbn*sampleSphere[i];\nsamplePosition=samplePosition*correctedRadius+origin;\n\nvec4 offset=vec4(samplePosition,1.0);\noffset=projection*offset;\noffset.xyz/=offset.w;\noffset.xy=offset.xy*0.5+0.5;\nif (offset.x<0.0 || offset.y<0.0 || offset.x>1.0 || offset.y>1.0) {\ncontinue;\n}\n\nfloat sampleDepth=abs(texture2D(textureSampler,offset.xy).r);\n\nfloat rangeCheck=abs(depth-sampleDepth)<correctedRadius ? 1.0 : 0.0;\ndifference=depthSign*samplePosition.z-sampleDepth;\n\nocclusion+=(difference>=1e-5 ? 1.0 : 0.0)*rangeCheck;\n}\n\nfloat ao=1.0-totalStrength*occlusion*samplesFactor;\nfloat result=clamp(ao+base,0.0,1.0);\ngl_FragColor=vec4(vec3(result),1.0);\n}\n#endif\n#ifdef BILATERAL_BLUR\nuniform sampler2D depthSampler;\nuniform float outSize;\nuniform float samplerOffsets[SAMPLES];\nvec4 blur9(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.3846153846)*direction;\nvec2 off2=vec2(3.2307692308)*direction;\ncolor+=texture2D(image,uv)*0.2270270270;\ncolor+=texture2D(image,uv+(off1/resolution))*0.3162162162;\ncolor+=texture2D(image,uv-(off1/resolution))*0.3162162162;\ncolor+=texture2D(image,uv+(off2/resolution))*0.0702702703;\ncolor+=texture2D(image,uv-(off2/resolution))*0.0702702703;\nreturn color;\n}\nvec4 blur13(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.411764705882353)*direction;\nvec2 off2=vec2(3.2941176470588234)*direction;\nvec2 off3=vec2(5.176470588235294)*direction;\ncolor+=texture2D(image,uv)*0.1964825501511404;\ncolor+=texture2D(image,uv+(off1/resolution))*0.2969069646728344;\ncolor+=texture2D(image,uv-(off1/resolution))*0.2969069646728344;\ncolor+=texture2D(image,uv+(off2/resolution))*0.09447039785044732;\ncolor+=texture2D(image,uv-(off2/resolution))*0.09447039785044732;\ncolor+=texture2D(image,uv+(off3/resolution))*0.010381362401148057;\ncolor+=texture2D(image,uv-(off3/resolution))*0.010381362401148057;\nreturn color;\n}\nvec4 blur13Bilateral(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.411764705882353)*direction;\nvec2 off2=vec2(3.2941176470588234)*direction;\nvec2 off3=vec2(5.176470588235294)*direction;\nfloat compareDepth=abs(texture2D(depthSampler,uv).r);\nfloat sampleDepth;\nfloat weight;\nfloat weightSum=30.0;\ncolor+=texture2D(image,uv)*30.0;\nsampleDepth=abs(texture2D(depthSampler,uv+(off1/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off1/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off1/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off1/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv+(off2/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off2/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off2/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off2/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv+(off3/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off3/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off3/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off3/resolution))*weight;\nreturn color/weightSum;\n}\nvoid main()\n{\n#if EXPENSIVE\nfloat compareDepth=abs(texture2D(depthSampler,vUV).r);\nfloat texelsize=1.0/outSize;\nfloat result=0.0;\nfloat weightSum=0.0;\nfor (int i=0; i<SAMPLES; ++i)\n{\n#ifdef BILATERAL_BLUR_H\nvec2 direction=vec2(1.0,0.0);\nvec2 sampleOffset=vec2(texelsize*samplerOffsets[i],0.0);\n#else\nvec2 direction=vec2(0.0,1.0);\nvec2 sampleOffset=vec2(0.0,texelsize*samplerOffsets[i]);\n#endif\nvec2 samplePos=vUV+sampleOffset;\nfloat sampleDepth=abs(texture2D(depthSampler,samplePos).r);\nfloat weight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30000.0);\nresult+=texture2D(textureSampler,samplePos).r*weight;\nweightSum+=weight;\n}\nresult/=weightSum;\ngl_FragColor.rgb=vec3(result);\ngl_FragColor.a=1.0;\n#else\nvec4 color;\n#ifdef BILATERAL_BLUR_H\nvec2 direction=vec2(1.0,0.0);\ncolor=blur13Bilateral(textureSampler,vUV,outSize,direction);\n#else\nvec2 direction=vec2(0.0,1.0);\ncolor=blur13Bilateral(textureSampler,vUV,outSize,direction);\n#endif\ngl_FragColor.rgb=vec3(color.r);\ngl_FragColor.a=1.0;\n#endif\n}\n#endif\n","ssaoCombinePixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D originalColor;\nuniform vec4 viewport;\nvarying vec2 vUV;\nvoid main(void) {\nvec4 ssaoColor=texture2D(textureSampler,viewport.xy+vUV*viewport.zw);\nvec4 sceneColor=texture2D(originalColor,vUV);\ngl_FragColor=sceneColor*ssaoColor;\n}\n","lensHighlightsPixelShader":"\nuniform sampler2D textureSampler; \n\nuniform float gain;\nuniform float threshold;\nuniform float screen_width;\nuniform float screen_height;\n\nvarying vec2 vUV;\n\nvec4 highlightColor(vec4 color) {\nvec4 highlight=color;\nfloat luminance=dot(highlight.rgb,vec3(0.2125,0.7154,0.0721));\nfloat lum_threshold;\nif (threshold>1.0) { lum_threshold=0.94+0.01*threshold; }\nelse { lum_threshold=0.5+0.44*threshold; }\nluminance=clamp((luminance-lum_threshold)*(1.0/(1.0-lum_threshold)),0.0,1.0);\nhighlight*=luminance*gain;\nhighlight.a=1.0;\nreturn highlight;\n}\nvoid main(void)\n{\nvec4 original=texture2D(textureSampler,vUV);\n\nif (gain == -1.0) {\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\nreturn;\n}\nfloat w=2.0/screen_width;\nfloat h=2.0/screen_height;\nfloat weight=1.0;\n\nvec4 blurred=vec4(0.0,0.0,0.0,0.0);\n#ifdef PENTAGON\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.84*w,0.43*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.48*w,-1.29*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.61*w,1.51*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.55*w,-0.74*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.71*w,-0.52*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.94*w,1.59*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.40*w,-1.87*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.62*w,1.16*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.09*w,0.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.46*w,-1.71*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.08*w,2.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.85*w,-1.89*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.89*w,0.16*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.29*w,1.88*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.40*w,-2.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.54*w,2.26*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.60*w,-0.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.31*w,-1.30*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.83*w,2.53*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.12*w,-2.48*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.60*w,1.11*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.82*w,0.99*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.50*w,-2.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.85*w,3.33*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.94*w,-1.92*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.27*w,-0.53*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.95*w,2.48*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.23*w,-3.04*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.17*w,2.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.97*w,-0.04*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.25*w,-2.00*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.31*w,3.08*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.94*w,-2.59*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.37*w,0.64*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.13*w,1.93*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.03*w,-3.65*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.60*w,3.17*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.14*w,-1.19*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.00*w,-1.19*h)));\n#else\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.85*w,0.36*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.52*w,-1.14*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.46*w,1.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.46*w,-0.83*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.79*w,-0.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.11*w,1.62*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.29*w,-2.07*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.69*w,1.39*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.28*w,0.12*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.65*w,-1.69*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.08*w,2.44*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.63*w,-1.90*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.55*w,0.31*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.13*w,1.52*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.56*w,-2.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.38*w,2.34*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.64*w,-0.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.53*w,-1.21*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.06*w,2.63*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.00*w,-2.69*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.59*w,1.32*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.82*w,0.78*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.57*w,-2.50*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.54*w,2.93*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.39*w,-1.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.01*w,-0.28*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.04*w,2.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.02*w,-3.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.09*w,2.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.07*w,-0.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.44*w,-1.90*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.52*w,3.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.68*w,-2.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.01*w,0.79*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.76*w,1.46*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.05*w,-2.94*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.21*w,2.88*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.84*w,-1.30*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.98*w,-0.96*h)));\n#endif\nblurred/=39.0;\ngl_FragColor=blurred;\n\n}","depthOfFieldPixelShader":"\n\n\n\n\nuniform sampler2D textureSampler;\nuniform sampler2D highlightsSampler;\nuniform sampler2D depthSampler;\nuniform sampler2D grainSampler;\n\nuniform float grain_amount;\nuniform bool blur_noise;\nuniform float screen_width;\nuniform float screen_height;\nuniform float distortion;\nuniform bool dof_enabled;\n\nuniform float screen_distance; \nuniform float aperture;\nuniform float darken;\nuniform float edge_blur;\nuniform bool highlights;\n\nuniform float near;\nuniform float far;\n\nvarying vec2 vUV;\n\n#define PI 3.14159265\n#define TWOPI 6.28318530\n#define inverse_focal_length 0.1 \n\nvec2 centered_screen_pos;\nvec2 distorted_coords;\nfloat radius2;\nfloat radius;\n\nvec2 rand(vec2 co)\n{\nfloat noise1=(fract(sin(dot(co,vec2(12.9898,78.233)))*43758.5453));\nfloat noise2=(fract(sin(dot(co,vec2(12.9898,78.233)*2.0))*43758.5453));\nreturn clamp(vec2(noise1,noise2),0.0,1.0);\n}\n\nvec2 getDistortedCoords(vec2 coords) {\nif (distortion == 0.0) { return coords; }\nvec2 direction=1.0*normalize(centered_screen_pos);\nvec2 dist_coords=vec2(0.5,0.5);\ndist_coords.x=0.5+direction.x*radius2*1.0;\ndist_coords.y=0.5+direction.y*radius2*1.0;\nfloat dist_amount=clamp(distortion*0.23,0.0,1.0);\ndist_coords=mix(coords,dist_coords,dist_amount);\nreturn dist_coords;\n}\n\nfloat sampleScreen(inout vec4 color,const in vec2 offset,const in float weight) {\n\nvec2 coords=distorted_coords;\nfloat angle=rand(coords*100.0).x*TWOPI;\ncoords+=vec2(offset.x*cos(angle)-offset.y*sin(angle),offset.x*sin(angle)+offset.y*cos(angle));\ncolor+=texture2D(textureSampler,coords)*weight;\nreturn weight;\n}\n\nfloat getBlurLevel(float size) {\nreturn min(3.0,ceil(size/1.0));\n}\n\nvec4 getBlurColor(float size) {\nvec4 col=texture2D(textureSampler,distorted_coords);\nif (size == 0.0) { return col; }\n\n\nfloat blur_level=getBlurLevel(size);\nfloat w=(size/screen_width);\nfloat h=(size/screen_height);\nfloat total_weight=1.0;\nvec2 sample_coords;\ntotal_weight+=sampleScreen(col,vec2(-0.50*w,0.24*h),0.93);\ntotal_weight+=sampleScreen(col,vec2(0.30*w,-0.75*h),0.90);\ntotal_weight+=sampleScreen(col,vec2(0.36*w,0.96*h),0.87);\ntotal_weight+=sampleScreen(col,vec2(-1.08*w,-0.55*h),0.85);\ntotal_weight+=sampleScreen(col,vec2(1.33*w,-0.37*h),0.83);\ntotal_weight+=sampleScreen(col,vec2(-0.82*w,1.31*h),0.80);\ntotal_weight+=sampleScreen(col,vec2(-0.31*w,-1.67*h),0.78);\ntotal_weight+=sampleScreen(col,vec2(1.47*w,1.11*h),0.76);\ntotal_weight+=sampleScreen(col,vec2(-1.97*w,0.19*h),0.74);\ntotal_weight+=sampleScreen(col,vec2(1.42*w,-1.57*h),0.72);\nif (blur_level>1.0) {\ntotal_weight+=sampleScreen(col,vec2(0.01*w,2.25*h),0.70);\ntotal_weight+=sampleScreen(col,vec2(-1.62*w,-1.74*h),0.67);\ntotal_weight+=sampleScreen(col,vec2(2.49*w,0.20*h),0.65);\ntotal_weight+=sampleScreen(col,vec2(-2.07*w,1.61*h),0.63);\ntotal_weight+=sampleScreen(col,vec2(0.46*w,-2.70*h),0.61);\ntotal_weight+=sampleScreen(col,vec2(1.55*w,2.40*h),0.59);\ntotal_weight+=sampleScreen(col,vec2(-2.88*w,-0.75*h),0.56);\ntotal_weight+=sampleScreen(col,vec2(2.73*w,-1.44*h),0.54);\ntotal_weight+=sampleScreen(col,vec2(-1.08*w,3.02*h),0.52);\ntotal_weight+=sampleScreen(col,vec2(-1.28*w,-3.05*h),0.49);\n}\nif (blur_level>2.0) {\ntotal_weight+=sampleScreen(col,vec2(3.11*w,1.43*h),0.46);\ntotal_weight+=sampleScreen(col,vec2(-3.36*w,1.08*h),0.44);\ntotal_weight+=sampleScreen(col,vec2(1.80*w,-3.16*h),0.41);\ntotal_weight+=sampleScreen(col,vec2(0.83*w,3.65*h),0.38);\ntotal_weight+=sampleScreen(col,vec2(-3.16*w,-2.19*h),0.34);\ntotal_weight+=sampleScreen(col,vec2(3.92*w,-0.53*h),0.31);\ntotal_weight+=sampleScreen(col,vec2(-2.59*w,3.12*h),0.26);\ntotal_weight+=sampleScreen(col,vec2(-0.20*w,-4.15*h),0.22);\ntotal_weight+=sampleScreen(col,vec2(3.02*w,3.00*h),0.15);\n}\ncol/=total_weight; \n\nif (darken>0.0) {\ncol.rgb*=clamp(0.3,1.0,1.05-size*0.5*darken);\n}\n\n\n\n\nreturn col;\n}\nvoid main(void)\n{\n\ncentered_screen_pos=vec2(vUV.x-0.5,vUV.y-0.5);\nradius2=centered_screen_pos.x*centered_screen_pos.x+centered_screen_pos.y*centered_screen_pos.y;\nradius=sqrt(radius2);\ndistorted_coords=getDistortedCoords(vUV); \nvec2 texels_coords=vec2(vUV.x*screen_width,vUV.y*screen_height); \nfloat depth=texture2D(depthSampler,distorted_coords).r; \nfloat distance=near+(far-near)*depth; \nvec4 color=texture2D(textureSampler,vUV); \n\n\nfloat coc=abs(aperture*(screen_distance*(inverse_focal_length-1.0/distance)-1.0));\n\nif (dof_enabled == false || coc<0.07) { coc=0.0; }\n\nfloat edge_blur_amount=0.0;\nif (edge_blur>0.0) {\nedge_blur_amount=clamp((radius*2.0-1.0+0.15*edge_blur)*1.5,0.0,1.0)*1.3;\n}\n\nfloat blur_amount=max(edge_blur_amount,coc);\n\nif (blur_amount == 0.0) {\ngl_FragColor=texture2D(textureSampler,distorted_coords);\n}\nelse {\n\ngl_FragColor=getBlurColor(blur_amount*1.7);\n\nif (highlights) {\ngl_FragColor.rgb+=clamp(coc,0.0,1.0)*texture2D(highlightsSampler,distorted_coords).rgb;\n}\nif (blur_noise) {\n\nvec2 noise=rand(distorted_coords)*0.01*blur_amount;\nvec2 blurred_coord=vec2(distorted_coords.x+noise.x,distorted_coords.y+noise.y);\ngl_FragColor=0.04*texture2D(textureSampler,blurred_coord)+0.96*gl_FragColor;\n}\n}\n\nif (grain_amount>0.0) {\nvec4 grain_color=texture2D(grainSampler,texels_coords*0.003);\ngl_FragColor.rgb+=(-0.5+grain_color.rgb)*0.30*grain_amount;\n}\n}\n","standardPixelShader":"uniform sampler2D textureSampler;\nvarying vec2 vUV;\n#if defined(PASS_POST_PROCESS)\nvoid main(void)\n{\nvec4 color=texture2D(textureSampler,vUV);\ngl_FragColor=color;\n}\n#endif\n#if defined(DOWN_SAMPLE_X4)\nuniform vec2 dsOffsets[16];\nvoid main(void)\n{\nvec4 average=vec4(0.0,0.0,0.0,0.0);\naverage=texture2D(textureSampler,vUV+dsOffsets[0]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[1]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[2]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[3]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[4]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[5]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[6]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[7]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[8]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[9]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[10]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[11]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[12]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[13]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[14]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[15]);\naverage/=16.0;\ngl_FragColor=average;\n}\n#endif\n#if defined(BRIGHT_PASS)\nuniform vec2 dsOffsets[4];\nuniform float brightThreshold;\nvoid main(void)\n{\nvec4 average=vec4(0.0,0.0,0.0,0.0);\naverage=texture2D(textureSampler,vUV+vec2(dsOffsets[0].x,dsOffsets[0].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[1].x,dsOffsets[1].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[2].x,dsOffsets[2].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[3].x,dsOffsets[3].y));\naverage*=0.25;\nfloat luminance=length(average.rgb);\nif (luminance<brightThreshold) {\naverage=vec4(0.0,0.0,0.0,1.0);\n}\ngl_FragColor=average;\n}\n#endif\n#if defined(TEXTURE_ADDER)\nuniform sampler2D otherSampler;\nuniform sampler2D lensSampler;\nuniform float exposure;\nvoid main(void)\n{\nvec3 colour=texture2D(textureSampler,vUV).rgb;\ncolour*=exposure;\nvec3 X=max(vec3(0.0,0.0,0.0),colour-0.004);\nvec3 retColor=(X*(6.2*X+0.5))/(X*(6.2*X+1.7)+0.06);\ncolour=retColor*retColor;\ncolour+=colour*texture2D(lensSampler,vUV).rgb;\nvec4 finalColor=vec4(colour.rgb,1.0)+texture2D(otherSampler,vUV);\ngl_FragColor=finalColor;\n}\n#endif\n#if defined(VLS)\n#define PI 3.1415926535897932384626433832795\nuniform mat4 shadowViewProjection;\nuniform mat4 lightWorld;\nuniform vec3 cameraPosition;\nuniform vec3 sunDirection;\nuniform vec3 sunColor;\nuniform vec2 depthValues;\nuniform float scatteringCoefficient;\nuniform float scatteringPower;\nuniform sampler2D shadowMapSampler;\nuniform sampler2D positionSampler;\nfloat computeScattering(float lightDotView)\n{\nfloat result=1.0-scatteringCoefficient*scatteringCoefficient;\nresult/=(4.0*PI*pow(1.0+scatteringCoefficient*scatteringCoefficient-(2.0*scatteringCoefficient)*lightDotView,1.5));\nreturn result;\n}\nvoid main(void)\n{\n\nvec3 worldPos=texture2D(positionSampler,vUV).rgb;\nvec3 startPosition=cameraPosition;\nvec3 rayVector=worldPos-startPosition;\nfloat rayLength=length(rayVector);\nvec3 rayDirection=rayVector/rayLength;\nfloat stepLength=rayLength/NB_STEPS;\nvec3 stepL=rayDirection*stepLength;\nvec3 currentPosition=startPosition;\nvec3 accumFog=vec3(0.0);\nfor (int i=0; i<int(NB_STEPS); i++)\n{\nvec4 worldInShadowCameraSpace=shadowViewProjection*vec4(currentPosition,1.0);\nfloat depthMetric=(worldInShadowCameraSpace.z+depthValues.x)/(depthValues.y);\nfloat shadowPixelDepth=clamp(depthMetric,0.0,1.0);\nworldInShadowCameraSpace.xyz/=worldInShadowCameraSpace.w;\nworldInShadowCameraSpace.xyz=0.5*worldInShadowCameraSpace.xyz+vec3(0.5);\nfloat shadowMapValue=texture2D(shadowMapSampler,worldInShadowCameraSpace.xy).r;\nif (shadowMapValue>shadowPixelDepth)\naccumFog+=sunColor*computeScattering(dot(rayDirection,sunDirection));\ncurrentPosition+=stepL;\n}\naccumFog/=NB_STEPS;\nvec3 color=accumFog*scatteringPower;\ngl_FragColor=vec4(color*exp(color) ,1.0);\n}\n#endif\n#if defined(VLSMERGE)\nuniform sampler2D originalSampler;\nvoid main(void)\n{\ngl_FragColor=texture2D(originalSampler,vUV)+texture2D(textureSampler,vUV);\n}\n#endif\n#if defined(LUMINANCE)\nuniform vec2 lumOffsets[4];\nvoid main()\n{\nfloat average=0.0;\nvec4 color=vec4(0.0);\nfloat maximum=-1e20;\nvec3 weight=vec3(0.299,0.587,0.114);\nfor (int i=0; i<4; i++)\n{\ncolor=texture2D(textureSampler,vUV+ lumOffsets[i]);\n\nfloat GreyValue=dot(color.rgb,vec3(0.33,0.33,0.33));\n\n#ifdef WEIGHTED_AVERAGE\nfloat GreyValue=dot(color.rgb,weight);\n#endif\n#ifdef BRIGHTNESS\nfloat GreyValue=max(color.r,max(color.g,color.b));\n#endif\n#ifdef HSL_COMPONENT\nfloat GreyValue=0.5*(max(color.r,max(color.g,color.b))+min(color.r,min(color.g,color.b)));\n#endif\n#ifdef MAGNITUDE\nfloat GreyValue=length(color.rgb);\n#endif\nmaximum=max(maximum,GreyValue);\naverage+=(0.25*log(1e-5+GreyValue));\n}\naverage=exp(average);\ngl_FragColor=vec4(average,maximum,0.0,1.0);\n}\n#endif\n#if defined(LUMINANCE_DOWN_SAMPLE)\nuniform vec2 dsOffsets[9];\nuniform float halfDestPixelSize;\n#ifdef FINAL_DOWN_SAMPLER\nvec4 pack(float value) {\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(value*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\n#endif\nvoid main()\n{\nvec4 color=vec4(0.0);\nfloat average=0.0;\nfor (int i=0; i<9; i++)\n{\ncolor=texture2D(textureSampler,vUV+vec2(halfDestPixelSize,halfDestPixelSize)+dsOffsets[i]);\naverage+=color.r;\n}\naverage/=9.0;\n#ifdef FINAL_DOWN_SAMPLER\ngl_FragColor=pack(average);\n#else\ngl_FragColor=vec4(average,average,0.0,1.0);\n#endif\n}\n#endif\n#if defined(HDR)\nuniform sampler2D textureAdderSampler;\nuniform float averageLuminance;\nvoid main()\n{\nvec4 color=texture2D(textureAdderSampler,vUV);\nvec4 adjustedColor=color/averageLuminance;\ncolor=adjustedColor;\ncolor.a=1.0;\ngl_FragColor=color;\n}\n#endif\n#if defined(LENS_FLARE)\n#define GHOSTS 3\nuniform sampler2D lensColorSampler;\nuniform float strength;\nuniform float ghostDispersal;\nuniform float haloWidth;\nuniform vec2 resolution;\nuniform float distortionStrength;\nfloat hash(vec2 p)\n{\nfloat h=dot(p,vec2(127.1,311.7));\nreturn -1.0+2.0*fract(sin(h)*43758.5453123);\n}\nfloat noise(in vec2 p)\n{\nvec2 i=floor(p);\nvec2 f=fract(p);\nvec2 u=f*f*(3.0-2.0*f);\nreturn mix(mix(hash(i+vec2(0.0,0.0)),\nhash(i+vec2(1.0,0.0)),u.x),\nmix(hash(i+vec2(0.0,1.0)),\nhash(i+vec2(1.0,1.0)),u.x),u.y);\n}\nfloat fbm(vec2 p)\n{\nfloat f=0.0;\nf+=0.5000*noise(p); p*=2.02;\nf+=0.2500*noise(p); p*=2.03;\nf+=0.1250*noise(p); p*=2.01;\nf+=0.0625*noise(p); p*=2.04;\nf/=0.9375;\nreturn f;\n}\nvec3 pattern(vec2 uv)\n{\nvec2 p=-1.0+2.0*uv;\nfloat p2=dot(p,p);\nfloat f=fbm(vec2(15.0*p2))/2.0;\nfloat r=0.2+0.6*sin(12.5*length(uv-vec2(0.5)));\nfloat g=0.2+0.6*sin(20.5*length(uv-vec2(0.5)));\nfloat b=0.2+0.6*sin(17.2*length(uv-vec2(0.5)));\nreturn (1.0-f)*vec3(r,g,b);\n}\nfloat luminance(vec3 color)\n{\nreturn dot(color.rgb,vec3(0.2126,0.7152,0.0722));\n}\nvec4 textureDistorted(sampler2D tex,vec2 texcoord,vec2 direction,vec3 distortion)\n{\nreturn vec4(\ntexture2D(tex,texcoord+direction*distortion.r).r,\ntexture2D(tex,texcoord+direction*distortion.g).g,\ntexture2D(tex,texcoord+direction*distortion.b).b,\n1.0\n);\n}\nvoid main(void)\n{\nvec2 uv=-vUV+vec2(1.0);\nvec2 ghostDir=(vec2(0.5)-uv)*ghostDispersal;\nvec2 texelSize=1.0/resolution;\nvec3 distortion=vec3(-texelSize.x*distortionStrength,0.0,texelSize.x*distortionStrength);\nvec4 result=vec4(0.0);\nfloat ghostIndice=1.0;\nfor (int i=0; i<GHOSTS; ++i)\n{\nvec2 offset=fract(uv+ghostDir*ghostIndice);\nfloat weight=length(vec2(0.5)-offset)/length(vec2(0.5));\nweight=pow(1.0-weight,10.0);\nresult+=textureDistorted(textureSampler,offset,normalize(ghostDir),distortion)*weight*strength;\nghostIndice+=1.0;\n}\nvec2 haloVec=normalize(ghostDir)*haloWidth;\nfloat weight=length(vec2(0.5)-fract(uv+haloVec))/length(vec2(0.5));\nweight=pow(1.0-weight,10.0);\nresult+=textureDistorted(textureSampler,fract(uv+haloVec),normalize(ghostDir),distortion)*weight*strength;\nresult*=texture2D(lensColorSampler,vec2(length(vec2(0.5)-uv)/length(vec2(0.5))));\ngl_FragColor=result;\n}\n#endif\n#if defined(LENS_FLARE_COMPOSE)\nuniform sampler2D otherSampler;\nuniform sampler2D lensDirtSampler;\nuniform sampler2D lensStarSampler;\nuniform mat4 lensStarMatrix;\nvoid main(void)\n{\nvec2 lensFlareCoords=(lensStarMatrix*vec4(vUV,1.0,1.0)).xy;\nvec4 lensMod=texture2D(lensDirtSampler,vUV);\nlensMod+=texture2D(lensStarSampler,vUV);\nvec4 result=texture2D(textureSampler,vUV)*lensMod;\ngl_FragColor=texture2D(otherSampler,vUV)+result;\n}\n#endif\n#if defined(DEPTH_OF_FIELD)\nuniform sampler2D otherSampler;\nuniform sampler2D depthSampler;\nuniform float distance;\nvoid main(void)\n{\nvec4 sharp=texture2D(otherSampler,vUV);\nvec4 blur=texture2D(textureSampler,vUV);\nfloat dist=clamp(texture2D(depthSampler,vUV).r*distance,0.0,1.0);\nfloat factor=0.0;\nif (dist<0.05)\nfactor=1.0;\nelse if (dist<0.1)\nfactor=20.0*(0.1-dist);\nelse if (dist<0.5)\nfactor=0.0;\nelse\nfactor=2.0*(dist-0.5);\nfactor=clamp(factor,0.0,0.90);\ngl_FragColor=mix(sharp,blur,factor);\n}\n#endif\n#if defined(MOTION_BLUR)\nuniform mat4 inverseViewProjection;\nuniform mat4 prevViewProjection;\nuniform vec2 screenSize;\nuniform float motionScale;\nuniform float motionStrength;\nuniform sampler2D depthSampler;\nvoid main(void)\n{\nvec2 texelSize=1.0/screenSize;\nfloat depth=texture2D(depthSampler,vUV).r;\nvec4 cpos=vec4(vUV*2.0-1.0,depth,1.0);\ncpos=cpos*inverseViewProjection;\nvec4 ppos=cpos*prevViewProjection;\nppos.xyz/=ppos.w;\nppos.xy=ppos.xy*0.5+0.5;\nvec2 velocity=(ppos.xy-vUV)*motionScale*motionStrength;\nfloat speed=length(velocity/texelSize);\nint nSamples=int(clamp(speed,1.0,MAX_MOTION_SAMPLES));\nvec4 result=texture2D(textureSampler,vUV);\nfor (int i=1; i<int(MAX_MOTION_SAMPLES); ++i) {\nif (i>=nSamples)\nbreak;\nvec2 offset1=vUV+velocity*(float(i)/float(nSamples-1)-0.5);\nresult+=texture2D(textureSampler,offset1);\n}\ngl_FragColor=result/float(nSamples);\n}\n#endif\n","fxaaVertexShader":"\nattribute vec2 position;\nuniform vec2 texelSize;\n\nvarying vec2 vUV;\nvarying vec2 sampleCoordS;\nvarying vec2 sampleCoordE;\nvarying vec2 sampleCoordN;\nvarying vec2 sampleCoordW;\nvarying vec2 sampleCoordNW;\nvarying vec2 sampleCoordSE;\nvarying vec2 sampleCoordNE;\nvarying vec2 sampleCoordSW;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=(position*madd+madd);\nsampleCoordS=vUV+vec2( 0.0,1.0)*texelSize;\nsampleCoordE=vUV+vec2( 1.0,0.0)*texelSize;\nsampleCoordN=vUV+vec2( 0.0,-1.0)*texelSize;\nsampleCoordW=vUV+vec2(-1.0,0.0)*texelSize;\nsampleCoordNW=vUV+vec2(-1.0,-1.0)*texelSize;\nsampleCoordSE=vUV+vec2( 1.0,1.0)*texelSize;\nsampleCoordNE=vUV+vec2( 1.0,-1.0)*texelSize;\nsampleCoordSW=vUV+vec2(-1.0,1.0)*texelSize;\ngl_Position=vec4(position,0.0,1.0);\n}","fxaaPixelShader":"uniform sampler2D textureSampler;\nuniform vec2 texelSize;\nvarying vec2 vUV;\nvarying vec2 sampleCoordS;\nvarying vec2 sampleCoordE;\nvarying vec2 sampleCoordN;\nvarying vec2 sampleCoordW;\nvarying vec2 sampleCoordNW;\nvarying vec2 sampleCoordSE;\nvarying vec2 sampleCoordNE;\nvarying vec2 sampleCoordSW;\nconst float fxaaQualitySubpix=1.0;\nconst float fxaaQualityEdgeThreshold=0.166;\nconst float fxaaQualityEdgeThresholdMin=0.0833;\nconst vec3 kLumaCoefficients=vec3(0.2126,0.7152,0.0722);\n#define FxaaLuma(rgba) dot(rgba.rgb,kLumaCoefficients)\nvoid main(){\nvec2 posM;\nposM.x=vUV.x;\nposM.y=vUV.y;\nvec4 rgbyM=texture2D(textureSampler,vUV,0.0);\nfloat lumaM=FxaaLuma(rgbyM);\nfloat lumaS=FxaaLuma(texture2D(textureSampler,sampleCoordS,0.0));\nfloat lumaE=FxaaLuma(texture2D(textureSampler,sampleCoordE,0.0));\nfloat lumaN=FxaaLuma(texture2D(textureSampler,sampleCoordN,0.0));\nfloat lumaW=FxaaLuma(texture2D(textureSampler,sampleCoordW,0.0));\nfloat maxSM=max(lumaS,lumaM);\nfloat minSM=min(lumaS,lumaM);\nfloat maxESM=max(lumaE,maxSM);\nfloat minESM=min(lumaE,minSM);\nfloat maxWN=max(lumaN,lumaW);\nfloat minWN=min(lumaN,lumaW);\nfloat rangeMax=max(maxWN,maxESM);\nfloat rangeMin=min(minWN,minESM);\nfloat rangeMaxScaled=rangeMax*fxaaQualityEdgeThreshold;\nfloat range=rangeMax-rangeMin;\nfloat rangeMaxClamped=max(fxaaQualityEdgeThresholdMin,rangeMaxScaled);\n#ifndef MALI\nif(range<rangeMaxClamped) \n{\ngl_FragColor=rgbyM;\nreturn;\n}\n#endif\nfloat lumaNW=FxaaLuma(texture2D(textureSampler,sampleCoordNW,0.0));\nfloat lumaSE=FxaaLuma(texture2D(textureSampler,sampleCoordSE,0.0));\nfloat lumaNE=FxaaLuma(texture2D(textureSampler,sampleCoordNE,0.0));\nfloat lumaSW=FxaaLuma(texture2D(textureSampler,sampleCoordSW,0.0));\nfloat lumaNS=lumaN+lumaS;\nfloat lumaWE=lumaW+lumaE;\nfloat subpixRcpRange=1.0/range;\nfloat subpixNSWE=lumaNS+lumaWE;\nfloat edgeHorz1=(-2.0*lumaM)+lumaNS;\nfloat edgeVert1=(-2.0*lumaM)+lumaWE;\nfloat lumaNESE=lumaNE+lumaSE;\nfloat lumaNWNE=lumaNW+lumaNE;\nfloat edgeHorz2=(-2.0*lumaE)+lumaNESE;\nfloat edgeVert2=(-2.0*lumaN)+lumaNWNE;\nfloat lumaNWSW=lumaNW+lumaSW;\nfloat lumaSWSE=lumaSW+lumaSE;\nfloat edgeHorz4=(abs(edgeHorz1)*2.0)+abs(edgeHorz2);\nfloat edgeVert4=(abs(edgeVert1)*2.0)+abs(edgeVert2);\nfloat edgeHorz3=(-2.0*lumaW)+lumaNWSW;\nfloat edgeVert3=(-2.0*lumaS)+lumaSWSE;\nfloat edgeHorz=abs(edgeHorz3)+edgeHorz4;\nfloat edgeVert=abs(edgeVert3)+edgeVert4;\nfloat subpixNWSWNESE=lumaNWSW+lumaNESE;\nfloat lengthSign=texelSize.x;\nbool horzSpan=edgeHorz>=edgeVert;\nfloat subpixA=subpixNSWE*2.0+subpixNWSWNESE;\nif (!horzSpan)\n{\nlumaN=lumaW;\n}\nif (!horzSpan) \n{\nlumaS=lumaE;\n}\nif (horzSpan) \n{\nlengthSign=texelSize.y;\n}\nfloat subpixB=(subpixA*(1.0/12.0))-lumaM;\nfloat gradientN=lumaN-lumaM;\nfloat gradientS=lumaS-lumaM;\nfloat lumaNN=lumaN+lumaM;\nfloat lumaSS=lumaS+lumaM;\nbool pairN=abs(gradientN)>=abs(gradientS);\nfloat gradient=max(abs(gradientN),abs(gradientS));\nif (pairN)\n{\nlengthSign=-lengthSign;\n}\nfloat subpixC=clamp(abs(subpixB)*subpixRcpRange,0.0,1.0);\nvec2 posB;\nposB.x=posM.x;\nposB.y=posM.y;\nvec2 offNP;\noffNP.x=(!horzSpan) ? 0.0 : texelSize.x;\noffNP.y=(horzSpan) ? 0.0 : texelSize.y;\nif (!horzSpan) \n{\nposB.x+=lengthSign*0.5;\n}\nif (horzSpan)\n{\nposB.y+=lengthSign*0.5;\n}\nvec2 posN;\nposN.x=posB.x-offNP.x*1.5;\nposN.y=posB.y-offNP.y*1.5;\nvec2 posP;\nposP.x=posB.x+offNP.x*1.5;\nposP.y=posB.y+offNP.y*1.5;\nfloat subpixD=((-2.0)*subpixC)+3.0;\nfloat lumaEndN=FxaaLuma(texture2D(textureSampler,posN,0.0));\nfloat subpixE=subpixC*subpixC;\nfloat lumaEndP=FxaaLuma(texture2D(textureSampler,posP,0.0));\nif (!pairN) \n{\nlumaNN=lumaSS;\n}\nfloat gradientScaled=gradient*1.0/4.0;\nfloat lumaMM=lumaM-lumaNN*0.5;\nfloat subpixF=subpixD*subpixE;\nbool lumaMLTZero=lumaMM<0.0;\nlumaEndN-=lumaNN*0.5;\nlumaEndP-=lumaNN*0.5;\nbool doneN=abs(lumaEndN)>=gradientScaled;\nbool doneP=abs(lumaEndP)>=gradientScaled;\nif (!doneN) \n{\nposN.x-=offNP.x*3.0;\n}\nif (!doneN) \n{\nposN.y-=offNP.y*3.0;\n}\nbool doneNP=(!doneN) || (!doneP);\nif (!doneP) \n{\nposP.x+=offNP.x*3.0;\n}\nif (!doneP)\n{\nposP.y+=offNP.y*3.0;\n}\nif (doneNP)\n{\nif (!doneN) lumaEndN=FxaaLuma(texture2D(textureSampler,posN.xy,0.0));\nif (!doneP) lumaEndP=FxaaLuma(texture2D(textureSampler,posP.xy,0.0));\nif (!doneN) lumaEndN=lumaEndN-lumaNN*0.5;\nif (!doneP) lumaEndP=lumaEndP-lumaNN*0.5;\ndoneN=abs(lumaEndN)>=gradientScaled;\ndoneP=abs(lumaEndP)>=gradientScaled;\nif (!doneN) posN.x-=offNP.x*12.0;\nif (!doneN) posN.y-=offNP.y*12.0;\ndoneNP=(!doneN) || (!doneP);\nif (!doneP) posP.x+=offNP.x*12.0;\nif (!doneP) posP.y+=offNP.y*12.0;\n}\nfloat dstN=posM.x-posN.x;\nfloat dstP=posP.x-posM.x;\nif (!horzSpan)\n{\ndstN=posM.y-posN.y;\n}\nif (!horzSpan) \n{\ndstP=posP.y-posM.y;\n}\nbool goodSpanN=(lumaEndN<0.0) != lumaMLTZero;\nfloat spanLength=(dstP+dstN);\nbool goodSpanP=(lumaEndP<0.0) != lumaMLTZero;\nfloat spanLengthRcp=1.0/spanLength;\nbool directionN=dstN<dstP;\nfloat dst=min(dstN,dstP);\nbool goodSpan=directionN ? goodSpanN : goodSpanP;\nfloat subpixG=subpixF*subpixF;\nfloat pixelOffset=(dst*(-spanLengthRcp))+0.5;\nfloat subpixH=subpixG*fxaaQualitySubpix;\nfloat pixelOffsetGood=goodSpan ? pixelOffset : 0.0;\nfloat pixelOffsetSubpix=max(pixelOffsetGood,subpixH);\nif (!horzSpan)\n{\nposM.x+=pixelOffsetSubpix*lengthSign;\n}\nif (horzSpan)\n{\nposM.y+=pixelOffsetSubpix*lengthSign;\n}\n#ifdef MALI\nif(range<rangeMaxClamped) \n{\ngl_FragColor=rgbyM;\n}\nelse\n{\ngl_FragColor=texture2D(textureSampler,posM,0.0);\n}\n#else\ngl_FragColor=texture2D(textureSampler,posM,0.0);\n#endif\n}","chromaticAberrationPixelShader":"\nuniform sampler2D textureSampler; \n\nuniform float chromatic_aberration;\nuniform float radialIntensity;\nuniform vec2 direction;\nuniform vec2 centerPosition;\nuniform float screen_width;\nuniform float screen_height;\n\nvarying vec2 vUV;\nvoid main(void)\n{\nvec2 centered_screen_pos=vec2(vUV.x-centerPosition.x,vUV.y-centerPosition.y);\nvec2 directionOfEffect=direction;\nif(directionOfEffect.x == 0. && directionOfEffect.y == 0.){\ndirectionOfEffect=normalize(centered_screen_pos);\n}\nfloat radius2=centered_screen_pos.x*centered_screen_pos.x\n+centered_screen_pos.y*centered_screen_pos.y;\nfloat radius=sqrt(radius2);\nvec4 original=texture2D(textureSampler,vUV);\n\nvec3 ref_indices=vec3(-0.3,0.0,0.3);\nfloat ref_shiftX=chromatic_aberration*pow(radius,radialIntensity)*directionOfEffect.x/screen_width;\nfloat ref_shiftY=chromatic_aberration*pow(radius,radialIntensity)*directionOfEffect.y/screen_height;\n\nvec2 ref_coords_r=vec2(vUV.x+ref_indices.r*ref_shiftX,vUV.y+ref_indices.r*ref_shiftY*0.5);\nvec2 ref_coords_g=vec2(vUV.x+ref_indices.g*ref_shiftX,vUV.y+ref_indices.g*ref_shiftY*0.5);\nvec2 ref_coords_b=vec2(vUV.x+ref_indices.b*ref_shiftX,vUV.y+ref_indices.b*ref_shiftY*0.5);\noriginal.r=texture2D(textureSampler,ref_coords_r).r;\noriginal.g=texture2D(textureSampler,ref_coords_g).g;\noriginal.b=texture2D(textureSampler,ref_coords_b).b;\noriginal.a=clamp(texture2D(textureSampler,ref_coords_r).a+texture2D(textureSampler,ref_coords_g).a+texture2D(textureSampler,ref_coords_b).a,0.,1.);\ngl_FragColor=original;\n}","grainPixelShader":"#include<helperFunctions>\n\nuniform sampler2D textureSampler; \n\nuniform float intensity;\nuniform float animatedSeed;\n\nvarying vec2 vUV;\nvoid main(void)\n{\ngl_FragColor=texture2D(textureSampler,vUV);\nvec2 seed=vUV*(animatedSeed);\nfloat grain=dither(seed,intensity);\n\nfloat lum=getLuminance(gl_FragColor.rgb);\nfloat grainAmount=(cos(-PI+(lum*PI*2.))+1.)/2.;\ngl_FragColor.rgb+=grain*grainAmount;\ngl_FragColor.rgb=max(gl_FragColor.rgb,0.0);\n}","sharpenPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 screenSize;\nuniform vec2 sharpnessAmounts;\nvoid main(void)\n{\nvec2 onePixel=vec2(1.0,1.0)/screenSize;\nvec4 color=texture2D(textureSampler,vUV);\nvec4 edgeDetection=texture2D(textureSampler,vUV+onePixel*vec2(0,-1)) +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,0)) +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,0)) +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,1)) -\ncolor*4.0;\ngl_FragColor=max(vec4(color.rgb*sharpnessAmounts.y,color.a)-(sharpnessAmounts.x*vec4(edgeDetection.rgb,0)),0.);\n}","kernelBlurVertexShader":"\nattribute vec2 position;\n\nuniform vec2 delta;\n\nvarying vec2 sampleCenter;\n#include<kernelBlurVaryingDeclaration>[0..varyingCount]\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nsampleCenter=(position*madd+madd);\n#include<kernelBlurVertex>[0..varyingCount]\ngl_Position=vec4(position,0.0,1.0);\n}","kernelBlurPixelShader":"\nuniform sampler2D textureSampler;\nuniform vec2 delta;\n\nvarying vec2 sampleCenter;\n#ifdef DOF\nuniform sampler2D circleOfConfusionSampler;\nuniform vec2 cameraMinMaxZ;\nfloat sampleDistance(const in vec2 offset) {\nfloat depth=texture2D(circleOfConfusionSampler,offset).g; \nreturn cameraMinMaxZ.x+(cameraMinMaxZ.y-cameraMinMaxZ.x)*depth; \n}\nfloat sampleCoC(const in vec2 offset) {\nfloat coc=texture2D(circleOfConfusionSampler,offset).r; \nreturn coc; \n}\n#endif\n#include<kernelBlurVaryingDeclaration>[0..varyingCount]\n#ifdef PACKEDFLOAT\nvec4 pack(float depth)\n{\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(depth*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\nfloat unpack(vec4 color)\n{\nconst vec4 bit_shift=vec4(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);\nreturn dot(color,bit_shift);\n}\n#endif\nvoid main(void)\n{\nfloat computedWeight=0.0;\n#ifdef PACKEDFLOAT \nfloat blend=0.;\n#else\nvec4 blend=vec4(0.);\n#endif\n#ifdef DOF\nfloat sumOfWeights=CENTER_WEIGHT; \nfloat factor=0.0;\n\n#ifdef PACKEDFLOAT\nblend+=unpack(texture2D(textureSampler,sampleCenter))*CENTER_WEIGHT;\n#else\nblend+=texture2D(textureSampler,sampleCenter)*CENTER_WEIGHT;\n#endif\n#endif\n#include<kernelBlurFragment>[0..varyingCount]\n#include<kernelBlurFragment2>[0..depCount]\n#ifdef PACKEDFLOAT\ngl_FragColor=pack(blend);\n#else\ngl_FragColor=blend;\n#endif\n#ifdef DOF\ngl_FragColor/=sumOfWeights;\n#endif\n}","depthOfFieldMergePixelShader":"uniform sampler2D textureSampler;\nvarying vec2 vUV;\nuniform sampler2D circleOfConfusionSampler;\nuniform sampler2D blurStep0;\n#if BLUR_LEVEL>0\nuniform sampler2D blurStep1;\n#endif\n#if BLUR_LEVEL>1\nuniform sampler2D blurStep2;\n#endif\nvoid main(void)\n{\nfloat coc=texture2D(circleOfConfusionSampler,vUV).r;\n#if BLUR_LEVEL == 0\nvec4 original=texture2D(textureSampler,vUV);\nvec4 blurred0=texture2D(blurStep0,vUV);\ngl_FragColor=mix(original,blurred0,coc);\n#endif\n#if BLUR_LEVEL == 1\nif(coc<0.5){\nvec4 original=texture2D(textureSampler,vUV);\nvec4 blurred1=texture2D(blurStep1,vUV);\ngl_FragColor=mix(original,blurred1,coc/0.5);\n}else{\nvec4 blurred0=texture2D(blurStep0,vUV); \nvec4 blurred1=texture2D(blurStep1,vUV);\ngl_FragColor=mix(blurred1,blurred0,(coc-0.5)/0.5);\n}\n#endif\n#if BLUR_LEVEL == 2\nif(coc<0.33){\nvec4 original=texture2D(textureSampler,vUV);\nvec4 blurred2=texture2D(blurStep2,vUV);\ngl_FragColor=mix(original,blurred2,coc/0.33);\n}else if(coc<0.66){\nvec4 blurred1=texture2D(blurStep1,vUV);\nvec4 blurred2=texture2D(blurStep2,vUV);\ngl_FragColor=mix(blurred2,blurred1,(coc-0.33)/0.33);\n}else{\nvec4 blurred0=texture2D(blurStep0,vUV);\nvec4 blurred1=texture2D(blurStep1,vUV);\ngl_FragColor=mix(blurred1,blurred0,(coc-0.66)/0.34);\n}\n#endif\n}\n","circleOfConfusionPixelShader":"\nuniform sampler2D depthSampler;\n\nvarying vec2 vUV;\n\nuniform vec2 cameraMinMaxZ;\n\nuniform float focusDistance;\nuniform float cocPrecalculation;\nvoid main(void)\n{\nfloat depth=texture2D(depthSampler,vUV).r;\nfloat pixelDistance=(cameraMinMaxZ.x+(cameraMinMaxZ.y-cameraMinMaxZ.x)*depth)*1000.0; \nfloat coc=abs(cocPrecalculation* ((focusDistance-pixelDistance)/pixelDistance));\ncoc=clamp(coc,0.0,1.0);\ngl_FragColor=vec4(coc,depth,coc,1.0);\n}\n","bloomMergePixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D bloomBlur;\nvarying vec2 vUV;\nuniform float bloomWeight;\nvoid main(void)\n{\ngl_FragColor=texture2D(textureSampler,vUV);\nvec3 blurred=texture2D(bloomBlur,vUV).rgb;\ngl_FragColor.rgb=gl_FragColor.rgb+(blurred.rgb*bloomWeight); \n}\n","extractHighlightsPixelShader":"#include<helperFunctions>\n\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform float threshold;\nuniform float exposure;\nvoid main(void) \n{\ngl_FragColor=texture2D(textureSampler,vUV);\nfloat luma=getLuminance(gl_FragColor.rgb*exposure);\ngl_FragColor.rgb=step(threshold,luma)*gl_FragColor.rgb;\n}","geometryVertexShader":"precision highp float;\nprecision highp int;\n#include<bonesDeclaration>\n#include<instancesDeclaration>\nattribute vec3 position;\nattribute vec3 normal;\n#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nvarying vec2 uv;\n#endif\n#ifdef UV2\nvarying vec2 uv2;\n#endif\n#endif\n\nuniform mat4 viewProjection;\nuniform mat4 view;\nvarying vec3 vNormalV;\nvarying vec4 vViewPos;\n#ifdef POSITION\nvarying vec3 vPosition;\n#endif\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\nvec4 pos=vec4(finalWorld*vec4(position,1.0));\nvNormalV=normalize(vec3((view*finalWorld)*vec4(normal,0.0)));\nvViewPos=view*pos;\n#ifdef POSITION\nvPosition=pos.xyz/pos.w;\n#endif\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","geometryPixelShader":"#extension GL_EXT_draw_buffers : require\nprecision highp float;\nprecision highp int;\nvarying vec3 vNormalV;\nvarying vec4 vViewPos;\n#ifdef POSITION\nvarying vec3 vPosition;\n#endif\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef POSITION\n#include<mrtFragmentDeclaration>[3]\n#else\n#include<mrtFragmentDeclaration>[2]\n#endif\nvoid main() {\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\ngl_FragData[0]=vec4(vViewPos.z/vViewPos.w,0.0,0.0,1.0);\n\ngl_FragData[1]=vec4(normalize(vNormalV),1.0);\n\n#ifdef POSITION\ngl_FragData[2]=vec4(vPosition,1.0);\n#endif\n}","refractionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D refractionSampler;\n\nuniform vec3 baseColor;\nuniform float depth;\nuniform float colorLevel;\nvoid main() {\nfloat ref=1.0-texture2D(refractionSampler,vUV).r;\nvec2 uv=vUV-vec2(0.5);\nvec2 offset=uv*depth*ref;\nvec3 sourceColor=texture2D(textureSampler,vUV-offset).rgb;\ngl_FragColor=vec4(sourceColor+sourceColor*ref*colorLevel,1.0);\n}","blackAndWhitePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform float degree;\nvoid main(void) \n{\nvec3 color=texture2D(textureSampler,vUV).rgb;\nfloat luminance=dot(color,vec3(0.3,0.59,0.11)); \nvec3 blackAndWhite=vec3(luminance,luminance,luminance);\ngl_FragColor=vec4(color-((color-blackAndWhite)*degree),1.0);\n}","convolutionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 screenSize;\nuniform float kernel[9];\nvoid main(void)\n{\nvec2 onePixel=vec2(1.0,1.0)/screenSize;\nvec4 colorSum =\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,-1))*kernel[0] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,-1))*kernel[1] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,-1))*kernel[2] +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,0))*kernel[3] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,0))*kernel[4] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,0))*kernel[5] +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,1))*kernel[6] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,1))*kernel[7] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,1))*kernel[8];\nfloat kernelWeight =\nkernel[0] +\nkernel[1] +\nkernel[2] +\nkernel[3] +\nkernel[4] +\nkernel[5] +\nkernel[6] +\nkernel[7] +\nkernel[8];\nif (kernelWeight<=0.0) {\nkernelWeight=1.0;\n}\ngl_FragColor=vec4((colorSum/kernelWeight).rgb,1);\n}","filterPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform mat4 kernelMatrix;\nvoid main(void)\n{\nvec3 baseColor=texture2D(textureSampler,vUV).rgb;\nvec3 updatedColor=(kernelMatrix*vec4(baseColor,1.0)).rgb;\ngl_FragColor=vec4(updatedColor,1.0);\n}","volumetricLightScatteringPixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D lightScatteringSampler;\nuniform float decay;\nuniform float exposure;\nuniform float weight;\nuniform float density;\nuniform vec2 meshPositionOnScreen;\nvarying vec2 vUV;\nvoid main(void) {\nvec2 tc=vUV;\nvec2 deltaTexCoord=(tc-meshPositionOnScreen.xy);\ndeltaTexCoord*=1.0/float(NUM_SAMPLES)*density;\nfloat illuminationDecay=1.0;\nvec4 color=texture2D(lightScatteringSampler,tc)*0.4;\nfor(int i=0; i<NUM_SAMPLES; i++) {\ntc-=deltaTexCoord;\nvec4 dataSample=texture2D(lightScatteringSampler,tc)*0.4;\ndataSample*=illuminationDecay*weight;\ncolor+=dataSample;\nilluminationDecay*=decay;\n}\nvec4 realColor=texture2D(textureSampler,vUV);\ngl_FragColor=((vec4((vec3(color.r,color.g,color.b)*exposure),1))+(realColor*(1.5-0.4)));\n}\n","volumetricLightScatteringPassPixelShader":"#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\n#endif\n#if defined(ALPHATEST)\nuniform sampler2D diffuseSampler;\n#endif\nvoid main(void)\n{\n#if defined(ALPHATEST)\nvec4 diffuseColor=texture2D(diffuseSampler,vUV);\nif (diffuseColor.a<0.4)\ndiscard;\n#endif\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\n}\n","colorCorrectionPixelShader":"\nuniform sampler2D textureSampler; \nuniform sampler2D colorTable; \n\nvarying vec2 vUV;\n\nconst float SLICE_COUNT=16.0; \n\nvec4 sampleAs3DTexture(sampler2D textureSampler,vec3 uv,float width) {\nfloat sliceSize=1.0/width; \nfloat slicePixelSize=sliceSize/width; \nfloat sliceInnerSize=slicePixelSize*(width-1.0); \nfloat zSlice0=min(floor(uv.z*width),width-1.0);\nfloat zSlice1=min(zSlice0+1.0,width-1.0);\nfloat xOffset=slicePixelSize*0.5+uv.x*sliceInnerSize;\nfloat s0=xOffset+(zSlice0*sliceSize);\nfloat s1=xOffset+(zSlice1*sliceSize);\nvec4 slice0Color=texture2D(textureSampler,vec2(s0,uv.y));\nvec4 slice1Color=texture2D(textureSampler,vec2(s1,uv.y));\nfloat zOffset=mod(uv.z*width,1.0);\nvec4 result=mix(slice0Color,slice1Color,zOffset);\nreturn result;\n}\nvoid main(void)\n{\nvec4 screen_color=texture2D(textureSampler,vUV);\ngl_FragColor=sampleAs3DTexture(colorTable,screen_color.rgb,SLICE_COUNT);\n}","tonemapPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform float _ExposureAdjustment;\n#if defined(HABLE_TONEMAPPING)\nconst float A=0.15;\nconst float B=0.50;\nconst float C=0.10;\nconst float D=0.20;\nconst float E=0.02;\nconst float F=0.30;\nconst float W=11.2;\n#endif\nfloat Luminance(vec3 c)\n{\nreturn dot(c,vec3(0.22,0.707,0.071));\n}\nvoid main(void) \n{\nvec3 colour=texture2D(textureSampler,vUV).rgb;\n#if defined(REINHARD_TONEMAPPING)\nfloat lum=Luminance(colour.rgb); \nfloat lumTm=lum*_ExposureAdjustment;\nfloat scale=lumTm/(1.0+lumTm); \ncolour*=scale/lum;\n#elif defined(HABLE_TONEMAPPING)\ncolour*=_ExposureAdjustment;\nconst float ExposureBias=2.0;\nvec3 x=ExposureBias*colour;\nvec3 curr=((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F;\nx=vec3(W,W,W);\nvec3 whiteScale=1.0/(((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F);\ncolour=curr*whiteScale;\n#elif defined(OPTIMIZED_HEJIDAWSON_TONEMAPPING)\ncolour*=_ExposureAdjustment;\nvec3 X=max(vec3(0.0,0.0,0.0),colour-0.004);\nvec3 retColor=(X*(6.2*X+0.5))/(X*(6.2*X+1.7)+0.06);\ncolour=retColor*retColor;\n#elif defined(PHOTOGRAPHIC_TONEMAPPING)\ncolour=vec3(1.0,1.0,1.0)-exp2(-_ExposureAdjustment*colour);\n#endif\ngl_FragColor=vec4(colour.rgb,1.0);\n}","displayPassPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D passSampler;\nvoid main(void)\n{\ngl_FragColor=texture2D(passSampler,vUV);\n}","highlightsPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nconst vec3 RGBLuminanceCoefficients=vec3(0.2126,0.7152,0.0722);\nvoid main(void) \n{\nvec4 tex=texture2D(textureSampler,vUV);\nvec3 c=tex.rgb;\nfloat luma=dot(c.rgb,RGBLuminanceCoefficients);\n\n\ngl_FragColor=vec4(pow(c,vec3(25.0-luma*15.0)),tex.a); \n}","imageProcessingPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n#include<imageProcessingDeclaration>\n#include<helperFunctions>\n#include<imageProcessingFunctions>\nvoid main(void)\n{\nvec4 result=texture2D(textureSampler,vUV);\n#ifdef IMAGEPROCESSING\n#ifndef FROMLINEARSPACE\n\nresult.rgb=toLinearSpace(result.rgb);\n#endif\nresult=applyImageProcessing(result);\n#else\n\n#ifdef FROMLINEARSPACE\nresult=applyImageProcessing(result);\n#endif\n#endif\ngl_FragColor=result;\n}","lensFlareVertexShader":"\nattribute vec2 position;\n\nuniform mat4 viewportMatrix;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=position*madd+madd;\ngl_Position=viewportMatrix*vec4(position,0.0,1.0);\n}","lensFlarePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec4 color;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\ngl_FragColor=baseColor*color;\n}","anaglyphPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D leftSampler;\nvoid main(void)\n{\nvec4 leftFrag=texture2D(leftSampler,vUV);\nleftFrag=vec4(1.0,leftFrag.g,leftFrag.b,1.0);\nvec4 rightFrag=texture2D(textureSampler,vUV);\nrightFrag=vec4(rightFrag.r,1.0,1.0,1.0);\ngl_FragColor=vec4(rightFrag.rgb*leftFrag.rgb,1.0);\n}","stereoscopicInterlacePixelShader":"const vec3 TWO=vec3(2.0,2.0,2.0);\nvarying vec2 vUV;\nuniform sampler2D camASampler;\nuniform sampler2D textureSampler;\nuniform vec2 stepSize;\nvoid main(void)\n{\nbool useCamB;\nvec2 texCoord1;\nvec2 texCoord2;\nvec3 frag1;\nvec3 frag2;\n#ifdef IS_STEREOSCOPIC_HORIZ\nuseCamB=vUV.x>0.5;\ntexCoord1=vec2(useCamB ? (vUV.x-0.5)*2.0 : vUV.x*2.0,vUV.y);\ntexCoord2=vec2(texCoord1.x+stepSize.x,vUV.y);\n#else\nuseCamB=vUV.y>0.5;\ntexCoord1=vec2(vUV.x,useCamB ? (vUV.y-0.5)*2.0 : vUV.y*2.0);\ntexCoord2=vec2(vUV.x,texCoord1.y+stepSize.y);\n#endif\n\nif (useCamB){\nfrag1=texture2D(textureSampler,texCoord1).rgb;\nfrag2=texture2D(textureSampler,texCoord2).rgb;\n}else{\nfrag1=texture2D(camASampler ,texCoord1).rgb;\nfrag2=texture2D(camASampler ,texCoord2).rgb;\n}\ngl_FragColor=vec4((frag1+frag2)/TWO,1.0);\n}","vrDistortionCorrectionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 LensCenter;\nuniform vec2 Scale;\nuniform vec2 ScaleIn;\nuniform vec4 HmdWarpParam;\nvec2 HmdWarp(vec2 in01) {\nvec2 theta=(in01-LensCenter)*ScaleIn; \nfloat rSq=theta.x*theta.x+theta.y*theta.y;\nvec2 rvector=theta*(HmdWarpParam.x+HmdWarpParam.y*rSq+HmdWarpParam.z*rSq*rSq+HmdWarpParam.w*rSq*rSq*rSq);\nreturn LensCenter+Scale*rvector;\n}\nvoid main(void)\n{\nvec2 tc=HmdWarp(vUV);\nif (tc.x <0.0 || tc.x>1.0 || tc.y<0.0 || tc.y>1.0)\ngl_FragColor=vec4(0.0,0.0,0.0,0.0);\nelse{\ngl_FragColor=texture2D(textureSampler,tc);\n}\n}","glowBlurPostProcessPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec2 screenSize;\nuniform vec2 direction;\nuniform float blurWidth;\n\nfloat getLuminance(vec3 color)\n{\nreturn dot(color,vec3(0.2126,0.7152,0.0722));\n}\nvoid main(void)\n{\nfloat weights[7];\nweights[0]=0.05;\nweights[1]=0.1;\nweights[2]=0.2;\nweights[3]=0.3;\nweights[4]=0.2;\nweights[5]=0.1;\nweights[6]=0.05;\nvec2 texelSize=vec2(1.0/screenSize.x,1.0/screenSize.y);\nvec2 texelStep=texelSize*direction*blurWidth;\nvec2 start=vUV-3.0*texelStep;\nvec4 baseColor=vec4(0.,0.,0.,0.);\nvec2 texelOffset=vec2(0.,0.);\nfor (int i=0; i<7; i++)\n{\n\nvec4 texel=texture2D(textureSampler,start+texelOffset);\nbaseColor.a+=texel.a*weights[i];\n\nfloat luminance=getLuminance(baseColor.rgb);\nfloat luminanceTexel=getLuminance(texel.rgb);\nfloat choice=step(luminanceTexel,luminance);\nbaseColor.rgb=choice*baseColor.rgb+(1.0-choice)*texel.rgb;\ntexelOffset+=texelStep;\n}\ngl_FragColor=baseColor;\n}","glowMapGenerationPixelShader":"#ifdef ALPHATEST\nvarying vec2 vUVDiffuse;\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vUVEmissive;\nuniform sampler2D emissiveSampler;\n#endif\nuniform vec4 color;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUVDiffuse).a<0.4)\ndiscard;\n#endif\n#ifdef EMISSIVE\ngl_FragColor=texture2D(emissiveSampler,vUVEmissive)*color;\n#else\ngl_FragColor=color;\n#endif\n}","glowMapGenerationVertexShader":"\nattribute vec3 position;\n#include<bonesDeclaration>\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\nvarying vec4 vPosition;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef ALPHATEST\nvarying vec2 vUVDiffuse;\nuniform mat4 diffuseMatrix;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vUVEmissive;\nuniform mat4 emissiveMatrix;\n#endif\nvoid main(void)\n{\nvec3 positionUpdated=position;\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#include<instancesVertex>\n#include<bonesVertex>\n#ifdef CUBEMAP\nvPosition=finalWorld*vec4(positionUpdated,1.0);\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#else\nvPosition=viewProjection*finalWorld*vec4(positionUpdated,1.0);\ngl_Position=vPosition;\n#endif\n#ifdef ALPHATEST\n#ifdef DIFFUSEUV1\nvUVDiffuse=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef DIFFUSEUV2\nvUVDiffuse=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n#ifdef EMISSIVE\n#ifdef EMISSIVEUV1\nvUVEmissive=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef EMISSIVEUV2\nvUVEmissive=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","glowMapMergePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n#ifdef EMISSIVE\nuniform sampler2D textureSampler2;\n#endif\n\nuniform float offset;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\n#ifdef EMISSIVE\nbaseColor+=texture2D(textureSampler2,vUV);\nbaseColor*=offset;\n#else\nbaseColor.a=abs(offset-baseColor.a);\n#ifdef STROKE\nfloat alpha=smoothstep(.0,.1,baseColor.a);\nbaseColor.a=alpha;\nbaseColor.rgb=baseColor.rgb*alpha;\n#endif\n#endif\ngl_FragColor=baseColor;\n}","glowMapMergeVertexShader":"\nattribute vec2 position;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) {\nvUV=position*madd+madd;\ngl_Position=vec4(position,0.0,1.0);\n}","lineVertexShader":"\nattribute vec3 position;\nattribute vec4 normal;\n\nuniform mat4 worldViewProjection;\nuniform float width;\nuniform float aspectRatio;\nvoid main(void) {\nvec4 viewPosition=worldViewProjection*vec4(position,1.0);\nvec4 viewPositionNext=worldViewProjection*vec4(normal.xyz,1.0);\nvec2 currentScreen=viewPosition.xy/viewPosition.w;\nvec2 nextScreen=viewPositionNext.xy/viewPositionNext.w;\ncurrentScreen.x*=aspectRatio;\nnextScreen.x*=aspectRatio;\nvec2 dir=normalize(nextScreen-currentScreen);\nvec2 normalDir=vec2(-dir.y,dir.x);\nnormalDir*=width/2.0;\nnormalDir.x/=aspectRatio;\nvec4 offset=vec4(normalDir*normal.w,0.0,0.0);\ngl_Position=viewPosition+offset;\n}","linePixelShader":"uniform vec4 color;\nvoid main(void) {\ngl_FragColor=color;\n}","outlineVertexShader":"\nattribute vec3 position;\nattribute vec3 normal;\n#include<bonesDeclaration>\n\nuniform float offset;\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\n#include<logDepthDeclaration>\nvoid main(void)\n{\nvec3 offsetPosition=position+normal*offset;\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(offsetPosition,1.0);\n#ifdef ALPHATEST\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n#include<logDepthVertex>\n}\n","outlinePixelShader":"#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\nuniform vec4 color;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\n#include<logDepthDeclaration>\nvoid main(void) {\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\n#include<logDepthFragment>\ngl_FragColor=color;\n}","layerVertexShader":"\nattribute vec2 position;\n\nuniform vec2 scale;\nuniform vec2 offset;\nuniform mat4 textureMatrix;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvec2 shiftedPosition=position*scale+offset;\nvUV=vec2(textureMatrix*vec4(shiftedPosition*madd+madd,1.0,0.0));\ngl_Position=vec4(shiftedPosition,0.0,1.0);\n}","layerPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec4 color;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\ngl_FragColor=baseColor*color;\n}","backgroundVertexShader":"precision highp float;\n#include<__decl__backgroundVertex>\n#include<helperFunctions>\n\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2; \n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0\nvarying vec2 vDiffuseUV;\n#endif\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\nvoid main(void) {\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=position;\n#endif \n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\nvec4 worldPos=finalWorld*vec4(position,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvNormalW=normalize(normalWorld*normal);\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(position,0.0)));\n#ifdef EQUIRECTANGULAR_RELFECTION_FOV\nmat3 screenToWorld=inverseMat3(mat3(finalWorld*viewProjection));\nvec3 segment=mix(vDirectionW,screenToWorld*vec3(0.0,0.0,1.0),abs(fFovMultiplier-1.0));\nif (fFovMultiplier<=1.0) {\nvDirectionW=normalize(segment);\n} else {\nvDirectionW=normalize(vDirectionW+(vDirectionW-segment));\n}\n#endif\n#endif\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef MAINUV1\nvMainUV1=uv;\n#endif \n#ifdef MAINUV2\nvMainUV2=uv2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0 \nif (vDiffuseInfos.x == 0.)\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n\n#include<clipPlaneVertex>\n\n#include<fogVertex>\n\n#include<shadowsVertex>[0..maxSimultaneousLights]\n\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n\n#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif\n}\n","backgroundPixelShader":"#ifdef TEXTURELODSUPPORT\n#extension GL_EXT_shader_texture_lod : enable\n#endif\nprecision highp float;\n#include<__decl__backgroundFragment>\n#define RECIPROCAL_PI2 0.15915494\n\nuniform vec3 vEyePosition;\n\nvarying vec3 vPositionW;\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif \n#ifdef MAINUV2 \nvarying vec2 vMainUV2; \n#endif \n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef DIFFUSE\n#if DIFFUSEDIRECTUV == 1\n#define vDiffuseUV vMainUV1\n#elif DIFFUSEDIRECTUV == 2\n#define vDiffuseUV vMainUV2\n#else\nvarying vec2 vDiffuseUV;\n#endif\nuniform sampler2D diffuseSampler;\n#endif\n\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\n#define sampleReflection(s,c) textureCube(s,c)\nuniform samplerCube reflectionSampler;\n#ifdef TEXTURELODSUPPORT\n#define sampleReflectionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#else\n#define sampleReflection(s,c) texture2D(s,c)\nuniform sampler2D reflectionSampler;\n#ifdef TEXTURELODSUPPORT\n#define sampleReflectionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n\n#ifndef FROMLINEARSPACE\n#define FROMLINEARSPACE;\n#endif\n\n#ifndef SHADOWONLY\n#define SHADOWONLY;\n#endif\n#include<imageProcessingDeclaration>\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<helperFunctions>\n#include<lightsFragmentFunctions>\n#include<shadowsFragmentFunctions>\n#include<imageProcessingFunctions>\n#include<clipPlaneFragmentDeclaration>\n\n#include<fogFragmentDeclaration>\n#ifdef REFLECTIONFRESNEL\n#define FRESNEL_MAXIMUM_ON_ROUGH 0.25\nvec3 fresnelSchlickEnvironmentGGX(float VdotN,vec3 reflectance0,vec3 reflectance90,float smoothness)\n{\n\nfloat weight=mix(FRESNEL_MAXIMUM_ON_ROUGH,1.0,smoothness);\nreturn reflectance0+weight*(reflectance90-reflectance0)*pow(clamp(1.0-VdotN,0.,1.),5.0);\n}\n#endif\nvoid main(void) {\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=vec3(0.0,1.0,0.0);\n#endif\n\nfloat shadow=1.;\nfloat globalShadow=0.;\nfloat shadowLightCount=0.;\n#include<lightFragment>[0..maxSimultaneousLights]\n#ifdef SHADOWINUSE\nglobalShadow/=shadowLightCount;\n#else\nglobalShadow=1.0;\n#endif\n\nvec3 reflectionColor=vec3(1.,1.,1.);\n#ifdef REFLECTION\nvec3 reflectionVector=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflectionVector.z*=-1.0;\n#endif\n\n#ifdef REFLECTIONMAP_3D\nvec3 reflectionCoords=reflectionVector;\n#else\nvec2 reflectionCoords=reflectionVector.xy;\n#ifdef REFLECTIONMAP_PROJECTION\nreflectionCoords/=reflectionVector.z;\n#endif\nreflectionCoords.y=1.0-reflectionCoords.y;\n#endif\n#ifdef REFLECTIONBLUR\nfloat reflectionLOD=vReflectionInfos.y;\n#ifdef TEXTURELODSUPPORT\n\nreflectionLOD=reflectionLOD*log2(vReflectionMicrosurfaceInfos.x)*vReflectionMicrosurfaceInfos.y+vReflectionMicrosurfaceInfos.z;\nreflectionColor=sampleReflectionLod(reflectionSampler,reflectionCoords,reflectionLOD).rgb;\n#else\nfloat lodReflectionNormalized=clamp(reflectionLOD,0.,1.);\nfloat lodReflectionNormalizedDoubled=lodReflectionNormalized*2.0;\nvec3 reflectionSpecularMid=sampleReflection(reflectionSampler,reflectionCoords).rgb;\nif(lodReflectionNormalizedDoubled<1.0){\nreflectionColor=mix(\nsampleReflection(reflectionSamplerHigh,reflectionCoords).rgb,\nreflectionSpecularMid,\nlodReflectionNormalizedDoubled\n);\n} else {\nreflectionColor=mix(\nreflectionSpecularMid,\nsampleReflection(reflectionSamplerLow,reflectionCoords).rgb,\nlodReflectionNormalizedDoubled-1.0\n);\n}\n#endif\n#else\nvec4 reflectionSample=sampleReflection(reflectionSampler,reflectionCoords);\nreflectionColor=reflectionSample.rgb;\n#endif\n#ifdef GAMMAREFLECTION\nreflectionColor=toLinearSpace(reflectionColor.rgb);\n#endif\n#ifdef REFLECTIONBGR\nreflectionColor=reflectionColor.bgr;\n#endif\n\nreflectionColor*=vReflectionInfos.x;\n#endif\n\nvec3 diffuseColor=vec3(1.,1.,1.);\nfloat finalAlpha=alpha;\n#ifdef DIFFUSE\nvec4 diffuseMap=texture2D(diffuseSampler,vDiffuseUV);\n#ifdef GAMMADIFFUSE\ndiffuseMap.rgb=toLinearSpace(diffuseMap.rgb);\n#endif\n\ndiffuseMap.rgb*=vDiffuseInfos.y;\n#ifdef DIFFUSEHASALPHA\nfinalAlpha*=diffuseMap.a;\n#endif\ndiffuseColor=diffuseMap.rgb;\n#endif\n\n#ifdef REFLECTIONFRESNEL\nvec3 colorBase=diffuseColor;\n#else\nvec3 colorBase=reflectionColor*diffuseColor;\n#endif\ncolorBase=max(colorBase,0.0);\n\n#ifdef USERGBCOLOR\nvec3 finalColor=colorBase;\n#else\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,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"};
  98761. BABYLON.Effect.IncludesShadersStore={"depthPrePass":"#ifdef DEPTHPREPASS\ngl_FragColor=vec4(0.,0.,0.,1.0);\nreturn;\n#endif","bonesDeclaration":"#if NUM_BONE_INFLUENCERS>0\nuniform mat4 mBones[BonesPerMesh];\nattribute vec4 matricesIndices;\nattribute vec4 matricesWeights;\n#if NUM_BONE_INFLUENCERS>4\nattribute vec4 matricesIndicesExtra;\nattribute vec4 matricesWeightsExtra;\n#endif\n#endif","instancesDeclaration":"#ifdef INSTANCES\nattribute vec4 world0;\nattribute vec4 world1;\nattribute vec4 world2;\nattribute vec4 world3;\n#else\nuniform mat4 world;\n#endif","pointCloudVertexDeclaration":"#ifdef POINTSIZE\nuniform float pointSize;\n#endif","bumpVertexDeclaration":"#if defined(BUMP) || defined(PARALLAX)\n#if defined(TANGENT) && defined(NORMAL) \nvarying mat3 vTBN;\n#endif\n#endif\n","clipPlaneVertexDeclaration":"#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nvarying float fClipDistance;\n#endif","fogVertexDeclaration":"#ifdef FOG\nvarying vec3 vFogDistance;\n#endif","morphTargetsVertexGlobalDeclaration":"#ifdef MORPHTARGETS\nuniform float morphTargetInfluences[NUM_MORPH_INFLUENCERS];\n#endif","morphTargetsVertexDeclaration":"#ifdef MORPHTARGETS\nattribute vec3 position{X};\n#ifdef MORPHTARGETS_NORMAL\nattribute vec3 normal{X};\n#endif\n#ifdef MORPHTARGETS_TANGENT\nattribute vec3 tangent{X};\n#endif\n#endif","logDepthDeclaration":"#ifdef LOGARITHMICDEPTH\nuniform float logarithmicDepthConstant;\nvarying float vFragmentDepth;\n#endif","morphTargetsVertex":"#ifdef MORPHTARGETS\npositionUpdated+=(position{X}-position)*morphTargetInfluences[{X}];\n#ifdef MORPHTARGETS_NORMAL\nnormalUpdated+=(normal{X}-normal)*morphTargetInfluences[{X}];\n#endif\n#ifdef MORPHTARGETS_TANGENT\ntangentUpdated.xyz+=(tangent{X}-tangent.xyz)*morphTargetInfluences[{X}];\n#endif\n#endif","instancesVertex":"#ifdef INSTANCES\nmat4 finalWorld=mat4(world0,world1,world2,world3);\n#else\nmat4 finalWorld=world;\n#endif","bonesVertex":"#if NUM_BONE_INFLUENCERS>0\nmat4 influence;\ninfluence=mBones[int(matricesIndices[0])]*matricesWeights[0];\n#if NUM_BONE_INFLUENCERS>1\ninfluence+=mBones[int(matricesIndices[1])]*matricesWeights[1];\n#endif \n#if NUM_BONE_INFLUENCERS>2\ninfluence+=mBones[int(matricesIndices[2])]*matricesWeights[2];\n#endif \n#if NUM_BONE_INFLUENCERS>3\ninfluence+=mBones[int(matricesIndices[3])]*matricesWeights[3];\n#endif \n#if NUM_BONE_INFLUENCERS>4\ninfluence+=mBones[int(matricesIndicesExtra[0])]*matricesWeightsExtra[0];\n#endif \n#if NUM_BONE_INFLUENCERS>5\ninfluence+=mBones[int(matricesIndicesExtra[1])]*matricesWeightsExtra[1];\n#endif \n#if NUM_BONE_INFLUENCERS>6\ninfluence+=mBones[int(matricesIndicesExtra[2])]*matricesWeightsExtra[2];\n#endif \n#if NUM_BONE_INFLUENCERS>7\ninfluence+=mBones[int(matricesIndicesExtra[3])]*matricesWeightsExtra[3];\n#endif \nfinalWorld=finalWorld*influence;\n#endif","bumpVertex":"#if defined(BUMP) || defined(PARALLAX)\n#if defined(TANGENT) && defined(NORMAL)\nvec3 tbnNormal=normalize(normalUpdated);\nvec3 tbnTangent=normalize(tangentUpdated.xyz);\nvec3 tbnBitangent=cross(tbnNormal,tbnTangent)*tangentUpdated.w;\nvTBN=mat3(finalWorld)*mat3(tbnTangent,tbnBitangent,tbnNormal);\n#endif\n#endif","clipPlaneVertex":"#ifdef CLIPPLANE\nfClipDistance=dot(worldPos,vClipPlane);\n#endif","fogVertex":"#ifdef FOG\nvFogDistance=(view*worldPos).xyz;\n#endif","shadowsVertex":"#ifdef SHADOWS\n#if defined(SHADOW{X}) && !defined(SHADOWCUBE{X})\nvPositionFromLight{X}=lightMatrix{X}*worldPos;\nvDepthMetric{X}=((vPositionFromLight{X}.z+light{X}.depthValues.x)/(light{X}.depthValues.y));\n#endif\n#endif","pointCloudVertex":"#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif","logDepthVertex":"#ifdef LOGARITHMICDEPTH\nvFragmentDepth=1.0+gl_Position.w;\ngl_Position.z=log2(max(0.000001,vFragmentDepth))*logarithmicDepthConstant;\n#endif","helperFunctions":"const float PI=3.1415926535897932384626433832795;\nconst float LinearEncodePowerApprox=2.2;\nconst float GammaEncodePowerApprox=1.0/LinearEncodePowerApprox;\nconst vec3 LuminanceEncodeApprox=vec3(0.2126,0.7152,0.0722);\nmat3 transposeMat3(mat3 inMatrix) {\nvec3 i0=inMatrix[0];\nvec3 i1=inMatrix[1];\nvec3 i2=inMatrix[2];\nmat3 outMatrix=mat3(\nvec3(i0.x,i1.x,i2.x),\nvec3(i0.y,i1.y,i2.y),\nvec3(i0.z,i1.z,i2.z)\n);\nreturn outMatrix;\n}\n\nmat3 inverseMat3(mat3 inMatrix) {\nfloat a00=inMatrix[0][0],a01=inMatrix[0][1],a02=inMatrix[0][2];\nfloat a10=inMatrix[1][0],a11=inMatrix[1][1],a12=inMatrix[1][2];\nfloat a20=inMatrix[2][0],a21=inMatrix[2][1],a22=inMatrix[2][2];\nfloat b01=a22*a11-a12*a21;\nfloat b11=-a22*a10+a12*a20;\nfloat b21=a21*a10-a11*a20;\nfloat det=a00*b01+a01*b11+a02*b21;\nreturn mat3(b01,(-a22*a01+a02*a21),(a12*a01-a02*a11),\nb11,(a22*a00-a02*a20),(-a12*a00+a02*a10),\nb21,(-a21*a00+a01*a20),(a11*a00-a01*a10))/det;\n}\nfloat computeFallOff(float value,vec2 clipSpace,float frustumEdgeFalloff)\n{\nfloat mask=smoothstep(1.0-frustumEdgeFalloff,1.0,clamp(dot(clipSpace,clipSpace),0.,1.));\nreturn mix(value,1.0,mask);\n}\nvec3 applyEaseInOut(vec3 x){\nreturn x*x*(3.0-2.0*x);\n}\nvec3 toLinearSpace(vec3 color)\n{\nreturn pow(color,vec3(LinearEncodePowerApprox));\n}\nvec3 toGammaSpace(vec3 color)\n{\nreturn pow(color,vec3(GammaEncodePowerApprox));\n}\nfloat square(float value)\n{\nreturn value*value;\n}\nfloat getLuminance(vec3 color)\n{\nreturn clamp(dot(color,LuminanceEncodeApprox),0.,1.);\n}\n\nfloat getRand(vec2 seed) {\nreturn fract(sin(dot(seed.xy ,vec2(12.9898,78.233)))*43758.5453);\n}\nfloat dither(vec2 seed,float varianceAmount) {\nfloat rand=getRand(seed);\nfloat dither=mix(-varianceAmount/255.0,varianceAmount/255.0,rand);\nreturn dither;\n}","lightFragmentDeclaration":"#ifdef LIGHT{X}\nuniform vec4 vLightData{X};\nuniform vec4 vLightDiffuse{X};\n#ifdef SPECULARTERM\nuniform vec3 vLightSpecular{X};\n#else\nvec3 vLightSpecular{X}=vec3(0.);\n#endif\n#ifdef SHADOW{X}\n#if defined(SHADOWCUBE{X})\nuniform samplerCube shadowSampler{X};\n#else\nvarying vec4 vPositionFromLight{X};\nvarying float vDepthMetric{X};\n#if defined(SHADOWPCSS{X})\nuniform highp sampler2DShadow shadowSampler{X};\nuniform highp sampler2D depthSampler{X};\n#elif defined(SHADOWPCF{X})\nuniform highp sampler2DShadow shadowSampler{X};\n#else\nuniform sampler2D shadowSampler{X};\n#endif\nuniform mat4 lightMatrix{X};\n#endif\nuniform vec4 shadowsInfo{X};\nuniform vec2 depthValues{X};\n#endif\n#ifdef SPOTLIGHT{X}\nuniform vec4 vLightDirection{X};\n#endif\n#ifdef HEMILIGHT{X}\nuniform vec3 vLightGround{X};\n#endif\n#ifdef PROJECTEDLIGHTTEXTURE{X}\nuniform mat4 textureProjectionMatrix{X};\nuniform sampler2D projectionLightSampler{X};\n#endif\n#endif","lightsFragmentFunctions":"\nstruct lightingInfo\n{\nvec3 diffuse;\n#ifdef SPECULARTERM\nvec3 specular;\n#endif\n#ifdef NDOTL\nfloat ndl;\n#endif\n};\nlightingInfo computeLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,float range,float glossiness) {\nlightingInfo result;\nvec3 lightVectorW;\nfloat attenuation=1.0;\nif (lightData.w == 0.)\n{\nvec3 direction=lightData.xyz-vPositionW;\nattenuation=max(0.,1.0-length(direction)/range);\nlightVectorW=normalize(direction);\n}\nelse\n{\nlightVectorW=normalize(-lightData.xyz);\n}\n\nfloat ndl=max(0.,dot(vNormal,lightVectorW));\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=ndl*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightVectorW);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeSpotLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec4 lightDirection,vec3 diffuseColor,vec3 specularColor,float range,float glossiness) {\nlightingInfo result;\nvec3 direction=lightData.xyz-vPositionW;\nvec3 lightVectorW=normalize(direction);\nfloat attenuation=max(0.,1.0-length(direction)/range);\n\nfloat cosAngle=max(0.,dot(lightDirection.xyz,-lightVectorW));\nif (cosAngle>=lightDirection.w)\n{\ncosAngle=max(0.,pow(cosAngle,lightData.w));\nattenuation*=cosAngle;\n\nfloat ndl=max(0.,dot(vNormal,lightVectorW));\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=ndl*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightVectorW);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor*attenuation;\n#endif\nreturn result;\n}\nresult.diffuse=vec3(0.);\n#ifdef SPECULARTERM\nresult.specular=vec3(0.);\n#endif\n#ifdef NDOTL\nresult.ndl=0.;\n#endif\nreturn result;\n}\nlightingInfo computeHemisphericLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,vec3 groundColor,float glossiness) {\nlightingInfo result;\n\nfloat ndl=dot(vNormal,lightData.xyz)*0.5+0.5;\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=mix(groundColor,diffuseColor,ndl);\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightData.xyz);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor;\n#endif\nreturn result;\n}\nvec3 computeProjectionTextureDiffuseLighting(sampler2D projectionLightSampler,mat4 textureProjectionMatrix){\nvec4 strq=textureProjectionMatrix*vec4(vPositionW,1.0);\nstrq/=strq.w;\nvec3 textureColor=texture2D(projectionLightSampler,strq.xy).rgb;\nreturn textureColor;\n}","lightUboDeclaration":"#ifdef LIGHT{X}\nuniform Light{X}\n{\nvec4 vLightData;\nvec4 vLightDiffuse;\nvec3 vLightSpecular;\n#ifdef SPOTLIGHT{X}\nvec4 vLightDirection;\n#endif\n#ifdef HEMILIGHT{X}\nvec3 vLightGround;\n#endif\nvec4 shadowsInfo;\nvec2 depthValues;\n} light{X};\n#ifdef PROJECTEDLIGHTTEXTURE{X}\nuniform mat4 textureProjectionMatrix{X};\nuniform sampler2D projectionLightSampler{X};\n#endif\n#ifdef SHADOW{X}\n#if defined(SHADOWCUBE{X})\nuniform samplerCube shadowSampler{X}; \n#else\nvarying vec4 vPositionFromLight{X};\nvarying float vDepthMetric{X};\n#if defined(SHADOWPCSS{X})\nuniform highp sampler2DShadow shadowSampler{X};\nuniform highp sampler2D depthSampler{X};\n#elif defined(SHADOWPCF{X})\nuniform highp sampler2DShadow shadowSampler{X};\n#else\nuniform sampler2D shadowSampler{X};\n#endif\nuniform mat4 lightMatrix{X};\n#endif\n#endif\n#endif","defaultVertexDeclaration":"\nuniform mat4 viewProjection;\nuniform mat4 view;\n#ifdef DIFFUSE\nuniform mat4 diffuseMatrix;\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef AMBIENT\nuniform mat4 ambientMatrix;\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\nuniform mat4 lightmapMatrix;\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nuniform vec2 vSpecularInfos;\nuniform mat4 specularMatrix;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform mat4 bumpMatrix;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n","defaultFragmentDeclaration":"uniform vec4 vDiffuseColor;\n#ifdef SPECULARTERM\nuniform vec4 vSpecularColor;\n#endif\nuniform vec3 vEmissiveColor;\n\n#ifdef DIFFUSE\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef AMBIENT\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY \nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform vec2 vTangentSpaceParams;\n#endif\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\n#ifndef REFRACTIONMAP_3D\nuniform mat4 refractionMatrix;\n#endif\n#ifdef REFRACTIONFRESNEL\nuniform vec4 refractionLeftColor;\nuniform vec4 refractionRightColor;\n#endif\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nuniform vec2 vSpecularInfos;\n#endif\n#ifdef DIFFUSEFRESNEL\nuniform vec4 diffuseLeftColor;\nuniform vec4 diffuseRightColor;\n#endif\n#ifdef OPACITYFRESNEL\nuniform vec4 opacityParts;\n#endif\n#ifdef EMISSIVEFRESNEL\nuniform vec4 emissiveLeftColor;\nuniform vec4 emissiveRightColor;\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\n#ifdef REFLECTIONMAP_SKYBOX\n#else\n#if defined(REFLECTIONMAP_PLANAR) || defined(REFLECTIONMAP_CUBIC) || defined(REFLECTIONMAP_PROJECTION)\nuniform mat4 reflectionMatrix;\n#endif\n#if defined(USE_LOCAL_REFLECTIONMAP_CUBIC) && defined(REFLECTIONMAP_CUBIC)\nuniform vec3 vReflectionPosition;\nuniform vec3 vReflectionSize; \n#endif\n#endif\n#ifdef REFLECTIONFRESNEL\nuniform vec4 reflectionLeftColor;\nuniform vec4 reflectionRightColor;\n#endif\n#endif","defaultUboDeclaration":"layout(std140,column_major) uniform;\nuniform Material\n{\nvec4 diffuseLeftColor;\nvec4 diffuseRightColor;\nvec4 opacityParts;\nvec4 reflectionLeftColor;\nvec4 reflectionRightColor;\nvec4 refractionLeftColor;\nvec4 refractionRightColor;\nvec4 emissiveLeftColor; \nvec4 emissiveRightColor;\nvec2 vDiffuseInfos;\nvec2 vAmbientInfos;\nvec2 vOpacityInfos;\nvec2 vReflectionInfos;\nvec3 vReflectionPosition;\nvec3 vReflectionSize;\nvec2 vEmissiveInfos;\nvec2 vLightmapInfos;\nvec2 vSpecularInfos;\nvec3 vBumpInfos;\nmat4 diffuseMatrix;\nmat4 ambientMatrix;\nmat4 opacityMatrix;\nmat4 reflectionMatrix;\nmat4 emissiveMatrix;\nmat4 lightmapMatrix;\nmat4 specularMatrix;\nmat4 bumpMatrix; \nvec4 vTangentSpaceParams;\nmat4 refractionMatrix;\nvec4 vRefractionInfos;\nvec4 vSpecularColor;\nvec3 vEmissiveColor;\nvec4 vDiffuseColor;\nfloat pointSize; \n};\nuniform Scene {\nmat4 viewProjection;\nmat4 view;\n};","shadowsFragmentFunctions":"#ifdef SHADOWS\n#ifndef SHADOWFLOAT\nfloat unpack(vec4 color)\n{\nconst vec4 bit_shift=vec4(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);\nreturn dot(color,bit_shift);\n}\n#endif\nfloat computeShadowCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\ndepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\n#ifndef SHADOWFLOAT\nfloat shadow=unpack(textureCube(shadowSampler,directionToLight));\n#else\nfloat shadow=textureCube(shadowSampler,directionToLight).x;\n#endif\nif (depth>shadow)\n{\nreturn darkness;\n}\nreturn 1.0;\n}\nfloat computeShadowWithPoissonSamplingCube(vec3 lightPosition,samplerCube shadowSampler,float mapSize,float darkness,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\ndepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\nfloat visibility=1.;\nvec3 poissonDisk[4];\npoissonDisk[0]=vec3(-1.0,1.0,-1.0);\npoissonDisk[1]=vec3(1.0,-1.0,-1.0);\npoissonDisk[2]=vec3(-1.0,-1.0,-1.0);\npoissonDisk[3]=vec3(1.0,-1.0,1.0);\n\n#ifndef SHADOWFLOAT\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[0]*mapSize))<depth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[1]*mapSize))<depth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[2]*mapSize))<depth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[3]*mapSize))<depth) visibility-=0.25;\n#else\nif (textureCube(shadowSampler,directionToLight+poissonDisk[0]*mapSize).x<depth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[1]*mapSize).x<depth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[2]*mapSize).x<depth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[3]*mapSize).x<depth) visibility-=0.25;\n#endif\nreturn min(1.0,visibility+darkness);\n}\nfloat computeShadowWithESMCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,float depthScale,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\nfloat shadowPixelDepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(textureCube(shadowSampler,directionToLight));\n#else\nfloat shadowMapSample=textureCube(shadowSampler,directionToLight).x;\n#endif\nfloat esm=1.0-clamp(exp(min(87.,depthScale*shadowPixelDepth))*shadowMapSample,0.,1.-darkness); \nreturn esm;\n}\nfloat computeShadowWithCloseESMCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,float depthScale,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\nfloat shadowPixelDepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(textureCube(shadowSampler,directionToLight));\n#else\nfloat shadowMapSample=textureCube(shadowSampler,directionToLight).x;\n#endif\nfloat esm=clamp(exp(min(87.,-depthScale*(shadowPixelDepth-shadowMapSample))),darkness,1.);\nreturn esm;\n}\nfloat computeShadow(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0);\n#ifndef SHADOWFLOAT\nfloat shadow=unpack(texture2D(shadowSampler,uv));\n#else\nfloat shadow=texture2D(shadowSampler,uv).x;\n#endif\nif (shadowPixelDepth>shadow)\n{\nreturn computeFallOff(darkness,clipSpace.xy,frustumEdgeFalloff);\n}\nreturn 1.;\n}\nfloat computeShadowWithPoissonSampling(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float mapSize,float darkness,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0);\nfloat visibility=1.;\nvec2 poissonDisk[4];\npoissonDisk[0]=vec2(-0.94201624,-0.39906216);\npoissonDisk[1]=vec2(0.94558609,-0.76890725);\npoissonDisk[2]=vec2(-0.094184101,-0.92938870);\npoissonDisk[3]=vec2(0.34495938,0.29387760);\n\n#ifndef SHADOWFLOAT\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[0]*mapSize))<shadowPixelDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[1]*mapSize))<shadowPixelDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[2]*mapSize))<shadowPixelDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[3]*mapSize))<shadowPixelDepth) visibility-=0.25;\n#else\nif (texture2D(shadowSampler,uv+poissonDisk[0]*mapSize).x<shadowPixelDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[1]*mapSize).x<shadowPixelDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[2]*mapSize).x<shadowPixelDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[3]*mapSize).x<shadowPixelDepth) visibility-=0.25;\n#endif\nreturn computeFallOff(min(1.0,visibility+darkness),clipSpace.xy,frustumEdgeFalloff);\n}\nfloat computeShadowWithESM(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float depthScale,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0);\n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(texture2D(shadowSampler,uv));\n#else\nfloat shadowMapSample=texture2D(shadowSampler,uv).x;\n#endif\nfloat esm=1.0-clamp(exp(min(87.,depthScale*shadowPixelDepth))*shadowMapSample,0.,1.-darkness);\nreturn computeFallOff(esm,clipSpace.xy,frustumEdgeFalloff);\n}\nfloat computeShadowWithCloseESM(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float depthScale,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0); \n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(texture2D(shadowSampler,uv));\n#else\nfloat shadowMapSample=texture2D(shadowSampler,uv).x;\n#endif\nfloat esm=clamp(exp(min(87.,-depthScale*(shadowPixelDepth-shadowMapSample))),darkness,1.);\nreturn computeFallOff(esm,clipSpace.xy,frustumEdgeFalloff);\n}\n#ifdef WEBGL2\n\nfloat computeShadowWithPCF1(vec4 vPositionFromLight,float depthMetric,sampler2DShadow shadowSampler,float darkness,float frustumEdgeFalloff)\n{\nif (depthMetric>1.0 || depthMetric<0.0) {\nreturn 1.0;\n}\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));\nfloat shadow=texture2D(shadowSampler,uvDepth);\nshadow=mix(darkness,1.,shadow);\nreturn computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);\n}\n\n\n\nfloat computeShadowWithPCF3(vec4 vPositionFromLight,float depthMetric,sampler2DShadow shadowSampler,vec2 shadowMapSizeAndInverse,float darkness,float frustumEdgeFalloff)\n{\nif (depthMetric>1.0 || depthMetric<0.0) {\nreturn 1.0;\n}\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));\nvec2 uv=uvDepth.xy*shadowMapSizeAndInverse.x; \nuv+=0.5; \nvec2 st=fract(uv); \nvec2 base_uv=floor(uv)-0.5; \nbase_uv*=shadowMapSizeAndInverse.y; \n\n\n\n\nvec2 uvw0=3.-2.*st;\nvec2 uvw1=1.+2.*st;\nvec2 u=vec2((2.-st.x)/uvw0.x-1.,st.x/uvw1.x+1.)*shadowMapSizeAndInverse.y;\nvec2 v=vec2((2.-st.y)/uvw0.y-1.,st.y/uvw1.y+1.)*shadowMapSizeAndInverse.y;\nfloat shadow=0.;\nshadow+=uvw0.x*uvw0.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[0]),uvDepth.z));\nshadow+=uvw1.x*uvw0.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[0]),uvDepth.z));\nshadow+=uvw0.x*uvw1.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[1]),uvDepth.z));\nshadow+=uvw1.x*uvw1.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[1]),uvDepth.z));\nshadow=shadow/16.;\nshadow=mix(darkness,1.,shadow);\nreturn computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);\n}\n\n\n\nfloat computeShadowWithPCF5(vec4 vPositionFromLight,float depthMetric,sampler2DShadow shadowSampler,vec2 shadowMapSizeAndInverse,float darkness,float frustumEdgeFalloff)\n{\nif (depthMetric>1.0 || depthMetric<0.0) {\nreturn 1.0;\n}\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));\nvec2 uv=uvDepth.xy*shadowMapSizeAndInverse.x; \nuv+=0.5; \nvec2 st=fract(uv); \nvec2 base_uv=floor(uv)-0.5; \nbase_uv*=shadowMapSizeAndInverse.y; \n\n\nvec2 uvw0=4.-3.*st;\nvec2 uvw1=vec2(7.);\nvec2 uvw2=1.+3.*st;\nvec3 u=vec3((3.-2.*st.x)/uvw0.x-2.,(3.+st.x)/uvw1.x,st.x/uvw2.x+2.)*shadowMapSizeAndInverse.y;\nvec3 v=vec3((3.-2.*st.y)/uvw0.y-2.,(3.+st.y)/uvw1.y,st.y/uvw2.y+2.)*shadowMapSizeAndInverse.y;\nfloat shadow=0.;\nshadow+=uvw0.x*uvw0.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[0]),uvDepth.z));\nshadow+=uvw1.x*uvw0.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[0]),uvDepth.z));\nshadow+=uvw2.x*uvw0.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[2],v[0]),uvDepth.z));\nshadow+=uvw0.x*uvw1.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[1]),uvDepth.z));\nshadow+=uvw1.x*uvw1.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[1]),uvDepth.z));\nshadow+=uvw2.x*uvw1.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[2],v[1]),uvDepth.z));\nshadow+=uvw0.x*uvw2.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[2]),uvDepth.z));\nshadow+=uvw1.x*uvw2.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[2]),uvDepth.z));\nshadow+=uvw2.x*uvw2.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[2],v[2]),uvDepth.z));\nshadow=shadow/144.;\nshadow=mix(darkness,1.,shadow);\nreturn computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);\n}\nconst vec3 PoissonSamplers32[64]=vec3[64](\nvec3(0.06407013,0.05409927,0.),\nvec3(0.7366577,0.5789394,0.),\nvec3(-0.6270542,-0.5320278,0.),\nvec3(-0.4096107,0.8411095,0.),\nvec3(0.6849564,-0.4990818,0.),\nvec3(-0.874181,-0.04579735,0.),\nvec3(0.9989998,0.0009880066,0.),\nvec3(-0.004920578,-0.9151649,0.),\nvec3(0.1805763,0.9747483,0.),\nvec3(-0.2138451,0.2635818,0.),\nvec3(0.109845,0.3884785,0.),\nvec3(0.06876755,-0.3581074,0.),\nvec3(0.374073,-0.7661266,0.),\nvec3(0.3079132,-0.1216763,0.),\nvec3(-0.3794335,-0.8271583,0.),\nvec3(-0.203878,-0.07715034,0.),\nvec3(0.5912697,0.1469799,0.),\nvec3(-0.88069,0.3031784,0.),\nvec3(0.5040108,0.8283722,0.),\nvec3(-0.5844124,0.5494877,0.),\nvec3(0.6017799,-0.1726654,0.),\nvec3(-0.5554981,0.1559997,0.),\nvec3(-0.3016369,-0.3900928,0.),\nvec3(-0.5550632,-0.1723762,0.),\nvec3(0.925029,0.2995041,0.),\nvec3(-0.2473137,0.5538505,0.),\nvec3(0.9183037,-0.2862392,0.),\nvec3(0.2469421,0.6718712,0.),\nvec3(0.3916397,-0.4328209,0.),\nvec3(-0.03576927,-0.6220032,0.),\nvec3(-0.04661255,0.7995201,0.),\nvec3(0.4402924,0.3640312,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.)\n);\nconst vec3 PoissonSamplers64[64]=vec3[64](\nvec3(-0.613392,0.617481,0.),\nvec3(0.170019,-0.040254,0.),\nvec3(-0.299417,0.791925,0.),\nvec3(0.645680,0.493210,0.),\nvec3(-0.651784,0.717887,0.),\nvec3(0.421003,0.027070,0.),\nvec3(-0.817194,-0.271096,0.),\nvec3(-0.705374,-0.668203,0.),\nvec3(0.977050,-0.108615,0.),\nvec3(0.063326,0.142369,0.),\nvec3(0.203528,0.214331,0.),\nvec3(-0.667531,0.326090,0.),\nvec3(-0.098422,-0.295755,0.),\nvec3(-0.885922,0.215369,0.),\nvec3(0.566637,0.605213,0.),\nvec3(0.039766,-0.396100,0.),\nvec3(0.751946,0.453352,0.),\nvec3(0.078707,-0.715323,0.),\nvec3(-0.075838,-0.529344,0.),\nvec3(0.724479,-0.580798,0.),\nvec3(0.222999,-0.215125,0.),\nvec3(-0.467574,-0.405438,0.),\nvec3(-0.248268,-0.814753,0.),\nvec3(0.354411,-0.887570,0.),\nvec3(0.175817,0.382366,0.),\nvec3(0.487472,-0.063082,0.),\nvec3(-0.084078,0.898312,0.),\nvec3(0.488876,-0.783441,0.),\nvec3(0.470016,0.217933,0.),\nvec3(-0.696890,-0.549791,0.),\nvec3(-0.149693,0.605762,0.),\nvec3(0.034211,0.979980,0.),\nvec3(0.503098,-0.308878,0.),\nvec3(-0.016205,-0.872921,0.),\nvec3(0.385784,-0.393902,0.),\nvec3(-0.146886,-0.859249,0.),\nvec3(0.643361,0.164098,0.),\nvec3(0.634388,-0.049471,0.),\nvec3(-0.688894,0.007843,0.),\nvec3(0.464034,-0.188818,0.),\nvec3(-0.440840,0.137486,0.),\nvec3(0.364483,0.511704,0.),\nvec3(0.034028,0.325968,0.),\nvec3(0.099094,-0.308023,0.),\nvec3(0.693960,-0.366253,0.),\nvec3(0.678884,-0.204688,0.),\nvec3(0.001801,0.780328,0.),\nvec3(0.145177,-0.898984,0.),\nvec3(0.062655,-0.611866,0.),\nvec3(0.315226,-0.604297,0.),\nvec3(-0.780145,0.486251,0.),\nvec3(-0.371868,0.882138,0.),\nvec3(0.200476,0.494430,0.),\nvec3(-0.494552,-0.711051,0.),\nvec3(0.612476,0.705252,0.),\nvec3(-0.578845,-0.768792,0.),\nvec3(-0.772454,-0.090976,0.),\nvec3(0.504440,0.372295,0.),\nvec3(0.155736,0.065157,0.),\nvec3(0.391522,0.849605,0.),\nvec3(-0.620106,-0.328104,0.),\nvec3(0.789239,-0.419965,0.),\nvec3(-0.545396,0.538133,0.),\nvec3(-0.178564,-0.596057,0.)\n);\n\n\n\n\n\nfloat computeShadowWithPCSS(vec4 vPositionFromLight,float depthMetric,sampler2D depthSampler,sampler2DShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff,int searchTapCount,int pcfTapCount,vec3[64] poissonSamplers)\n{\nif (depthMetric>1.0 || depthMetric<0.0) {\nreturn 1.0;\n}\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));\nfloat blockerDepth=0.0;\nfloat sumBlockerDepth=0.0;\nfloat numBlocker=0.0;\nfor (int i=0; i<searchTapCount; i ++) {\nblockerDepth=texture(depthSampler,uvDepth.xy+(lightSizeUV*shadowMapSizeInverse*PoissonSamplers32[i].xy)).r;\nif (blockerDepth<depthMetric) {\nsumBlockerDepth+=blockerDepth;\nnumBlocker++;\n}\n}\nif (numBlocker<1.0) {\nreturn 1.0;\n}\nfloat avgBlockerDepth=sumBlockerDepth/numBlocker;\n\nfloat AAOffset=shadowMapSizeInverse*10.;\n\n\nfloat penumbraRatio=((depthMetric-avgBlockerDepth)+AAOffset);\nfloat filterRadius=penumbraRatio*lightSizeUV*shadowMapSizeInverse;\nfloat random=getRand(vPositionFromLight.xy);\nfloat rotationAngle=random*3.1415926;\nvec2 rotationVector=vec2(cos(rotationAngle),sin(rotationAngle));\nfloat shadow=0.;\nfor (int i=0; i<pcfTapCount; i++) {\nvec3 offset=poissonSamplers[i];\n\noffset=vec3(offset.x*rotationVector.x-offset.y*rotationVector.y,offset.y*rotationVector.x+offset.x*rotationVector.y,0.);\nshadow+=texture2D(shadowSampler,uvDepth+offset*filterRadius);\n}\nshadow/=float(pcfTapCount);\n\nshadow=mix(shadow,1.,depthMetric-avgBlockerDepth);\n\nshadow=mix(darkness,1.,shadow);\n\nreturn computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);\n}\nfloat computeShadowWithPCSS16(vec4 vPositionFromLight,float depthMetric,sampler2D depthSampler,sampler2DShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff)\n{\nreturn computeShadowWithPCSS(vPositionFromLight,depthMetric,depthSampler,shadowSampler,shadowMapSizeInverse,lightSizeUV,darkness,frustumEdgeFalloff,16,16,PoissonSamplers32);\n}\nfloat computeShadowWithPCSS32(vec4 vPositionFromLight,float depthMetric,sampler2D depthSampler,sampler2DShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff)\n{\nreturn computeShadowWithPCSS(vPositionFromLight,depthMetric,depthSampler,shadowSampler,shadowMapSizeInverse,lightSizeUV,darkness,frustumEdgeFalloff,16,32,PoissonSamplers32);\n}\nfloat computeShadowWithPCSS64(vec4 vPositionFromLight,float depthMetric,sampler2D depthSampler,sampler2DShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff)\n{\nreturn computeShadowWithPCSS(vPositionFromLight,depthMetric,depthSampler,shadowSampler,shadowMapSizeInverse,lightSizeUV,darkness,frustumEdgeFalloff,32,64,PoissonSamplers64);\n}\n#endif\n#endif\n","fresnelFunction":"#ifdef FRESNEL\nfloat computeFresnelTerm(vec3 viewDirection,vec3 worldNormal,float bias,float power)\n{\nfloat fresnelTerm=pow(bias+abs(dot(viewDirection,worldNormal)),power);\nreturn clamp(fresnelTerm,0.,1.);\n}\n#endif","reflectionFunction":"#ifdef USE_LOCAL_REFLECTIONMAP_CUBIC\nvec3 parallaxCorrectNormal( vec3 vertexPos,vec3 origVec,vec3 cubeSize,vec3 cubePos ) {\n\nvec3 invOrigVec=vec3(1.0,1.0,1.0)/origVec;\nvec3 halfSize=cubeSize*0.5;\nvec3 intersecAtMaxPlane=(cubePos+halfSize-vertexPos)*invOrigVec;\nvec3 intersecAtMinPlane=(cubePos-halfSize-vertexPos)*invOrigVec;\n\nvec3 largestIntersec=max(intersecAtMaxPlane,intersecAtMinPlane);\n\nfloat distance=min(min(largestIntersec.x,largestIntersec.y),largestIntersec.z);\n\nvec3 intersectPositionWS=vertexPos+origVec*distance;\n\nreturn intersectPositionWS-cubePos;\n}\n#endif\nvec3 computeReflectionCoords(vec4 worldPos,vec3 worldNormal)\n{\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvec3 direction=vDirectionW;\nfloat t=clamp(direction.y*-0.5+0.5,0.,1.0);\nfloat s=atan(direction.z,direction.x)*RECIPROCAL_PI2+0.5;\n#ifdef REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED\nreturn vec3(1.0-s,t,0);\n#else\nreturn vec3(s,t,0);\n#endif\n#endif\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR\nvec3 cameraToVertex=normalize(worldPos.xyz-vEyePosition.xyz);\nvec3 r=reflect(cameraToVertex,worldNormal);\nfloat t=clamp(r.y*-0.5+0.5,0.,1.0);\nfloat s=atan(r.z,r.x)*RECIPROCAL_PI2+0.5;\nreturn vec3(s,t,0);\n#endif\n#ifdef REFLECTIONMAP_SPHERICAL\nvec3 viewDir=normalize(vec3(view*worldPos));\nvec3 viewNormal=normalize(vec3(view*vec4(worldNormal,0.0)));\nvec3 r=reflect(viewDir,viewNormal);\nr.z=r.z-1.0;\nfloat m=2.0*length(r);\nreturn vec3(r.x/m+0.5,1.0-r.y/m-0.5,0);\n#endif\n#ifdef REFLECTIONMAP_PLANAR\nvec3 viewDir=worldPos.xyz-vEyePosition.xyz;\nvec3 coords=normalize(reflect(viewDir,worldNormal));\nreturn vec3(reflectionMatrix*vec4(coords,1));\n#endif\n#ifdef REFLECTIONMAP_CUBIC\nvec3 viewDir=normalize(worldPos.xyz-vEyePosition.xyz);\n\nvec3 coords=reflect(viewDir,worldNormal);\n#ifdef USE_LOCAL_REFLECTIONMAP_CUBIC\ncoords=parallaxCorrectNormal(worldPos.xyz,coords,vReflectionSize,vReflectionPosition);\n#endif\ncoords=vec3(reflectionMatrix*vec4(coords,0));\n#ifdef INVERTCUBICMAP\ncoords.y*=-1.0;\n#endif\nreturn coords;\n#endif\n#ifdef REFLECTIONMAP_PROJECTION\nreturn vec3(reflectionMatrix*(view*worldPos));\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nreturn vPositionUVW;\n#endif\n#ifdef REFLECTIONMAP_EXPLICIT\nreturn vec3(0,0,0);\n#endif\n}","imageProcessingDeclaration":"#ifdef EXPOSURE\nuniform float exposureLinear;\n#endif\n#ifdef CONTRAST\nuniform float contrast;\n#endif\n#ifdef VIGNETTE\nuniform vec2 vInverseScreenSize;\nuniform vec4 vignetteSettings1;\nuniform vec4 vignetteSettings2;\n#endif\n#ifdef COLORCURVES\nuniform vec4 vCameraColorCurveNegative;\nuniform vec4 vCameraColorCurveNeutral;\nuniform vec4 vCameraColorCurvePositive;\n#endif\n#ifdef COLORGRADING\n#ifdef COLORGRADING3D\nuniform highp sampler3D txColorTransform;\n#else\nuniform sampler2D txColorTransform;\n#endif\nuniform vec4 colorTransformSettings;\n#endif","imageProcessingFunctions":"#if defined(COLORGRADING) && !defined(COLORGRADING3D)\n\nvec3 sampleTexture3D(sampler2D colorTransform,vec3 color,vec2 sampler3dSetting)\n{\nfloat sliceSize=2.0*sampler3dSetting.x; \n#ifdef SAMPLER3DGREENDEPTH\nfloat sliceContinuous=(color.g-sampler3dSetting.x)*sampler3dSetting.y;\n#else\nfloat sliceContinuous=(color.b-sampler3dSetting.x)*sampler3dSetting.y;\n#endif\nfloat sliceInteger=floor(sliceContinuous);\n\n\nfloat sliceFraction=sliceContinuous-sliceInteger;\n#ifdef SAMPLER3DGREENDEPTH\nvec2 sliceUV=color.rb;\n#else\nvec2 sliceUV=color.rg;\n#endif\nsliceUV.x*=sliceSize;\nsliceUV.x+=sliceInteger*sliceSize;\nsliceUV=clamp(sliceUV,0.,1.);\nvec4 slice0Color=texture2D(colorTransform,sliceUV);\nsliceUV.x+=sliceSize;\nsliceUV=clamp(sliceUV,0.,1.);\nvec4 slice1Color=texture2D(colorTransform,sliceUV);\nvec3 result=mix(slice0Color.rgb,slice1Color.rgb,sliceFraction);\n#ifdef SAMPLER3DBGRMAP\ncolor.rgb=result.rgb;\n#else\ncolor.rgb=result.bgr;\n#endif\nreturn color;\n}\n#endif\nvec4 applyImageProcessing(vec4 result) {\n#ifdef EXPOSURE\nresult.rgb*=exposureLinear;\n#endif\n#ifdef VIGNETTE\n\nvec2 viewportXY=gl_FragCoord.xy*vInverseScreenSize;\nviewportXY=viewportXY*2.0-1.0;\nvec3 vignetteXY1=vec3(viewportXY*vignetteSettings1.xy+vignetteSettings1.zw,1.0);\nfloat vignetteTerm=dot(vignetteXY1,vignetteXY1);\nfloat vignette=pow(vignetteTerm,vignetteSettings2.w);\n\nvec3 vignetteColor=vignetteSettings2.rgb;\n#ifdef VIGNETTEBLENDMODEMULTIPLY\nvec3 vignetteColorMultiplier=mix(vignetteColor,vec3(1,1,1),vignette);\nresult.rgb*=vignetteColorMultiplier;\n#endif\n#ifdef VIGNETTEBLENDMODEOPAQUE\nresult.rgb=mix(vignetteColor,result.rgb,vignette);\n#endif\n#endif\n#ifdef TONEMAPPING\nconst float tonemappingCalibration=1.590579;\nresult.rgb=1.0-exp2(-tonemappingCalibration*result.rgb);\n#endif\n\nresult.rgb=toGammaSpace(result.rgb);\nresult.rgb=clamp(result.rgb,0.0,1.0);\n#ifdef CONTRAST\n\nvec3 resultHighContrast=applyEaseInOut(result.rgb);\nif (contrast<1.0) {\n\nresult.rgb=mix(vec3(0.5,0.5,0.5),result.rgb,contrast);\n} else {\n\nresult.rgb=mix(result.rgb,resultHighContrast,contrast-1.0);\n}\n#endif\n\n#ifdef COLORGRADING\nvec3 colorTransformInput=result.rgb*colorTransformSettings.xxx+colorTransformSettings.yyy;\n#ifdef COLORGRADING3D\nvec3 colorTransformOutput=texture(txColorTransform,colorTransformInput).rgb;\n#else\nvec3 colorTransformOutput=sampleTexture3D(txColorTransform,colorTransformInput,colorTransformSettings.yz).rgb;\n#endif\nresult.rgb=mix(result.rgb,colorTransformOutput,colorTransformSettings.www);\n#endif\n#ifdef COLORCURVES\n\nfloat luma=getLuminance(result.rgb);\nvec2 curveMix=clamp(vec2(luma*3.0-1.5,luma*-3.0+1.5),vec2(0.0),vec2(1.0));\nvec4 colorCurve=vCameraColorCurveNeutral+curveMix.x*vCameraColorCurvePositive-curveMix.y*vCameraColorCurveNegative;\nresult.rgb*=colorCurve.rgb;\nresult.rgb=mix(vec3(luma),result.rgb,colorCurve.a);\n#endif\nreturn result;\n}","bumpFragmentFunctions":"#ifdef BUMP\n#if BUMPDIRECTUV == 1\n#define vBumpUV vMainUV1\n#elif BUMPDIRECTUV == 2\n#define vBumpUV vMainUV2\n#else\nvarying vec2 vBumpUV;\n#endif\nuniform sampler2D bumpSampler;\n#if defined(TANGENT) && defined(NORMAL) \nvarying mat3 vTBN;\n#endif\n#ifdef OBJECTSPACE_NORMALMAP\nuniform mat4 normalMatrix;\n#endif\n\nmat3 cotangent_frame(vec3 normal,vec3 p,vec2 uv)\n{\n\nuv=gl_FrontFacing ? uv : -uv;\n\nvec3 dp1=dFdx(p);\nvec3 dp2=dFdy(p);\nvec2 duv1=dFdx(uv);\nvec2 duv2=dFdy(uv);\n\nvec3 dp2perp=cross(dp2,normal);\nvec3 dp1perp=cross(normal,dp1);\nvec3 tangent=dp2perp*duv1.x+dp1perp*duv2.x;\nvec3 bitangent=dp2perp*duv1.y+dp1perp*duv2.y;\n\ntangent*=vTangentSpaceParams.x;\nbitangent*=vTangentSpaceParams.y;\n\nfloat invmax=inversesqrt(max(dot(tangent,tangent),dot(bitangent,bitangent)));\nreturn mat3(tangent*invmax,bitangent*invmax,normal);\n}\nvec3 perturbNormal(mat3 cotangentFrame,vec2 uv)\n{\nvec3 map=texture2D(bumpSampler,uv).xyz;\nmap=map*2.0-1.0;\n#ifdef NORMALXYSCALE\nmap=normalize(map*vec3(vBumpInfos.y,vBumpInfos.y,1.0));\n#endif\nreturn normalize(cotangentFrame*map);\n}\n#ifdef PARALLAX\nconst float minSamples=4.;\nconst float maxSamples=15.;\nconst int iMaxSamples=15;\n\nvec2 parallaxOcclusion(vec3 vViewDirCoT,vec3 vNormalCoT,vec2 texCoord,float parallaxScale) {\nfloat parallaxLimit=length(vViewDirCoT.xy)/vViewDirCoT.z;\nparallaxLimit*=parallaxScale;\nvec2 vOffsetDir=normalize(vViewDirCoT.xy);\nvec2 vMaxOffset=vOffsetDir*parallaxLimit;\nfloat numSamples=maxSamples+(dot(vViewDirCoT,vNormalCoT)*(minSamples-maxSamples));\nfloat stepSize=1.0/numSamples;\n\nfloat currRayHeight=1.0;\nvec2 vCurrOffset=vec2(0,0);\nvec2 vLastOffset=vec2(0,0);\nfloat lastSampledHeight=1.0;\nfloat currSampledHeight=1.0;\nfor (int i=0; i<iMaxSamples; i++)\n{\ncurrSampledHeight=texture2D(bumpSampler,vBumpUV+vCurrOffset).w;\n\nif (currSampledHeight>currRayHeight)\n{\nfloat delta1=currSampledHeight-currRayHeight;\nfloat delta2=(currRayHeight+stepSize)-lastSampledHeight;\nfloat ratio=delta1/(delta1+delta2);\nvCurrOffset=(ratio)* vLastOffset+(1.0-ratio)*vCurrOffset;\n\nbreak;\n}\nelse\n{\ncurrRayHeight-=stepSize;\nvLastOffset=vCurrOffset;\nvCurrOffset+=stepSize*vMaxOffset;\nlastSampledHeight=currSampledHeight;\n}\n}\nreturn vCurrOffset;\n}\nvec2 parallaxOffset(vec3 viewDir,float heightScale)\n{\n\nfloat height=texture2D(bumpSampler,vBumpUV).w;\nvec2 texCoordOffset=heightScale*viewDir.xy*height;\nreturn -texCoordOffset;\n}\n#endif\n#endif","clipPlaneFragmentDeclaration":"#ifdef CLIPPLANE\nvarying float fClipDistance;\n#endif","fogFragmentDeclaration":"#ifdef FOG\n#define FOGMODE_NONE 0.\n#define FOGMODE_EXP 1.\n#define FOGMODE_EXP2 2.\n#define FOGMODE_LINEAR 3.\n#define E 2.71828\nuniform vec4 vFogInfos;\nuniform vec3 vFogColor;\nvarying vec3 vFogDistance;\nfloat CalcFogFactor()\n{\nfloat fogCoeff=1.0;\nfloat fogStart=vFogInfos.y;\nfloat fogEnd=vFogInfos.z;\nfloat fogDensity=vFogInfos.w;\nfloat fogDistance=length(vFogDistance);\nif (FOGMODE_LINEAR == vFogInfos.x)\n{\nfogCoeff=(fogEnd-fogDistance)/(fogEnd-fogStart);\n}\nelse if (FOGMODE_EXP == vFogInfos.x)\n{\nfogCoeff=1.0/pow(E,fogDistance*fogDensity);\n}\nelse if (FOGMODE_EXP2 == vFogInfos.x)\n{\nfogCoeff=1.0/pow(E,fogDistance*fogDistance*fogDensity*fogDensity);\n}\nreturn clamp(fogCoeff,0.0,1.0);\n}\n#endif","clipPlaneFragment":"#ifdef CLIPPLANE\nif (fClipDistance>0.0)\n{\ndiscard;\n}\n#endif","bumpFragment":"vec2 uvOffset=vec2(0.0,0.0);\n#if defined(BUMP) || defined(PARALLAX)\n#ifdef NORMALXYSCALE\nfloat normalScale=1.0;\n#else \nfloat normalScale=vBumpInfos.y;\n#endif\n#if defined(TANGENT) && defined(NORMAL)\nmat3 TBN=vTBN;\n#else\nmat3 TBN=cotangent_frame(normalW*normalScale,vPositionW,vBumpUV);\n#endif\n#endif\n#ifdef PARALLAX\nmat3 invTBN=transposeMat3(TBN);\n#ifdef PARALLAXOCCLUSION\nuvOffset=parallaxOcclusion(invTBN*-viewDirectionW,invTBN*normalW,vBumpUV,vBumpInfos.z);\n#else\nuvOffset=parallaxOffset(invTBN*viewDirectionW,vBumpInfos.z);\n#endif\n#endif\n#ifdef BUMP\n#ifdef OBJECTSPACE_NORMALMAP\nnormalW=normalize(texture2D(bumpSampler,vBumpUV).xyz*2.0-1.0);\nnormalW=normalize(mat3(normalMatrix)*normalW); \n#else\nnormalW=perturbNormal(TBN,vBumpUV+uvOffset);\n#endif\n#endif","lightFragment":"#ifdef LIGHT{X}\n#if defined(SHADOWONLY) || (defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X}) && defined(LIGHTMAPNOSPECULAR{X}))\n\n#else\n#ifdef PBR\n#ifdef SPOTLIGHT{X}\ninfo=computeSpotLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDirection,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,roughness,NdotV,specularEnvironmentR0,specularEnvironmentR90,geometricRoughnessFactor,NdotL);\n#endif\n#ifdef HEMILIGHT{X}\ninfo=computeHemisphericLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightGround,roughness,NdotV,specularEnvironmentR0,specularEnvironmentR90,geometricRoughnessFactor,NdotL);\n#endif\n#if defined(POINTLIGHT{X}) || defined(DIRLIGHT{X})\ninfo=computeLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,roughness,NdotV,specularEnvironmentR0,specularEnvironmentR90,geometricRoughnessFactor,NdotL);\n#endif\n#else\n#ifdef SPOTLIGHT{X}\ninfo=computeSpotLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDirection,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,glossiness);\n#endif\n#ifdef HEMILIGHT{X}\ninfo=computeHemisphericLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightGround,glossiness);\n#endif\n#if defined(POINTLIGHT{X}) || defined(DIRLIGHT{X})\ninfo=computeLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,glossiness);\n#endif\n#endif\n#ifdef PROJECTEDLIGHTTEXTURE{X}\ninfo.diffuse*=computeProjectionTextureDiffuseLighting(projectionLightSampler{X},textureProjectionMatrix{X});\n#endif\n#endif\n#ifdef SHADOW{X}\n#ifdef SHADOWCLOSEESM{X}\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithCloseESMCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.depthValues);\n#else\nshadow=computeShadowWithCloseESM(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.shadowsInfo.w);\n#endif\n#elif defined(SHADOWESM{X})\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithESMCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.depthValues);\n#else\nshadow=computeShadowWithESM(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.shadowsInfo.w);\n#endif\n#elif defined(SHADOWPOISSON{X})\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithPoissonSamplingCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.x,light{X}.depthValues);\n#else\nshadow=computeShadowWithPoissonSampling(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#elif defined(SHADOWPCF{X})\n#if defined(SHADOWLOWQUALITY{X})\nshadow=computeShadowWithPCF1(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#elif defined(SHADOWMEDIUMQUALITY{X})\nshadow=computeShadowWithPCF3(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.yz,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#else\nshadow=computeShadowWithPCF5(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.yz,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#elif defined(SHADOWPCSS{X})\n#if defined(SHADOWLOWQUALITY{X})\nshadow=computeShadowWithPCSS16(vPositionFromLight{X},vDepthMetric{X},depthSampler{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#elif defined(SHADOWMEDIUMQUALITY{X})\nshadow=computeShadowWithPCSS32(vPositionFromLight{X},vDepthMetric{X},depthSampler{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#else\nshadow=computeShadowWithPCSS64(vPositionFromLight{X},vDepthMetric{X},depthSampler{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#else\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.depthValues);\n#else\nshadow=computeShadow(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#endif\n#ifdef SHADOWONLY\n#ifndef SHADOWINUSE\n#define SHADOWINUSE\n#endif\nglobalShadow+=shadow;\nshadowLightCount+=1.0;\n#endif\n#else\nshadow=1.;\n#endif\n#ifndef SHADOWONLY\n#ifdef CUSTOMUSERLIGHTING\ndiffuseBase+=computeCustomDiffuseLighting(info,diffuseBase,shadow);\n#ifdef SPECULARTERM\nspecularBase+=computeCustomSpecularLighting(info,specularBase,shadow);\n#endif\n#elif defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X})\ndiffuseBase+=lightmapColor*shadow;\n#ifdef SPECULARTERM\n#ifndef LIGHTMAPNOSPECULAR{X}\nspecularBase+=info.specular*shadow*lightmapColor;\n#endif\n#endif\n#else\ndiffuseBase+=info.diffuse*shadow;\n#ifdef SPECULARTERM\nspecularBase+=info.specular*shadow;\n#endif\n#endif\n#endif\n#endif","logDepthFragment":"#ifdef LOGARITHMICDEPTH\ngl_FragDepthEXT=log2(vFragmentDepth)*logarithmicDepthConstant*0.5;\n#endif","fogFragment":"#ifdef FOG\nfloat fog=CalcFogFactor();\ncolor.rgb=fog*color.rgb+(1.0-fog)*vFogColor;\n#endif","pbrVertexDeclaration":"uniform mat4 view;\nuniform mat4 viewProjection;\n#ifdef ALBEDO\nuniform mat4 albedoMatrix;\nuniform vec2 vAlbedoInfos;\n#endif\n#ifdef AMBIENT\nuniform mat4 ambientMatrix;\nuniform vec3 vAmbientInfos;\n#endif\n#ifdef OPACITY\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\nuniform mat4 lightmapMatrix;\n#endif\n#ifdef REFLECTIVITY \nuniform vec3 vReflectivityInfos;\nuniform mat4 reflectivityMatrix;\n#endif\n#ifdef MICROSURFACEMAP\nuniform vec2 vMicroSurfaceSamplerInfos;\nuniform mat4 microSurfaceSamplerMatrix;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform mat4 bumpMatrix;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\nuniform mat4 refractionMatrix;\nuniform vec3 vRefractionMicrosurfaceInfos;\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\n#endif\n","pbrFragmentDeclaration":"uniform vec3 vReflectionColor;\nuniform vec4 vAlbedoColor;\n\nuniform vec4 vLightingIntensity;\nuniform vec4 vReflectivityColor;\nuniform vec3 vEmissiveColor;\n\n#ifdef ALBEDO\nuniform vec2 vAlbedoInfos;\n#endif\n#ifdef AMBIENT\nuniform vec3 vAmbientInfos;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform vec2 vTangentSpaceParams;\n#endif\n#ifdef OPACITY \nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\n#endif\n#ifdef REFLECTIVITY\nuniform vec3 vReflectivityInfos;\n#endif\n#ifdef MICROSURFACEMAP\nuniform vec2 vMicroSurfaceSamplerInfos;\n#endif\n\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif\n\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\nuniform mat4 refractionMatrix;\nuniform vec3 vRefractionMicrosurfaceInfos;\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\n#if defined(USE_LOCAL_REFLECTIONMAP_CUBIC) && defined(REFLECTIONMAP_CUBIC)\nuniform vec3 vReflectionPosition;\nuniform vec3 vReflectionSize; \n#endif\n#endif","pbrUboDeclaration":"layout(std140,column_major) uniform;\nuniform Material\n{\nuniform vec2 vAlbedoInfos;\nuniform vec3 vAmbientInfos;\nuniform vec2 vOpacityInfos;\nuniform vec2 vEmissiveInfos;\nuniform vec2 vLightmapInfos;\nuniform vec3 vReflectivityInfos;\nuniform vec2 vMicroSurfaceSamplerInfos;\nuniform vec4 vRefractionInfos;\nuniform vec2 vReflectionInfos;\nuniform vec3 vReflectionPosition;\nuniform vec3 vReflectionSize; \nuniform vec3 vBumpInfos;\nuniform mat4 albedoMatrix;\nuniform mat4 ambientMatrix;\nuniform mat4 opacityMatrix;\nuniform mat4 emissiveMatrix;\nuniform mat4 lightmapMatrix;\nuniform mat4 reflectivityMatrix;\nuniform mat4 microSurfaceSamplerMatrix;\nuniform mat4 bumpMatrix;\nuniform vec2 vTangentSpaceParams;\nuniform mat4 refractionMatrix;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionColor;\nuniform vec4 vAlbedoColor;\nuniform vec4 vLightingIntensity;\nuniform vec3 vRefractionMicrosurfaceInfos;\nuniform vec3 vReflectionMicrosurfaceInfos;\nuniform vec4 vReflectivityColor;\nuniform vec3 vEmissiveColor;\nuniform float pointSize;\n};\nuniform Scene {\nmat4 viewProjection;\nmat4 view;\n};","pbrFunctions":"\n#define RECIPROCAL_PI2 0.15915494\n#define FRESNEL_MAXIMUM_ON_ROUGH 0.25\n\nconst float kRougnhessToAlphaScale=0.1;\nconst float kRougnhessToAlphaOffset=0.29248125;\nfloat convertRoughnessToAverageSlope(float roughness)\n{\n\nconst float kMinimumVariance=0.0005;\nfloat alphaG=square(roughness)+kMinimumVariance;\nreturn alphaG;\n}\n\nfloat smithVisibilityG1_TrowbridgeReitzGGX(float dot,float alphaG)\n{\nfloat tanSquared=(1.0-dot*dot)/(dot*dot);\nreturn 2.0/(1.0+sqrt(1.0+alphaG*alphaG*tanSquared));\n}\nfloat smithVisibilityG_TrowbridgeReitzGGX_Walter(float NdotL,float NdotV,float alphaG)\n{\nreturn smithVisibilityG1_TrowbridgeReitzGGX(NdotL,alphaG)*smithVisibilityG1_TrowbridgeReitzGGX(NdotV,alphaG);\n}\n\n\nfloat normalDistributionFunction_TrowbridgeReitzGGX(float NdotH,float alphaG)\n{\n\n\n\nfloat a2=square(alphaG);\nfloat d=NdotH*NdotH*(a2-1.0)+1.0;\nreturn a2/(PI*d*d);\n}\nvec3 fresnelSchlickGGX(float VdotH,vec3 reflectance0,vec3 reflectance90)\n{\nreturn reflectance0+(reflectance90-reflectance0)*pow(clamp(1.0-VdotH,0.,1.),5.0);\n}\nvec3 fresnelSchlickEnvironmentGGX(float VdotN,vec3 reflectance0,vec3 reflectance90,float smoothness)\n{\n\nfloat weight=mix(FRESNEL_MAXIMUM_ON_ROUGH,1.0,smoothness);\nreturn reflectance0+weight*(reflectance90-reflectance0)*pow(clamp(1.0-VdotN,0.,1.),5.0);\n}\n\nvec3 computeSpecularTerm(float NdotH,float NdotL,float NdotV,float VdotH,float roughness,vec3 reflectance0,vec3 reflectance90,float geometricRoughnessFactor)\n{\nroughness=max(roughness,geometricRoughnessFactor);\nfloat alphaG=convertRoughnessToAverageSlope(roughness);\nfloat distribution=normalDistributionFunction_TrowbridgeReitzGGX(NdotH,alphaG);\nfloat visibility=smithVisibilityG_TrowbridgeReitzGGX_Walter(NdotL,NdotV,alphaG);\nvisibility/=(4.0*NdotL*NdotV); \nfloat specTerm=max(0.,visibility*distribution)*NdotL;\nvec3 fresnel=fresnelSchlickGGX(VdotH,reflectance0,reflectance90);\nreturn fresnel*specTerm;\n}\nfloat computeDiffuseTerm(float NdotL,float NdotV,float VdotH,float roughness)\n{\n\n\nfloat diffuseFresnelNV=pow(clamp(1.0-NdotL,0.000001,1.),5.0);\nfloat diffuseFresnelNL=pow(clamp(1.0-NdotV,0.000001,1.),5.0);\nfloat diffuseFresnel90=0.5+2.0*VdotH*VdotH*roughness;\nfloat fresnel =\n(1.0+(diffuseFresnel90-1.0)*diffuseFresnelNL) *\n(1.0+(diffuseFresnel90-1.0)*diffuseFresnelNV);\nreturn fresnel*NdotL/PI;\n}\nfloat adjustRoughnessFromLightProperties(float roughness,float lightRadius,float lightDistance)\n{\n#ifdef USEPHYSICALLIGHTFALLOFF\n\nfloat lightRoughness=lightRadius/lightDistance;\n\nfloat totalRoughness=clamp(lightRoughness+roughness,0.,1.);\nreturn totalRoughness;\n#else\nreturn roughness;\n#endif\n}\nfloat computeDefaultMicroSurface(float microSurface,vec3 reflectivityColor)\n{\nconst float kReflectivityNoAlphaWorkflow_SmoothnessMax=0.95;\nfloat reflectivityLuminance=getLuminance(reflectivityColor);\nfloat reflectivityLuma=sqrt(reflectivityLuminance);\nmicroSurface=reflectivityLuma*kReflectivityNoAlphaWorkflow_SmoothnessMax;\nreturn microSurface;\n}\n\n\nfloat fresnelGrazingReflectance(float reflectance0) {\nfloat reflectance90=clamp(reflectance0*25.0,0.0,1.0);\nreturn reflectance90;\n}\n\n\n#define UNPACK_LOD(x) (1.0-x)*255.0\nfloat getLodFromAlphaG(float cubeMapDimensionPixels,float alphaG,float NdotV) {\nfloat microsurfaceAverageSlope=alphaG;\n\n\n\n\n\n\nmicrosurfaceAverageSlope*=sqrt(abs(NdotV));\nfloat microsurfaceAverageSlopeTexels=microsurfaceAverageSlope*cubeMapDimensionPixels;\nfloat lod=log2(microsurfaceAverageSlopeTexels);\nreturn lod;\n}\nfloat environmentRadianceOcclusion(float ambientOcclusion,float NdotVUnclamped) {\n\n\nfloat temp=NdotVUnclamped+ambientOcclusion;\nreturn clamp(square(temp)-1.0+ambientOcclusion,0.0,1.0);\n}\nfloat environmentHorizonOcclusion(vec3 view,vec3 normal) {\n\nvec3 reflection=reflect(view,normal);\nfloat temp=clamp( 1.0+1.1*dot(reflection,normal),0.0,1.0);\nreturn square(temp);\n}","harmonicsFunctions":"#ifdef USESPHERICALFROMREFLECTIONMAP\nuniform vec3 vSphericalX;\nuniform vec3 vSphericalY;\nuniform vec3 vSphericalZ;\nuniform vec3 vSphericalXX_ZZ;\nuniform vec3 vSphericalYY_ZZ;\nuniform vec3 vSphericalZZ;\nuniform vec3 vSphericalXY;\nuniform vec3 vSphericalYZ;\nuniform vec3 vSphericalZX;\nvec3 quaternionVectorRotation_ScaledSqrtTwo(vec4 Q,vec3 V){\nvec3 T=cross(Q.xyz,V);\nT+=Q.www*V;\nreturn cross(Q.xyz,T)+V;\n}\nvec3 environmentIrradianceJones(vec3 normal)\n{\n\n\n\n\n\n\n\n\n\nfloat Nx=normal.x;\nfloat Ny=normal.y;\nfloat Nz=normal.z;\nvec3 C1=vSphericalZZ.rgb;\nvec3 Cx=vSphericalX.rgb;\nvec3 Cy=vSphericalY.rgb;\nvec3 Cz=vSphericalZ.rgb;\nvec3 Cxx_zz=vSphericalXX_ZZ.rgb;\nvec3 Cyy_zz=vSphericalYY_ZZ.rgb;\nvec3 Cxy=vSphericalXY.rgb;\nvec3 Cyz=vSphericalYZ.rgb;\nvec3 Czx=vSphericalZX.rgb;\nvec3 a1=Cyy_zz*Ny+Cy;\nvec3 a2=Cyz*Nz+a1;\nvec3 b1=Czx*Nz+Cx;\nvec3 b2=Cxy*Ny+b1;\nvec3 b3=Cxx_zz*Nx+b2;\nvec3 t1=Cz*Nz+C1;\nvec3 t2=a2*Ny+t1;\nvec3 t3=b3*Nx+t2;\nreturn t3;\n}\n#endif","pbrLightFunctions":"\nstruct lightingInfo\n{\nvec3 diffuse;\n#ifdef SPECULARTERM\nvec3 specular;\n#endif\n};\nfloat computeDistanceLightFalloff(vec3 lightOffset,float lightDistanceSquared,float range)\n{ \n#ifdef USEPHYSICALLIGHTFALLOFF\nfloat lightDistanceFalloff=1.0/((lightDistanceSquared+0.001));\n#else\nfloat lightDistanceFalloff=max(0.,1.0-length(lightOffset)/range);\n#endif\nreturn lightDistanceFalloff;\n}\nfloat computeDirectionalLightFalloff(vec3 lightDirection,vec3 directionToLightCenterW,float cosHalfAngle,float exponent)\n{\nfloat falloff=0.0;\n#ifdef USEPHYSICALLIGHTFALLOFF\nconst float kMinusLog2ConeAngleIntensityRatio=6.64385618977; \n\n\n\n\n\nfloat concentrationKappa=kMinusLog2ConeAngleIntensityRatio/(1.0-cosHalfAngle);\n\n\nvec4 lightDirectionSpreadSG=vec4(-lightDirection*concentrationKappa,-concentrationKappa);\nfalloff=exp2(dot(vec4(directionToLightCenterW,1.0),lightDirectionSpreadSG));\n#else\nfloat cosAngle=max(0.000000000000001,dot(-lightDirection,directionToLightCenterW));\nif (cosAngle>=cosHalfAngle)\n{\nfalloff=max(0.,pow(cosAngle,exponent));\n}\n#endif\nreturn falloff;\n}\nlightingInfo computeLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,float rangeRadius,float roughness,float NdotV,vec3 reflectance0,vec3 reflectance90,float geometricRoughnessFactor,out float NdotL) {\nlightingInfo result;\nvec3 lightDirection;\nfloat attenuation=1.0;\nfloat lightDistance;\n\nif (lightData.w == 0.)\n{\nvec3 lightOffset=lightData.xyz-vPositionW;\nfloat lightDistanceSquared=dot(lightOffset,lightOffset);\nattenuation=computeDistanceLightFalloff(lightOffset,lightDistanceSquared,rangeRadius);\nlightDistance=sqrt(lightDistanceSquared);\nlightDirection=normalize(lightOffset);\n}\n\nelse\n{\nlightDistance=length(-lightData.xyz);\nlightDirection=normalize(-lightData.xyz);\n}\n\nroughness=adjustRoughnessFromLightProperties(roughness,rangeRadius,lightDistance);\n\nvec3 H=normalize(viewDirectionW+lightDirection);\nNdotL=clamp(dot(vNormal,lightDirection),0.00000000001,1.0);\nfloat VdotH=clamp(dot(viewDirectionW,H),0.0,1.0);\nfloat diffuseTerm=computeDiffuseTerm(NdotL,NdotV,VdotH,roughness);\nresult.diffuse=diffuseTerm*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nfloat NdotH=clamp(dot(vNormal,H),0.000000000001,1.0);\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,reflectance0,reflectance90,geometricRoughnessFactor);\nresult.specular=specTerm*diffuseColor*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeSpotLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec4 lightDirection,vec3 diffuseColor,vec3 specularColor,float rangeRadius,float roughness,float NdotV,vec3 reflectance0,vec3 reflectance90,float geometricRoughnessFactor,out float NdotL) {\nlightingInfo result;\nvec3 lightOffset=lightData.xyz-vPositionW;\nvec3 directionToLightCenterW=normalize(lightOffset);\n\nfloat lightDistanceSquared=dot(lightOffset,lightOffset);\nfloat attenuation=computeDistanceLightFalloff(lightOffset,lightDistanceSquared,rangeRadius);\n\nfloat directionalAttenuation=computeDirectionalLightFalloff(lightDirection.xyz,directionToLightCenterW,lightDirection.w,lightData.w);\nattenuation*=directionalAttenuation;\n\nfloat lightDistance=sqrt(lightDistanceSquared);\nroughness=adjustRoughnessFromLightProperties(roughness,rangeRadius,lightDistance);\n\nvec3 H=normalize(viewDirectionW+directionToLightCenterW);\nNdotL=clamp(dot(vNormal,directionToLightCenterW),0.000000000001,1.0);\nfloat VdotH=clamp(dot(viewDirectionW,H),0.0,1.0);\nfloat diffuseTerm=computeDiffuseTerm(NdotL,NdotV,VdotH,roughness);\nresult.diffuse=diffuseTerm*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nfloat NdotH=clamp(dot(vNormal,H),0.000000000001,1.0);\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,reflectance0,reflectance90,geometricRoughnessFactor);\nresult.specular=specTerm*diffuseColor*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeHemisphericLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,vec3 groundColor,float roughness,float NdotV,vec3 reflectance0,vec3 reflectance90,float geometricRoughnessFactor,out float NdotL) {\nlightingInfo result;\n\n\n\nNdotL=dot(vNormal,lightData.xyz)*0.5+0.5;\nresult.diffuse=mix(groundColor,diffuseColor,NdotL);\n#ifdef SPECULARTERM\n\nvec3 lightVectorW=normalize(lightData.xyz);\nvec3 H=normalize(viewDirectionW+lightVectorW);\nfloat NdotH=clamp(dot(vNormal,H),0.000000000001,1.0);\nNdotL=clamp(NdotL,0.000000000001,1.0);\nfloat VdotH=clamp(dot(viewDirectionW,H),0.0,1.0);\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,reflectance0,reflectance90,geometricRoughnessFactor);\nresult.specular=specTerm*diffuseColor;\n#endif\nreturn result;\n}\nvec3 computeProjectionTextureDiffuseLighting(sampler2D projectionLightSampler,mat4 textureProjectionMatrix){\nvec4 strq=textureProjectionMatrix*vec4(vPositionW,1.0);\nstrq/=strq.w;\nvec3 textureColor=texture2D(projectionLightSampler,strq.xy).rgb;\nreturn toLinearSpace(textureColor);\n}","kernelBlurFragment":"#ifdef DOF\nfactor=sampleCoC(sampleCoord{X}); \ncomputedWeight=KERNEL_WEIGHT{X}*factor;\nsumOfWeights+=computedWeight;\n#else\ncomputedWeight=KERNEL_WEIGHT{X};\n#endif\n#ifdef PACKEDFLOAT\nblend+=unpack(texture2D(textureSampler,sampleCoord{X}))*computedWeight;\n#else\nblend+=texture2D(textureSampler,sampleCoord{X})*computedWeight;\n#endif","kernelBlurFragment2":"#ifdef DOF\nfactor=sampleCoC(sampleCenter+delta*KERNEL_DEP_OFFSET{X});\ncomputedWeight=KERNEL_DEP_WEIGHT{X}*factor;\nsumOfWeights+=computedWeight;\n#else\ncomputedWeight=KERNEL_DEP_WEIGHT{X};\n#endif\n#ifdef PACKEDFLOAT\nblend+=unpack(texture2D(textureSampler,sampleCenter+delta*KERNEL_DEP_OFFSET{X}))*computedWeight;\n#else\nblend+=texture2D(textureSampler,sampleCenter+delta*KERNEL_DEP_OFFSET{X})*computedWeight;\n#endif","kernelBlurVaryingDeclaration":"varying vec2 sampleCoord{X};","kernelBlurVertex":"sampleCoord{X}=sampleCenter+delta*KERNEL_OFFSET{X};","mrtFragmentDeclaration":"#if __VERSION__>=200\nlayout(location=0) out vec4 glFragData[{X}];\n#endif\n","bones300Declaration":"#if NUM_BONE_INFLUENCERS>0\nuniform mat4 mBones[BonesPerMesh];\nin vec4 matricesIndices;\nin vec4 matricesWeights;\n#if NUM_BONE_INFLUENCERS>4\nin vec4 matricesIndicesExtra;\nin vec4 matricesWeightsExtra;\n#endif\n#endif","instances300Declaration":"#ifdef INSTANCES\nin vec4 world0;\nin vec4 world1;\nin vec4 world2;\nin vec4 world3;\n#else\nuniform mat4 world;\n#endif","backgroundVertexDeclaration":"uniform mat4 view;\nuniform mat4 viewProjection;\nuniform float shadowLevel;\n#ifdef DIFFUSE\nuniform mat4 diffuseMatrix;\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\nuniform float fFovMultiplier;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif","backgroundFragmentDeclaration":" uniform vec4 vPrimaryColor;\n#ifdef USEHIGHLIGHTANDSHADOWCOLORS\nuniform vec4 vPrimaryColorShadow;\n#endif\nuniform float shadowLevel;\nuniform float alpha;\n#ifdef DIFFUSE\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\n#endif\n#if defined(REFLECTIONFRESNEL) || defined(OPACITYFRESNEL)\nuniform vec3 vBackgroundCenter;\n#endif\n#ifdef REFLECTIONFRESNEL\nuniform vec4 vReflectionControl;\n#endif\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif","backgroundUboDeclaration":"layout(std140,column_major) uniform;\nuniform Material\n{\nuniform vec4 vPrimaryColor;\nuniform vec4 vPrimaryColorShadow;\nuniform vec2 vDiffuseInfos;\nuniform vec2 vReflectionInfos;\nuniform mat4 diffuseMatrix;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\nuniform float fFovMultiplier;\nuniform float pointSize;\nuniform float shadowLevel;\nuniform float alpha;\n#if defined(REFLECTIONFRESNEL) || defined(OPACITYFRESNEL)\nuniform vec3 vBackgroundCenter;\n#endif\n#ifdef REFLECTIONFRESNEL\nuniform vec4 vReflectionControl;\n#endif\n};\nuniform Scene {\nmat4 viewProjection;\nmat4 view;\n};"};var globalObject = (typeof global !== 'undefined') ? global : ((typeof window !== 'undefined') ? window : this);
  98762. globalObject["BABYLON"] = BABYLON;
  98763. var EffectFallbacks = BABYLON.EffectFallbacks;var EffectCreationOptions = BABYLON.EffectCreationOptions;var Effect = BABYLON.Effect;var KeyboardEventTypes = BABYLON.KeyboardEventTypes;var KeyboardInfo = BABYLON.KeyboardInfo;var KeyboardInfoPre = BABYLON.KeyboardInfoPre;var PointerEventTypes = BABYLON.PointerEventTypes;var PointerInfoBase = BABYLON.PointerInfoBase;var PointerInfoPre = BABYLON.PointerInfoPre;var PointerInfo = BABYLON.PointerInfo;var Color3 = BABYLON.Color3;var Color4 = BABYLON.Color4;var Vector2 = BABYLON.Vector2;var Vector3 = BABYLON.Vector3;var Vector4 = BABYLON.Vector4;var Size = BABYLON.Size;var Quaternion = BABYLON.Quaternion;var Matrix = BABYLON.Matrix;var Plane = BABYLON.Plane;var Viewport = BABYLON.Viewport;var Frustum = BABYLON.Frustum;var Axis = BABYLON.Axis;var BezierCurve = BABYLON.BezierCurve;var Angle = BABYLON.Angle;var Arc2 = BABYLON.Arc2;var Path2 = BABYLON.Path2;var Path3D = BABYLON.Path3D;var Curve3 = BABYLON.Curve3;var PositionNormalVertex = BABYLON.PositionNormalVertex;var PositionNormalTextureVertex = BABYLON.PositionNormalTextureVertex;var Tmp = BABYLON.Tmp;var Scalar = BABYLON.Scalar;var expandToProperty = BABYLON.expandToProperty;var serialize = BABYLON.serialize;var serializeAsTexture = BABYLON.serializeAsTexture;var serializeAsColor3 = BABYLON.serializeAsColor3;var serializeAsFresnelParameters = BABYLON.serializeAsFresnelParameters;var serializeAsVector2 = BABYLON.serializeAsVector2;var serializeAsVector3 = BABYLON.serializeAsVector3;var serializeAsMeshReference = BABYLON.serializeAsMeshReference;var serializeAsColorCurves = BABYLON.serializeAsColorCurves;var serializeAsColor4 = BABYLON.serializeAsColor4;var serializeAsImageProcessingConfiguration = BABYLON.serializeAsImageProcessingConfiguration;var serializeAsQuaternion = BABYLON.serializeAsQuaternion;var serializeAsCameraReference = BABYLON.serializeAsCameraReference;var SerializationHelper = BABYLON.SerializationHelper;var Deferred = BABYLON.Deferred;var EventState = BABYLON.EventState;var Observer = BABYLON.Observer;var MultiObserver = BABYLON.MultiObserver;var Observable = BABYLON.Observable;var SmartArray = BABYLON.SmartArray;var SmartArrayNoDuplicate = BABYLON.SmartArrayNoDuplicate;var LoadFileError = BABYLON.LoadFileError;var RetryStrategy = BABYLON.RetryStrategy;var Tools = BABYLON.Tools;var PerfCounter = BABYLON.PerfCounter;var className = BABYLON.className;var AsyncLoop = BABYLON.AsyncLoop;var PromisePolyfill = BABYLON.PromisePolyfill;var WorkerPool = BABYLON.WorkerPool;var _AlphaState = BABYLON._AlphaState;var _DepthCullingState = BABYLON._DepthCullingState;var _StencilState = BABYLON._StencilState;var InstancingAttributeInfo = BABYLON.InstancingAttributeInfo;var RenderTargetCreationOptions = BABYLON.RenderTargetCreationOptions;var DepthTextureCreationOptions = BABYLON.DepthTextureCreationOptions;var EngineCapabilities = BABYLON.EngineCapabilities;var Engine = BABYLON.Engine;var Node = BABYLON.Node;var BoundingSphere = BABYLON.BoundingSphere;var BoundingBox = BABYLON.BoundingBox;var BoundingInfo = BABYLON.BoundingInfo;var TransformNode = BABYLON.TransformNode;var AbstractMesh = BABYLON.AbstractMesh;var Light = BABYLON.Light;var Camera = BABYLON.Camera;var RenderingManager = BABYLON.RenderingManager;var RenderingGroup = BABYLON.RenderingGroup;var RenderingGroupInfo = BABYLON.RenderingGroupInfo;var Scene = BABYLON.Scene;var KeepAssets = BABYLON.KeepAssets;var AssetContainer = BABYLON.AssetContainer;var Buffer = BABYLON.Buffer;var VertexBuffer = BABYLON.VertexBuffer;var DummyInternalTextureTracker = BABYLON.DummyInternalTextureTracker;var InternalTexture = BABYLON.InternalTexture;var BaseTexture = BABYLON.BaseTexture;var Texture = BABYLON.Texture;var _InstancesBatch = BABYLON._InstancesBatch;var Mesh = BABYLON.Mesh;var BaseSubMesh = BABYLON.BaseSubMesh;var SubMesh = BABYLON.SubMesh;var MaterialDefines = BABYLON.MaterialDefines;var Material = BABYLON.Material;var UniformBuffer = BABYLON.UniformBuffer;var VertexData = BABYLON.VertexData;var Geometry = BABYLON.Geometry;var _PrimitiveGeometry = BABYLON._PrimitiveGeometry;var RibbonGeometry = BABYLON.RibbonGeometry;var BoxGeometry = BABYLON.BoxGeometry;var SphereGeometry = BABYLON.SphereGeometry;var DiscGeometry = BABYLON.DiscGeometry;var CylinderGeometry = BABYLON.CylinderGeometry;var TorusGeometry = BABYLON.TorusGeometry;var GroundGeometry = BABYLON.GroundGeometry;var TiledGroundGeometry = BABYLON.TiledGroundGeometry;var PlaneGeometry = BABYLON.PlaneGeometry;var TorusKnotGeometry = BABYLON.TorusKnotGeometry;var PostProcessManager = BABYLON.PostProcessManager;var PerformanceMonitor = BABYLON.PerformanceMonitor;var RollingAverage = BABYLON.RollingAverage;var ImageProcessingConfiguration = BABYLON.ImageProcessingConfiguration;var ColorGradingTexture = BABYLON.ColorGradingTexture;var ColorCurves = BABYLON.ColorCurves;var MaterialHelper = BABYLON.MaterialHelper;var PushMaterial = BABYLON.PushMaterial;var StandardMaterialDefines = BABYLON.StandardMaterialDefines;var StandardMaterial = BABYLON.StandardMaterial;var PBRBaseMaterial = BABYLON.PBRBaseMaterial;var PBRBaseSimpleMaterial = BABYLON.PBRBaseSimpleMaterial;var PBRMaterial = BABYLON.PBRMaterial;var PBRMetallicRoughnessMaterial = BABYLON.PBRMetallicRoughnessMaterial;var PBRSpecularGlossinessMaterial = BABYLON.PBRSpecularGlossinessMaterial;var CameraInputsManager = BABYLON.CameraInputsManager;var TargetCamera = BABYLON.TargetCamera;var FreeCameraMouseInput = BABYLON.FreeCameraMouseInput;var FreeCameraKeyboardMoveInput = BABYLON.FreeCameraKeyboardMoveInput;var FreeCameraInputsManager = BABYLON.FreeCameraInputsManager;var FreeCamera = BABYLON.FreeCamera;var ArcRotateCameraKeyboardMoveInput = BABYLON.ArcRotateCameraKeyboardMoveInput;var ArcRotateCameraMouseWheelInput = BABYLON.ArcRotateCameraMouseWheelInput;var ArcRotateCameraPointersInput = BABYLON.ArcRotateCameraPointersInput;var ArcRotateCameraInputsManager = BABYLON.ArcRotateCameraInputsManager;var ArcRotateCamera = BABYLON.ArcRotateCamera;var HemisphericLight = BABYLON.HemisphericLight;var ShadowLight = BABYLON.ShadowLight;var PointLight = BABYLON.PointLight;var DirectionalLight = BABYLON.DirectionalLight;var SpotLight = BABYLON.SpotLight;var AnimationPropertiesOverride = BABYLON.AnimationPropertiesOverride;var AnimationRange = BABYLON.AnimationRange;var AnimationEvent = BABYLON.AnimationEvent;var PathCursor = BABYLON.PathCursor;var Animation = BABYLON.Animation;var TargetedAnimation = BABYLON.TargetedAnimation;var AnimationGroup = BABYLON.AnimationGroup;var RuntimeAnimation = BABYLON.RuntimeAnimation;var Animatable = BABYLON.Animatable;var EasingFunction = BABYLON.EasingFunction;var CircleEase = BABYLON.CircleEase;var BackEase = BABYLON.BackEase;var BounceEase = BABYLON.BounceEase;var CubicEase = BABYLON.CubicEase;var ElasticEase = BABYLON.ElasticEase;var ExponentialEase = BABYLON.ExponentialEase;var PowerEase = BABYLON.PowerEase;var QuadraticEase = BABYLON.QuadraticEase;var QuarticEase = BABYLON.QuarticEase;var QuinticEase = BABYLON.QuinticEase;var SineEase = BABYLON.SineEase;var BezierCurveEase = BABYLON.BezierCurveEase;var Condition = BABYLON.Condition;var ValueCondition = BABYLON.ValueCondition;var PredicateCondition = BABYLON.PredicateCondition;var StateCondition = BABYLON.StateCondition;var Action = BABYLON.Action;var ActionEvent = BABYLON.ActionEvent;var ActionManager = BABYLON.ActionManager;var InterpolateValueAction = BABYLON.InterpolateValueAction;var SwitchBooleanAction = BABYLON.SwitchBooleanAction;var SetStateAction = BABYLON.SetStateAction;var SetValueAction = BABYLON.SetValueAction;var IncrementValueAction = BABYLON.IncrementValueAction;var PlayAnimationAction = BABYLON.PlayAnimationAction;var StopAnimationAction = BABYLON.StopAnimationAction;var DoNothingAction = BABYLON.DoNothingAction;var CombineAction = BABYLON.CombineAction;var ExecuteCodeAction = BABYLON.ExecuteCodeAction;var SetParentAction = BABYLON.SetParentAction;var PlaySoundAction = BABYLON.PlaySoundAction;var StopSoundAction = BABYLON.StopSoundAction;var SpriteManager = BABYLON.SpriteManager;var Sprite = BABYLON.Sprite;var IntersectionInfo = BABYLON.IntersectionInfo;var PickingInfo = BABYLON.PickingInfo;var Ray = BABYLON.Ray;var Collider = BABYLON.Collider;var CollisionCoordinatorWorker = BABYLON.CollisionCoordinatorWorker;var CollisionCoordinatorLegacy = BABYLON.CollisionCoordinatorLegacy;var Particle = BABYLON.Particle;var ParticleSystem = BABYLON.ParticleSystem;var BoxParticleEmitter = BABYLON.BoxParticleEmitter;var ConeParticleEmitter = BABYLON.ConeParticleEmitter;var SphereParticleEmitter = BABYLON.SphereParticleEmitter;var SphereDirectedParticleEmitter = BABYLON.SphereDirectedParticleEmitter;var GPUParticleSystem = BABYLON.GPUParticleSystem;var SolidParticle = BABYLON.SolidParticle;var ModelShape = BABYLON.ModelShape;var DepthSortedParticle = BABYLON.DepthSortedParticle;var SolidParticleSystem = BABYLON.SolidParticleSystem;var ShaderMaterial = BABYLON.ShaderMaterial;var GroundMesh = BABYLON.GroundMesh;var InstancedMesh = BABYLON.InstancedMesh;var LinesMesh = BABYLON.LinesMesh;var MeshBuilder = BABYLON.MeshBuilder;var DracoCompression = BABYLON.DracoCompression;var AudioEngine = BABYLON.AudioEngine;var Sound = BABYLON.Sound;var SoundTrack = BABYLON.SoundTrack;var Analyser = BABYLON.Analyser;var CubeTexture = BABYLON.CubeTexture;var RenderTargetTexture = BABYLON.RenderTargetTexture;var MultiRenderTarget = BABYLON.MultiRenderTarget;var MirrorTexture = BABYLON.MirrorTexture;var RefractionTexture = BABYLON.RefractionTexture;var DynamicTexture = BABYLON.DynamicTexture;var VideoTexture = BABYLON.VideoTexture;var RawTexture = BABYLON.RawTexture;var RawTexture3D = BABYLON.RawTexture3D;var PostProcess = BABYLON.PostProcess;var PassPostProcess = BABYLON.PassPostProcess;var ShadowGenerator = BABYLON.ShadowGenerator;var DefaultLoadingScreen = BABYLON.DefaultLoadingScreen;var SceneLoaderProgressEvent = BABYLON.SceneLoaderProgressEvent;var SceneLoader = BABYLON.SceneLoader;var FilesInput = BABYLON.FilesInput;var StringDictionary = BABYLON.StringDictionary;var Tags = BABYLON.Tags;var AndOrNotEvaluator = BABYLON.AndOrNotEvaluator;var Database = BABYLON.Database;var FresnelParameters = BABYLON.FresnelParameters;var MultiMaterial = BABYLON.MultiMaterial;var FreeCameraTouchInput = BABYLON.FreeCameraTouchInput;var TouchCamera = BABYLON.TouchCamera;var ProceduralTexture = BABYLON.ProceduralTexture;var CustomProceduralTexture = BABYLON.CustomProceduralTexture;var FreeCameraGamepadInput = BABYLON.FreeCameraGamepadInput;var ArcRotateCameraGamepadInput = BABYLON.ArcRotateCameraGamepadInput;var GamepadManager = BABYLON.GamepadManager;var StickValues = BABYLON.StickValues;var Gamepad = BABYLON.Gamepad;var GenericPad = BABYLON.GenericPad;var Xbox360Pad = BABYLON.Xbox360Pad;var PoseEnabledControllerHelper = BABYLON.PoseEnabledControllerHelper;var PoseEnabledController = BABYLON.PoseEnabledController;var WebVRController = BABYLON.WebVRController;var OculusTouchController = BABYLON.OculusTouchController;var ViveController = BABYLON.ViveController;var GenericController = BABYLON.GenericController;var WindowsMotionController = BABYLON.WindowsMotionController;var GearVRController = BABYLON.GearVRController;var DaydreamController = BABYLON.DaydreamController;var FollowCamera = BABYLON.FollowCamera;var ArcFollowCamera = BABYLON.ArcFollowCamera;var UniversalCamera = BABYLON.UniversalCamera;var GamepadCamera = BABYLON.GamepadCamera;var PostProcessRenderPipelineManager = BABYLON.PostProcessRenderPipelineManager;var PostProcessRenderEffect = BABYLON.PostProcessRenderEffect;var PostProcessRenderPipeline = BABYLON.PostProcessRenderPipeline;var DepthRenderer = BABYLON.DepthRenderer;var SSAORenderingPipeline = BABYLON.SSAORenderingPipeline;var SSAO2RenderingPipeline = BABYLON.SSAO2RenderingPipeline;var LensRenderingPipeline = BABYLON.LensRenderingPipeline;var StandardRenderingPipeline = BABYLON.StandardRenderingPipeline;var FxaaPostProcess = BABYLON.FxaaPostProcess;var ChromaticAberrationPostProcess = BABYLON.ChromaticAberrationPostProcess;var GrainPostProcess = BABYLON.GrainPostProcess;var SharpenPostProcess = BABYLON.SharpenPostProcess;var BlurPostProcess = BABYLON.BlurPostProcess;var DepthOfFieldBlurPostProcess = BABYLON.DepthOfFieldBlurPostProcess;var DepthOfFieldMergePostProcessOptions = BABYLON.DepthOfFieldMergePostProcessOptions;var DepthOfFieldMergePostProcess = BABYLON.DepthOfFieldMergePostProcess;var CircleOfConfusionPostProcess = BABYLON.CircleOfConfusionPostProcess;var DepthOfFieldEffect = BABYLON.DepthOfFieldEffect;var BloomMergePostProcess = BABYLON.BloomMergePostProcess;var ExtractHighlightsPostProcess = BABYLON.ExtractHighlightsPostProcess;var BloomEffect = BABYLON.BloomEffect;var DefaultRenderingPipeline = BABYLON.DefaultRenderingPipeline;var GeometryBufferRenderer = BABYLON.GeometryBufferRenderer;var RefractionPostProcess = BABYLON.RefractionPostProcess;var BlackAndWhitePostProcess = BABYLON.BlackAndWhitePostProcess;var ConvolutionPostProcess = BABYLON.ConvolutionPostProcess;var FilterPostProcess = BABYLON.FilterPostProcess;var VolumetricLightScatteringPostProcess = BABYLON.VolumetricLightScatteringPostProcess;var ColorCorrectionPostProcess = BABYLON.ColorCorrectionPostProcess;var TonemapPostProcess = BABYLON.TonemapPostProcess;var DisplayPassPostProcess = BABYLON.DisplayPassPostProcess;var HighlightsPostProcess = BABYLON.HighlightsPostProcess;var ImageProcessingPostProcess = BABYLON.ImageProcessingPostProcess;var Bone = BABYLON.Bone;var BoneIKController = BABYLON.BoneIKController;var BoneLookController = BABYLON.BoneLookController;var Skeleton = BABYLON.Skeleton;var SphericalPolynomial = BABYLON.SphericalPolynomial;var SphericalHarmonics = BABYLON.SphericalHarmonics;var CubeMapToSphericalPolynomialTools = BABYLON.CubeMapToSphericalPolynomialTools;var PanoramaToCubeMapTools = BABYLON.PanoramaToCubeMapTools;var HDRTools = BABYLON.HDRTools;var HDRCubeTexture = BABYLON.HDRCubeTexture;var Polygon = BABYLON.Polygon;var PolygonMeshBuilder = BABYLON.PolygonMeshBuilder;var CSG = BABYLON.CSG;var LensFlare = BABYLON.LensFlare;var LensFlareSystem = BABYLON.LensFlareSystem;var PhysicsJoint = BABYLON.PhysicsJoint;var DistanceJoint = BABYLON.DistanceJoint;var MotorEnabledJoint = BABYLON.MotorEnabledJoint;var HingeJoint = BABYLON.HingeJoint;var Hinge2Joint = BABYLON.Hinge2Joint;var PhysicsImpostor = BABYLON.PhysicsImpostor;var PhysicsEngine = BABYLON.PhysicsEngine;var PhysicsHelper = BABYLON.PhysicsHelper;var PhysicsRadialExplosionEvent = BABYLON.PhysicsRadialExplosionEvent;var PhysicsGravitationalFieldEvent = BABYLON.PhysicsGravitationalFieldEvent;var PhysicsUpdraftEvent = BABYLON.PhysicsUpdraftEvent;var PhysicsVortexEvent = BABYLON.PhysicsVortexEvent;var CannonJSPlugin = BABYLON.CannonJSPlugin;var OimoJSPlugin = BABYLON.OimoJSPlugin;var TGATools = BABYLON.TGATools;var DDSTools = BABYLON.DDSTools;var KhronosTextureContainer = BABYLON.KhronosTextureContainer;var RayHelper = BABYLON.RayHelper;var DebugLayer = BABYLON.DebugLayer;var BoundingBoxRenderer = BABYLON.BoundingBoxRenderer;var UtilityLayerRenderer = BABYLON.UtilityLayerRenderer;var Gizmo = BABYLON.Gizmo;var AxisDragGizmo = BABYLON.AxisDragGizmo;var PositionGizmo = BABYLON.PositionGizmo;var MorphTarget = BABYLON.MorphTarget;var MorphTargetManager = BABYLON.MorphTargetManager;var Octree = BABYLON.Octree;var OctreeBlock = BABYLON.OctreeBlock;var VRDistortionCorrectionPostProcess = BABYLON.VRDistortionCorrectionPostProcess;var AnaglyphPostProcess = BABYLON.AnaglyphPostProcess;var StereoscopicInterlacePostProcess = BABYLON.StereoscopicInterlacePostProcess;var FreeCameraDeviceOrientationInput = BABYLON.FreeCameraDeviceOrientationInput;var ArcRotateCameraVRDeviceOrientationInput = BABYLON.ArcRotateCameraVRDeviceOrientationInput;var VRCameraMetrics = BABYLON.VRCameraMetrics;var WebVRFreeCamera = BABYLON.WebVRFreeCamera;var DeviceOrientationCamera = BABYLON.DeviceOrientationCamera;var VRDeviceOrientationFreeCamera = BABYLON.VRDeviceOrientationFreeCamera;var VRDeviceOrientationGamepadCamera = BABYLON.VRDeviceOrientationGamepadCamera;var VRDeviceOrientationArcRotateCamera = BABYLON.VRDeviceOrientationArcRotateCamera;var AnaglyphFreeCamera = BABYLON.AnaglyphFreeCamera;var AnaglyphArcRotateCamera = BABYLON.AnaglyphArcRotateCamera;var AnaglyphGamepadCamera = BABYLON.AnaglyphGamepadCamera;var AnaglyphUniversalCamera = BABYLON.AnaglyphUniversalCamera;var StereoscopicFreeCamera = BABYLON.StereoscopicFreeCamera;var StereoscopicArcRotateCamera = BABYLON.StereoscopicArcRotateCamera;var StereoscopicGamepadCamera = BABYLON.StereoscopicGamepadCamera;var StereoscopicUniversalCamera = BABYLON.StereoscopicUniversalCamera;var VRExperienceHelper = BABYLON.VRExperienceHelper;var VirtualJoystick = BABYLON.VirtualJoystick;var VirtualJoysticksCamera = BABYLON.VirtualJoysticksCamera;var FreeCameraVirtualJoystickInput = BABYLON.FreeCameraVirtualJoystickInput;var SimplificationSettings = BABYLON.SimplificationSettings;var SimplificationQueue = BABYLON.SimplificationQueue;var DecimationTriangle = BABYLON.DecimationTriangle;var DecimationVertex = BABYLON.DecimationVertex;var QuadraticMatrix = BABYLON.QuadraticMatrix;var Reference = BABYLON.Reference;var QuadraticErrorSimplification = BABYLON.QuadraticErrorSimplification;var MeshLODLevel = BABYLON.MeshLODLevel;var SceneOptimization = BABYLON.SceneOptimization;var TextureOptimization = BABYLON.TextureOptimization;var HardwareScalingOptimization = BABYLON.HardwareScalingOptimization;var ShadowsOptimization = BABYLON.ShadowsOptimization;var PostProcessesOptimization = BABYLON.PostProcessesOptimization;var LensFlaresOptimization = BABYLON.LensFlaresOptimization;var CustomOptimization = BABYLON.CustomOptimization;var ParticlesOptimization = BABYLON.ParticlesOptimization;var RenderTargetsOptimization = BABYLON.RenderTargetsOptimization;var MergeMeshesOptimization = BABYLON.MergeMeshesOptimization;var SceneOptimizerOptions = BABYLON.SceneOptimizerOptions;var SceneOptimizer = BABYLON.SceneOptimizer;var OutlineRenderer = BABYLON.OutlineRenderer;var EdgesRenderer = BABYLON.EdgesRenderer;var EffectLayer = BABYLON.EffectLayer;var HighlightLayer = BABYLON.HighlightLayer;var GlowLayer = BABYLON.GlowLayer;var AbstractAssetTask = BABYLON.AbstractAssetTask;var AssetsProgressEvent = BABYLON.AssetsProgressEvent;var MeshAssetTask = BABYLON.MeshAssetTask;var TextFileAssetTask = BABYLON.TextFileAssetTask;var BinaryFileAssetTask = BABYLON.BinaryFileAssetTask;var ImageAssetTask = BABYLON.ImageAssetTask;var TextureAssetTask = BABYLON.TextureAssetTask;var CubeTextureAssetTask = BABYLON.CubeTextureAssetTask;var HDRCubeTextureAssetTask = BABYLON.HDRCubeTextureAssetTask;var AssetsManager = BABYLON.AssetsManager;var SceneSerializer = BABYLON.SceneSerializer;var ReflectionProbe = BABYLON.ReflectionProbe;var Layer = BABYLON.Layer;var TextureTools = BABYLON.TextureTools;var FramingBehavior = BABYLON.FramingBehavior;var BouncingBehavior = BABYLON.BouncingBehavior;var AutoRotationBehavior = BABYLON.AutoRotationBehavior;var PointerDragBehavior = BABYLON.PointerDragBehavior;var NullEngineOptions = BABYLON.NullEngineOptions;var NullEngine = BABYLON.NullEngine;var EngineInstrumentation = BABYLON.EngineInstrumentation;var SceneInstrumentation = BABYLON.SceneInstrumentation;var _TimeToken = BABYLON._TimeToken;var BackgroundMaterial = BABYLON.BackgroundMaterial;var EnvironmentHelper = BABYLON.EnvironmentHelper;var ParticleHelper = BABYLON.ParticleHelper;var VideoDome = BABYLON.VideoDome;var Space = BABYLON.Space ;var Orientation = BABYLON.Orientation ;var AnimationKeyInterpolation = BABYLON.AnimationKeyInterpolation ;var WorkerTaskType = BABYLON.WorkerTaskType ;var WorkerReplyType = BABYLON.WorkerReplyType ;var Xbox360Button = BABYLON.Xbox360Button ;var Xbox360Dpad = BABYLON.Xbox360Dpad ;var PoseEnabledControllerType = BABYLON.PoseEnabledControllerType ;var DepthOfFieldEffectBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel ;var TonemappingOperator = BABYLON.TonemappingOperator ;var PhysicsRadialImpulseFalloff = BABYLON.PhysicsRadialImpulseFalloff ;var PhysicsUpdraftMode = BABYLON.PhysicsUpdraftMode ;var Debug = BABYLON.Debug ;var JoystickAxis = BABYLON.JoystickAxis ;var SimplificationType = BABYLON.SimplificationType ;var AssetTaskState = BABYLON.AssetTaskState ;
  98764. export { EffectFallbacks,EffectCreationOptions,Effect,KeyboardEventTypes,KeyboardInfo,KeyboardInfoPre,PointerEventTypes,PointerInfoBase,PointerInfoPre,PointerInfo,Color3,Color4,Vector2,Vector3,Vector4,Size,Quaternion,Matrix,Plane,Viewport,Frustum,Axis,BezierCurve,Angle,Arc2,Path2,Path3D,Curve3,PositionNormalVertex,PositionNormalTextureVertex,Tmp,Scalar,expandToProperty,serialize,serializeAsTexture,serializeAsColor3,serializeAsFresnelParameters,serializeAsVector2,serializeAsVector3,serializeAsMeshReference,serializeAsColorCurves,serializeAsColor4,serializeAsImageProcessingConfiguration,serializeAsQuaternion,serializeAsCameraReference,SerializationHelper,Deferred,EventState,Observer,MultiObserver,Observable,SmartArray,SmartArrayNoDuplicate,LoadFileError,RetryStrategy,Tools,PerfCounter,className,AsyncLoop,PromisePolyfill,WorkerPool,_AlphaState,_DepthCullingState,_StencilState,InstancingAttributeInfo,RenderTargetCreationOptions,DepthTextureCreationOptions,EngineCapabilities,Engine,Node,BoundingSphere,BoundingBox,BoundingInfo,TransformNode,AbstractMesh,Light,Camera,RenderingManager,RenderingGroup,RenderingGroupInfo,Scene,KeepAssets,AssetContainer,Buffer,VertexBuffer,DummyInternalTextureTracker,InternalTexture,BaseTexture,Texture,_InstancesBatch,Mesh,BaseSubMesh,SubMesh,MaterialDefines,Material,UniformBuffer,VertexData,Geometry,_PrimitiveGeometry,RibbonGeometry,BoxGeometry,SphereGeometry,DiscGeometry,CylinderGeometry,TorusGeometry,GroundGeometry,TiledGroundGeometry,PlaneGeometry,TorusKnotGeometry,PostProcessManager,PerformanceMonitor,RollingAverage,ImageProcessingConfiguration,ColorGradingTexture,ColorCurves,MaterialHelper,PushMaterial,StandardMaterialDefines,StandardMaterial,PBRBaseMaterial,PBRBaseSimpleMaterial,PBRMaterial,PBRMetallicRoughnessMaterial,PBRSpecularGlossinessMaterial,CameraInputsManager,TargetCamera,FreeCameraMouseInput,FreeCameraKeyboardMoveInput,FreeCameraInputsManager,FreeCamera,ArcRotateCameraKeyboardMoveInput,ArcRotateCameraMouseWheelInput,ArcRotateCameraPointersInput,ArcRotateCameraInputsManager,ArcRotateCamera,HemisphericLight,ShadowLight,PointLight,DirectionalLight,SpotLight,AnimationPropertiesOverride,AnimationRange,AnimationEvent,PathCursor,Animation,TargetedAnimation,AnimationGroup,RuntimeAnimation,Animatable,EasingFunction,CircleEase,BackEase,BounceEase,CubicEase,ElasticEase,ExponentialEase,PowerEase,QuadraticEase,QuarticEase,QuinticEase,SineEase,BezierCurveEase,Condition,ValueCondition,PredicateCondition,StateCondition,Action,ActionEvent,ActionManager,InterpolateValueAction,SwitchBooleanAction,SetStateAction,SetValueAction,IncrementValueAction,PlayAnimationAction,StopAnimationAction,DoNothingAction,CombineAction,ExecuteCodeAction,SetParentAction,PlaySoundAction,StopSoundAction,SpriteManager,Sprite,IntersectionInfo,PickingInfo,Ray,Collider,CollisionCoordinatorWorker,CollisionCoordinatorLegacy,Particle,ParticleSystem,BoxParticleEmitter,ConeParticleEmitter,SphereParticleEmitter,SphereDirectedParticleEmitter,GPUParticleSystem,SolidParticle,ModelShape,DepthSortedParticle,SolidParticleSystem,ShaderMaterial,GroundMesh,InstancedMesh,LinesMesh,MeshBuilder,DracoCompression,AudioEngine,Sound,SoundTrack,Analyser,CubeTexture,RenderTargetTexture,MultiRenderTarget,MirrorTexture,RefractionTexture,DynamicTexture,VideoTexture,RawTexture,RawTexture3D,PostProcess,PassPostProcess,ShadowGenerator,DefaultLoadingScreen,SceneLoaderProgressEvent,SceneLoader,FilesInput,StringDictionary,Tags,AndOrNotEvaluator,Database,FresnelParameters,MultiMaterial,FreeCameraTouchInput,TouchCamera,ProceduralTexture,CustomProceduralTexture,FreeCameraGamepadInput,ArcRotateCameraGamepadInput,GamepadManager,StickValues,Gamepad,GenericPad,Xbox360Pad,PoseEnabledControllerHelper,PoseEnabledController,WebVRController,OculusTouchController,ViveController,GenericController,WindowsMotionController,GearVRController,DaydreamController,FollowCamera,ArcFollowCamera,UniversalCamera,GamepadCamera,PostProcessRenderPipelineManager,PostProcessRenderEffect,PostProcessRenderPipeline,DepthRenderer,SSAORenderingPipeline,SSAO2RenderingPipeline,LensRenderingPipeline,StandardRenderingPipeline,FxaaPostProcess,ChromaticAberrationPostProcess,GrainPostProcess,SharpenPostProcess,BlurPostProcess,DepthOfFieldBlurPostProcess,DepthOfFieldMergePostProcessOptions,DepthOfFieldMergePostProcess,CircleOfConfusionPostProcess,DepthOfFieldEffect,BloomMergePostProcess,ExtractHighlightsPostProcess,BloomEffect,DefaultRenderingPipeline,GeometryBufferRenderer,RefractionPostProcess,BlackAndWhitePostProcess,ConvolutionPostProcess,FilterPostProcess,VolumetricLightScatteringPostProcess,ColorCorrectionPostProcess,TonemapPostProcess,DisplayPassPostProcess,HighlightsPostProcess,ImageProcessingPostProcess,Bone,BoneIKController,BoneLookController,Skeleton,SphericalPolynomial,SphericalHarmonics,CubeMapToSphericalPolynomialTools,PanoramaToCubeMapTools,HDRTools,HDRCubeTexture,Polygon,PolygonMeshBuilder,CSG,LensFlare,LensFlareSystem,PhysicsJoint,DistanceJoint,MotorEnabledJoint,HingeJoint,Hinge2Joint,PhysicsImpostor,PhysicsEngine,PhysicsHelper,PhysicsRadialExplosionEvent,PhysicsGravitationalFieldEvent,PhysicsUpdraftEvent,PhysicsVortexEvent,CannonJSPlugin,OimoJSPlugin,TGATools,DDSTools,KhronosTextureContainer,RayHelper,DebugLayer,BoundingBoxRenderer,UtilityLayerRenderer,Gizmo,AxisDragGizmo,PositionGizmo,MorphTarget,MorphTargetManager,Octree,OctreeBlock,VRDistortionCorrectionPostProcess,AnaglyphPostProcess,StereoscopicInterlacePostProcess,FreeCameraDeviceOrientationInput,ArcRotateCameraVRDeviceOrientationInput,VRCameraMetrics,WebVRFreeCamera,DeviceOrientationCamera,VRDeviceOrientationFreeCamera,VRDeviceOrientationGamepadCamera,VRDeviceOrientationArcRotateCamera,AnaglyphFreeCamera,AnaglyphArcRotateCamera,AnaglyphGamepadCamera,AnaglyphUniversalCamera,StereoscopicFreeCamera,StereoscopicArcRotateCamera,StereoscopicGamepadCamera,StereoscopicUniversalCamera,VRExperienceHelper,VirtualJoystick,VirtualJoysticksCamera,FreeCameraVirtualJoystickInput,SimplificationSettings,SimplificationQueue,DecimationTriangle,DecimationVertex,QuadraticMatrix,Reference,QuadraticErrorSimplification,MeshLODLevel,SceneOptimization,TextureOptimization,HardwareScalingOptimization,ShadowsOptimization,PostProcessesOptimization,LensFlaresOptimization,CustomOptimization,ParticlesOptimization,RenderTargetsOptimization,MergeMeshesOptimization,SceneOptimizerOptions,SceneOptimizer,OutlineRenderer,EdgesRenderer,EffectLayer,HighlightLayer,GlowLayer,AbstractAssetTask,AssetsProgressEvent,MeshAssetTask,TextFileAssetTask,BinaryFileAssetTask,ImageAssetTask,TextureAssetTask,CubeTextureAssetTask,HDRCubeTextureAssetTask,AssetsManager,SceneSerializer,ReflectionProbe,Layer,TextureTools,FramingBehavior,BouncingBehavior,AutoRotationBehavior,PointerDragBehavior,NullEngineOptions,NullEngine,EngineInstrumentation,SceneInstrumentation,_TimeToken,BackgroundMaterial,EnvironmentHelper,ParticleHelper,VideoDome,Space ,Orientation ,AnimationKeyInterpolation ,WorkerTaskType ,WorkerReplyType ,Xbox360Button ,Xbox360Dpad ,PoseEnabledControllerType ,DepthOfFieldEffectBlurLevel ,TonemappingOperator ,PhysicsRadialImpulseFalloff ,PhysicsUpdraftMode ,Debug ,JoystickAxis ,SimplificationType ,AssetTaskState };